blob: 0627d918d39a0339d9febcb99b8bd5ece9409be4 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700399 // Propagate device availability to Engine
400 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200401
Eric Laurent0dd51852019-04-19 18:18:58 -0700402 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 mAvailableInputDevices.remove(device);
406
jiabinc0048632023-04-27 22:04:31 +0000407 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100408
409 mHwModules.cleanUpForDevice(device);
410
Eric Laurentd4692962014-05-05 18:13:44 -0700411 return INVALID_OPERATION;
412 }
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700415
416 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700417 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700418 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return INVALID_OPERATION;
421 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700422
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
jiabinc0048632023-04-27 22:04:31 +0000425 // Notify the HAL to prepare to disconnect device
426 broadcastDeviceConnectionState(
427 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
François Gaffie11d30102018-11-02 16:09:09 +0100429 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700430
431 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432
jiabinc0048632023-04-27 22:04:31 +0000433 // Set Disconnect to HALs
434 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
435
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436 // remove device from mReportedFormatsMap cache
437 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700438
439 // Propagate device availability to Engine
440 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700441 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700442
443 default:
François Gaffie11d30102018-11-02 16:09:09 +0100444 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return BAD_VALUE;
446 }
447
Eric Laurent0dd51852019-04-19 18:18:58 -0700448 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700449 // As the input device list can impact the output device selection, update
450 // getDeviceForStrategy() cache
451 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700452
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100453 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200454 // Reconnect Audio Source
455 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
456 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
457 checkAudioSourceForAttributes(attributes);
458 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700459 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100460 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700461 }
462
Eric Laurentb52c1522014-05-20 11:27:36 -0700463 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700465 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700466
François Gaffie11d30102018-11-02 16:09:09 +0100467 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return BAD_VALUE;
469}
470
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100471status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
472 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800473 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700474 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
475 devDescr->setName(device_name);
476 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100477}
478
Eric Laurent736a1022019-03-27 18:28:46 -0700479void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
480 audio_policy_dev_state_t state) {
481
482 // the Engine does not have to know about remote submix devices used by dynamic audio policies
483 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
484 return;
485 }
486 mEngine->setDeviceConnectionState(device, state);
487}
488
489
Eric Laurente0720872014-03-11 09:30:41 -0700490audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100491 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700492{
Eric Laurent634b7142016-04-20 13:48:02 -0700493 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
495 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700496 (strlen(device_address) != 0)/*matchAddress*/);
497
498 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100499 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700500 device, device_address);
501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
502 }
François Gaffie53615e22015-03-19 09:24:12 +0100503
Eric Laurent3a4311c2014-03-17 12:00:47 -0700504 DeviceVector *deviceVector;
505
Eric Laurente552edb2014-03-10 17:42:56 -0700506 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700507 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700508 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 deviceVector = &mAvailableInputDevices;
510 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100511 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 }
Eric Laurent634b7142016-04-20 13:48:02 -0700514
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 return (deviceVector->getDevice(
516 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800518}
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
521 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 const char *device_name,
523 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
526 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800528 // connect/disconnect only 1 device at a time
529 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
530
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700532 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534 // Nothing to do: device is not connected
535 return NO_ERROR;
536 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700539 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 // configure codecs.
541 // Handle two specific cases by sending a set parameter to
542 // configure A2DP codecs. No need to toggle device state.
543 // Case 1: A2DP active device switches from primary to primary
544 // module
545 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100546 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700547 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
549 if (availablePrimaryOutputDevices().contains(devDesc) &&
550 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 bool isA2dp = audio_is_a2dp_out_device(device);
552 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
553 : String8(AudioParameter::keyReconfigLeSupported);
554 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800555 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 int isReconfigSupported;
557 repliedParameters.getInt(supportKey, isReconfigSupported);
558 if (isReconfigSupported) {
559 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
560 : String8(AudioParameter::keyReconfigLe);
561 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800562 param.add(key, String8("true"));
563 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
564 devDesc->setEncodedFormat(encodedFormat);
565 return NO_ERROR;
566 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700567 }
568 }
cnx421bd2dcc42020-07-11 14:58:44 +0800569 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000570 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800571 for (size_t i = 0; i < mOutputs.size(); i++) {
572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000573 // mute media strategies to avoid sending the music tail into
574 // the earpiece or headset.
575 if (desc->isStrategyActive(musicStrategy)) {
576 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
577 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
578 tempRecommendedMuteDuration : desc->latency() * 4;
579 if (muteWaitMs < tempMuteDurationMs) {
580 muteWaitMs = tempMuteDurationMs;
581 }
582 }
cnx421bd2dcc42020-07-11 14:58:44 +0800583 setStrategyMute(musicStrategy, true, desc);
584 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
585 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
586 nullptr, true /*fromCache*/).types());
587 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000588 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
589 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
590 // happens after the actual device switch.
591 if (muteWaitMs > 0) {
592 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
593 usleep(muteWaitMs * 1000);
594 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800595 // Toggle the device state: UNAVAILABLE -> AVAILABLE
596 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100597 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800599 device_address, device_name,
600 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800601 if (status != NO_ERROR) {
602 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
603 status);
604 return status;
605 }
606
607 status = setDeviceConnectionState(device,
608 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800609 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800610 if (status != NO_ERROR) {
611 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
612 status);
613 return status;
614 }
615
616 return NO_ERROR;
617}
618
Pattydd807582021-11-04 21:01:03 +0800619status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
620 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800621{
Pattydd807582021-11-04 21:01:03 +0800622 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800623 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 std::unordered_set<audio_format_t> formatSet;
625 sp<HwModule> primaryModule =
626 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700627 if (primaryModule == nullptr) {
628 ALOGE("%s() unable to get primary module", __func__);
629 return NO_INIT;
630 }
Pattydd807582021-11-04 21:01:03 +0800631
632 DeviceTypeSet audioDeviceSet;
633
634 switch(device) {
635 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
636 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
637 break;
638 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800639 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
640 break;
641 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
642 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800643 break;
644 default:
645 ALOGE("%s() device type 0x%08x not supported", __func__, device);
646 return BAD_VALUE;
647 }
648
jiabin9a3361e2019-10-01 09:38:30 -0700649 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800650 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800651 for (const auto& device : declaredDevices) {
652 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800653 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800654 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800655 return status;
656}
657
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
659{
660 DeviceVector rxSinkdevices{};
661 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
662 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
663 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
664 auto rxSinkDevice = rxSinkdevices.itemAt(0);
665 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
666 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
667 // retrieve Rx Source device descriptor
668 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
669 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
670
671 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
672 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
673 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
674 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
675 return DeviceVector(rxSinkDevice);
676 }
677 }
678 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
679 // the device returned is not necessarily reachable via this output
680 // (filter later by setOutputDevices())
681 return getNewOutputDevices(mPrimaryOutput, fromCache);
682}
683
684status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
685{
François Gaffiedb1755b2023-09-01 11:50:35 +0200686 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100687 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
688 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
689 }
690 return INVALID_OPERATION;
691}
692
693status_t AudioPolicyManager::updateCallRoutingInternal(
694 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695{
696 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100697 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700698 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200699 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700700 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700702 }
François Gaffie11d30102018-11-02 16:09:09 +0100703
Francois Gaffie716e1432019-01-14 16:58:59 +0100704 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100705 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200706
707 disconnectTelephonyAudioSource(mCallRxSourceClient);
708 disconnectTelephonyAudioSource(mCallTxSourceClient);
709
710 if (rxDevices.isEmpty()) {
711 ALOGW("%s() no selected output device", __func__);
712 return INVALID_OPERATION;
713 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000714 if (txSourceDevice == nullptr) {
715 ALOGE("%s() selected input device not available", __func__);
716 return INVALID_OPERATION;
717 }
François Gaffiec005e562018-11-06 15:04:49 +0100718
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100719 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100720 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700721
François Gaffie9eb18552018-11-05 10:33:26 +0100722 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700723 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100724 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700725 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100726 // retrieve Rx Source and Tx Sink device descriptors
727 sp<DeviceDescriptor> rxSourceDevice =
728 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731 sp<DeviceDescriptor> txSinkDevice =
732 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735
736 // RX and TX Telephony device are declared by Primary Audio HAL
737 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
738 (telephonyRxModule->getHalVersionMajor() >= 3)) {
739 if (rxSourceDevice == 0 || txSinkDevice == 0) {
740 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100741 ALOGE("%s() no telephony Tx and/or RX device", __func__);
742 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100743 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100744 // createAudioPatchInternal now supports both HW / SW bridging
745 createRxPatch = true;
746 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100747 } else {
748 // If the RX device is on the primary HW module, then use legacy routing method for
749 // voice calls via setOutputDevice() on primary output.
750 // Otherwise, create two audio patches for TX and RX path.
751 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
752 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700753 // If the TX device is also on the primary HW module, setOutputDevice() will take care
754 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100755 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
756 (txSinkDevice != 0);
757 }
758 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
759 // Otherwise, create two audio patches for TX and RX path.
760 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200761 if (!hasPrimaryOutput()) {
762 ALOGW("%s() no primary output available", __func__);
763 return INVALID_OPERATION;
764 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530765 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700766 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200767 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800768 // If the TX device is on the primary HW module but RX device is
769 // on other HW module, SinkMetaData of telephony input should handle it
770 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700771 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700772 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100773 // terminate active capture if on the same HW module as the call TX source device
774 // FIXME: would be better to refine to only inputs whose profile connects to the
775 // call TX device but this information is not in the audio patch and logic here must be
776 // symmetric to the one in startInput()
777 for (const auto& activeDesc : mInputs.getActiveInputs()) {
778 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
779 closeActiveClients(activeDesc);
780 }
781 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800783 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100784 if (waitMs != nullptr) {
785 *waitMs = muteWaitMs;
786 }
787 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800788}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700789
Mikhail Naganov100f0122018-11-29 11:22:16 -0800790bool AudioPolicyManager::isDeviceOfModule(
791 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
792 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
793 if (module != 0) {
794 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
795 .indexOf(devDesc) != NAME_NOT_FOUND
796 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
797 .indexOf(devDesc) != NAME_NOT_FOUND;
798 }
799 return false;
800}
801
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200802void AudioPolicyManager::connectTelephonyRxAudioSource()
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805 const struct audio_port_config source = {
806 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
807 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
808 };
809 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100810
811 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent963dbcc2024-06-20 12:34:15 +0000812 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
813 true /*internal*/, true /*isCallRx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100814 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
815 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200816 ALOGE_IF(mCallRxSourceClient == nullptr,
817 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200818}
819
Francois Gaffie601801d2021-06-22 13:27:39 +0200820void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200821{
Francois Gaffie601801d2021-06-22 13:27:39 +0200822 if (clientDesc == nullptr) {
823 return;
824 }
825 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
826 "%s error stopping audio source", __func__);
827 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828}
829
830void AudioPolicyManager::connectTelephonyTxAudioSource(
831 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
832 uint32_t delayMs)
833{
Francois Gaffie601801d2021-06-22 13:27:39 +0200834 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200835 if (srcDevice == nullptr || sinkDevice == nullptr) {
836 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
837 return;
838 }
839 PatchBuilder patchBuilder;
840 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
841 ALOGV("%s between source %s and sink %s", __func__,
842 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200843 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200844 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
845
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200846 struct audio_port_config source = {};
847 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100848 mCallTxSourceClient = new SourceClientDescriptor(
849 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurent963dbcc2024-06-20 12:34:15 +0000850 mCommunnicationStrategy, toVolumeSource(aa), true,
851 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100852 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
853
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200854 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
855 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200856 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
857 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200858 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
859 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200860 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200861 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200862}
863
Eric Laurente0720872014-03-11 09:30:41 -0700864void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700865{
866 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100867 // store previous phone state for management of sonification strategy below
868 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100869 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100870
871 if (mEngine->setPhoneState(state) != NO_ERROR) {
872 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700873 return;
874 }
François Gaffie2110e042015-03-24 08:41:51 +0100875 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700876 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700877 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700878 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800879 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700880 }
881
François Gaffie2110e042015-03-24 08:41:51 +0100882 /**
883 * Switching to or from incall state or switching between telephony and VoIP lead to force
884 * routing command.
885 */
Eric Laurent74b71512019-11-06 17:21:57 -0800886 bool force = ((isStateInCall(oldState) != isStateInCall(state))
887 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700888
889 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700890 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700891
Eric Laurente552edb2014-03-10 17:42:56 -0700892 int delayMs = 0;
893 if (isStateInCall(state)) {
894 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100895 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
896 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700898 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700899 // mute media and sonification strategies and delay device switch by the largest
900 // latency of any output where either strategy is active.
901 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100902 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
903 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
904 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700905 (delayMs < (int)desc->latency()*2)) {
906 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700907 }
François Gaffiec005e562018-11-06 15:04:49 +0100908 setStrategyMute(musicStrategy, true, desc);
909 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
910 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
911 nullptr, true /*fromCache*/).types());
912 setStrategyMute(sonificationStrategy, true, desc);
913 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
914 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
915 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700916 }
917 }
918
François Gaffiedb1755b2023-09-01 11:50:35 +0200919 if (state == AUDIO_MODE_IN_CALL) {
920 (void)updateCallRouting(false /*fromCache*/, delayMs);
921 } else {
922 if (oldState == AUDIO_MODE_IN_CALL) {
923 disconnectTelephonyAudioSource(mCallRxSourceClient);
924 disconnectTelephonyAudioSource(mCallTxSourceClient);
925 }
926 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100927 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
928 // force routing command to audio hardware when ending call
929 // even if no device change is needed
930 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
931 rxDevices = mPrimaryOutput->devices();
932 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530933 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700934 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700935 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700936
jiabin3ff8d7d2022-12-13 06:27:44 +0000937 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700938 // reevaluate routing on all outputs in case tracks have been started during the call
939 for (size_t i = 0; i < mOutputs.size(); i++) {
940 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100941 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000942 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
943 && desc->mPreferredAttrInfo != nullptr) {
944 // If the output is using preferred mixer attributes and the audio mode is not normal,
945 // the output need to reopen with default configuration.
946 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
947 continue;
948 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200949 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
950 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530951 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200952 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700953 }
954 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000955 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700956
Eric Laurent96d1dda2022-03-14 17:14:19 +0100957 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
958
Eric Laurente552edb2014-03-10 17:42:56 -0700959 if (isStateInCall(state)) {
960 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700961 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800962 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700963 }
964
965 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100966 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
967 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700968}
969
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700970audio_mode_t AudioPolicyManager::getPhoneState() {
971 return mEngine->getPhoneState();
972}
973
Eric Laurente0720872014-03-11 09:30:41 -0700974void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100975 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700976{
François Gaffie2110e042015-03-24 08:41:51 +0100977 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700978 if (config == mEngine->getForceUse(usage)) {
979 return;
980 }
Eric Laurente552edb2014-03-10 17:42:56 -0700981
François Gaffie2110e042015-03-24 08:41:51 +0100982 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
983 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
984 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700985 }
François Gaffie2110e042015-03-24 08:41:51 +0100986 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
987 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
988 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700989
990 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700991 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800992
Eric Laurent22fcda22019-05-17 16:28:47 -0700993 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
994 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800995 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700996 }
997
Eric Laurentdc462862016-07-19 12:29:53 -0700998 //FIXME: workaround for truncated touch sounds
999 // to be removed when the problem is handled by system UI
1000 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001001 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1002 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1003 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001004
1005 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001006 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001007}
1008
Eric Laurente0720872014-03-11 09:30:41 -07001009void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001010{
1011 ALOGV("setSystemProperty() property %s, value %s", property, value);
1012}
1013
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014// Find an MSD output profile compatible with the parameters passed.
1015// When "directOnly" is set, restrict search to profiles for direct outputs.
1016sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1017 const DeviceVector& devices,
1018 uint32_t samplingRate,
1019 audio_format_t format,
1020 audio_channel_mask_t channelMask,
1021 audio_output_flags_t flags,
1022 bool directOnly)
1023{
1024 flags = getRelevantFlags(flags, directOnly);
1025
1026 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1027 if (msdModule != nullptr) {
1028 // for the msd module check if there are patches to the output devices
1029 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1030 HwModuleCollection modules;
1031 modules.add(msdModule);
1032 return searchCompatibleProfileHwModules(
1033 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1034 flags, directOnly);
1035 }
1036 }
1037 return nullptr;
1038}
1039
Michael Chana94fbb22018-04-24 14:31:19 +10001040// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1041// search to profiles for direct outputs.
1042sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001043 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001044 uint32_t samplingRate,
1045 audio_format_t format,
1046 audio_channel_mask_t channelMask,
1047 audio_output_flags_t flags,
1048 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001049{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001050 flags = getRelevantFlags(flags, directOnly);
1051
1052 return searchCompatibleProfileHwModules(
1053 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1054}
1055
1056audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1057 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001058 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059 // only retain flags that will drive the direct output profile selection
1060 // if explicitly requested
1061 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001062 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1064 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001065 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001066 return flags;
1067}
Eric Laurent861a6282015-05-18 15:40:16 -07001068
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1070 const HwModuleCollection& hwModules,
1071 const DeviceVector& devices,
1072 uint32_t samplingRate,
1073 audio_format_t format,
1074 audio_channel_mask_t channelMask,
1075 audio_output_flags_t flags,
1076 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001077 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001078 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001079 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001080 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001081 samplingRate, NULL /*updatedSamplingRate*/,
1082 format, NULL /*updatedFormat*/,
1083 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001084 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001085 continue;
1086 }
1087 // reject profiles not corresponding to a device currently available
1088 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1089 continue;
1090 }
1091 // reject profiles if connected device does not support codec
1092 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1093 continue;
1094 }
1095 if (!directOnly) {
1096 return curProfile;
1097 }
1098
1099 // when searching for direct outputs, if several profiles are compatible, give priority
1100 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001101 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001102 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001103 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 }
1105 profile = curProfile;
1106 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1107 break;
1108 }
Eric Laurente552edb2014-03-10 17:42:56 -07001109 }
1110 }
Eric Laurent861a6282015-05-18 15:40:16 -07001111 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001112}
1113
Eric Laurentfa0f6742021-08-17 18:39:44 +02001114sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001115 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001116{
1117 for (const auto& hwModule : mHwModules) {
1118 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001119 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120 continue;
1121 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001122 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001123 // reject profiles not corresponding to a device currently available
1124 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1125 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1126 continue;
1127 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001128 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1129 != devices.size()) {
1130 continue;
1131 }
1132 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001133 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1134 return curProfile;
1135 }
1136 }
1137 return nullptr;
1138}
1139
Eric Laurentf4e63452017-11-06 19:31:46 +00001140audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001141{
François Gaffiec005e562018-11-06 15:04:49 +01001142 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001143
1144 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1145 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1146 // format, flags, etc. This may result in some discrepancy for functions that utilize
1147 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1148 // and AudioSystem::getOutputSamplingRate().
1149
François Gaffie11d30102018-11-02 16:09:09 +01001150 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001151 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1152 if (stream == AUDIO_STREAM_MUSIC &&
1153 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1154 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1155 }
1156 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001157
François Gaffie11d30102018-11-02 16:09:09 +01001158 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1159 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001160 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001161}
1162
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001163status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1164 const audio_attributes_t *srcAttr,
1165 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001166{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001167 if (srcAttr != NULL) {
1168 if (!isValidAttributes(srcAttr)) {
1169 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1170 __func__,
1171 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1172 srcAttr->tags);
1173 return BAD_VALUE;
1174 }
1175 *dstAttr = *srcAttr;
1176 } else {
1177 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1178 ALOGE("%s: invalid stream type", __func__);
1179 return BAD_VALUE;
1180 }
François Gaffiec005e562018-11-06 15:04:49 +01001181 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001182 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001183
1184 // Only honor audibility enforced when required. The client will be
1185 // forced to reconnect if the forced usage changes.
1186 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001187 dstAttr->flags = static_cast<audio_flags_mask_t>(
1188 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001189 }
1190
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001191 return NO_ERROR;
1192}
1193
Kevin Rocard153f92d2018-12-18 18:33:28 -08001194status_t AudioPolicyManager::getOutputForAttrInt(
1195 audio_attributes_t *resultAttr,
1196 audio_io_handle_t *output,
1197 audio_session_t session,
1198 const audio_attributes_t *attr,
1199 audio_stream_type_t *stream,
1200 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001201 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001202 audio_output_flags_t *flags,
1203 audio_port_handle_t *selectedDeviceId,
1204 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001205 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001206 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001207 bool *isSpatialized,
1208 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001209{
François Gaffiec005e562018-11-06 15:04:49 +01001210 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001211 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001212 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001213 const sp<DeviceDescriptor> requestedDevice =
1214 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1215
Eric Laurent8a1095a2019-11-08 14:44:16 -08001216 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001217 *isSpatialized = false;
1218
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001219 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1220 if (status != NO_ERROR) {
1221 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001222 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001223 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001224 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001225 }
François Gaffiec005e562018-11-06 15:04:49 +01001226 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001227
François Gaffiec005e562018-11-06 15:04:49 +01001228 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1229 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001230
Oscar Azucena873d10f2023-01-12 18:34:42 -08001231 bool usePrimaryOutputFromPolicyMixes = false;
1232
Kevin Rocard153f92d2018-12-18 18:33:28 -08001233 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1234 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1235 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001236 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001237 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1238 .channel_mask = config->channel_mask,
1239 .format = config->format,
1240 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001241 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001242 mAvailableOutputDevices, requestedDevice, primaryMix,
1243 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001244 if (status != OK) {
1245 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001247
Kevin Rocard153f92d2018-12-18 18:33:28 -08001248 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001249 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1250 && !audio_is_linear_pcm(config->format)) {
1251 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001252 return BAD_VALUE;
1253 }
1254 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001255 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001256 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1257 primaryMix->mDeviceAddress,
1258 AUDIO_FORMAT_DEFAULT);
1259 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001260 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001261 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1262 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001263 // if a direct output can be opened to deliver the track's multi-channel content to the
1264 // output rather than being downmixed by the primary output, then use this direct
1265 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1266 // mix.
1267 bool tryDirectForChannelMask = policyDesc != nullptr
1268 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1269 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001270 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001271 audio_io_handle_t newOutput;
1272 status = openDirectOutput(
1273 *stream, session, config,
1274 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001275 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001276 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 policyDesc = mOutputs.valueFor(newOutput);
1278 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001279 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001280 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001281 policyDesc = nullptr;
1282 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001283 }
1284 if (policyDesc != nullptr) {
1285 policyDesc->mPolicyMix = primaryMix;
1286 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001287 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1288 : AUDIO_PORT_HANDLE_NONE;
1289 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1290 // Remove direct flag as it is not on a direct output.
1291 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1292 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001293
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001294 ALOGV("getOutputForAttr() returns output %d", *output);
1295 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1296 *outputType = API_OUT_MIX_PLAYBACK;
1297 } else {
1298 *outputType = API_OUTPUT_LEGACY;
1299 }
1300 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001301 } else {
1302 if (policyMixDevice != nullptr) {
1303 ALOGE("%s, try to use primary mix but no output found", __func__);
1304 return INVALID_OPERATION;
1305 }
1306 // Fallback to default engine selection as the selected primary mix device is not
1307 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001308 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001309 }
François Gaffiec005e562018-11-06 15:04:49 +01001310 // Virtual sources must always be dynamicaly or explicitly routed
1311 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1312 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1313 return BAD_VALUE;
1314 }
1315 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1316 // in order to let the choice of the order to future vendor engine
1317 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001318
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001319 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001320 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001321 }
1322
Nadav Barb2f18162018-07-18 13:01:53 +03001323 // Set incall music only if device was explicitly set, and fallback to the device which is
1324 // chosen by the engine if not.
1325 // FIXME: provide a more generic approach which is not device specific and move this back
1326 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001327 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001328 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001329 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001330 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001331 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001332 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001333 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001334 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001335 }
1336 }
1337
François Gaffiec005e562018-11-06 15:04:49 +01001338 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1339 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1340 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001341
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001342 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001343 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001344 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001345 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001346 ALOGV("%s() Using MSD devices %s instead of devices %s",
1347 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001348 } else {
1349 *output = AUDIO_IO_HANDLE_NONE;
1350 }
1351 }
1352 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001353 sp<PreferredMixerAttributesInfo> info = nullptr;
1354 if (outputDevices.size() == 1) {
1355 info = getPreferredMixerAttributesInfo(
1356 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001357 mEngine->getProductStrategyForAttributes(*resultAttr),
1358 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001359 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1360 // and it is currently active.
1361 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001362 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001363 info = nullptr;
1364 }
jiabin220eea12024-05-17 17:55:20 +00001365 if (com::android::media::audioserver::
1366 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1367 if (info != nullptr && info->getUid() == uid &&
1368 info->configMatches(*config) &&
1369 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1370 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1371 [this, &outputDevices](audio_usage_t usage) {
1372 return mOutputs.isUsageActiveOnDevice(
1373 usage, outputDevices[0]); }))) {
1374 // Bit-perfect request is not allowed when the phone mode is not normal or
1375 // there is any higher priority user case active.
1376 return INVALID_OPERATION;
1377 }
1378 }
jiabina84c3d32022-12-02 18:59:55 +00001379 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001380 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001381 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001382 // The client will be active if the client is currently preferred mixer owner and the
1383 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001384 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001385 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001386 && info->getUid() == uid
1387 && *output != AUDIO_IO_HANDLE_NONE
1388 // When bit-perfect output is selected for the preferred mixer attributes owner,
1389 // only need to consider the config matches.
1390 && mOutputs.valueFor(*output)->isConfigurationMatched(
1391 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001392
1393 if (*isBitPerfect) {
1394 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1395 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001396 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001397 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001398 AudioProfileVector profiles;
1399 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1400 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001401 const auto channels = profiles[0]->getChannels();
1402 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1403 config->channel_mask = *channels.begin();
1404 }
1405 const auto sampleRates = profiles[0]->getSampleRates();
1406 if (!sampleRates.empty() &&
1407 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1408 config->sample_rate = *sampleRates.begin();
1409 }
jiabinf1c73972022-04-14 16:28:52 -07001410 config->format = profiles[0]->getFormat();
1411 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001412 return INVALID_OPERATION;
1413 }
Paul McLeanaa981192015-03-21 09:55:15 -07001414
François Gaffiec005e562018-11-06 15:04:49 +01001415 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001416 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001417 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001418 *selectedDeviceId = outputDevice->getId();
1419 break;
1420 }
1421 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001422
Eric Laurent8a1095a2019-11-08 14:44:16 -08001423 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1424 *outputType = API_OUTPUT_TELEPHONY_TX;
1425 } else {
1426 *outputType = API_OUTPUT_LEGACY;
1427 }
1428
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001429 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1430
1431 return NO_ERROR;
1432}
1433
1434status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1435 audio_io_handle_t *output,
1436 audio_session_t session,
1437 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001438 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001439 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001440 audio_output_flags_t *flags,
1441 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001442 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001443 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001444 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001445 bool *isSpatialized,
1446 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001447{
1448 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1449 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1450 return INVALID_OPERATION;
1451 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001452 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001453 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001454 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001455 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001456 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001457 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001458 const sp<DeviceDescriptor> requestedDevice =
1459 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1460
1461 // Prevent from storing invalid requested device id in clients
1462 const audio_port_handle_t sanitizedRequestedPortId =
1463 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1464 *selectedDeviceId = sanitizedRequestedPortId;
1465
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001466 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001467 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001468 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1469 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 if (status != NO_ERROR) {
1471 return status;
1472 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001473 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001474 if (secondaryOutputs != nullptr) {
1475 for (auto &secondaryMix : secondaryMixes) {
1476 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1477 if (outputDesc != nullptr &&
1478 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1479 secondaryOutputs->push_back(outputDesc->mIoHandle);
1480 weakSecondaryOutputDescs.push_back(outputDesc);
1481 }
1482 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001483 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001484
Eric Laurent8fc147b2018-07-22 19:13:55 -07001485 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001486 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001487 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001488 };
jiabin4ef93452019-09-10 14:29:54 -07001489 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001490
Eric Laurentc209fe42020-06-05 18:11:23 -07001491 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001492 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001493 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001494 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001495 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001496 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001497 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001498 std::move(weakSecondaryOutputDescs),
1499 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001500 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001501
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001502 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1503 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001504
Eric Laurente83b55d2014-11-14 10:06:21 -08001505 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001506}
1507
Eric Laurentc529cf62020-04-17 18:19:10 -07001508status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1509 audio_session_t session,
1510 const audio_config_t *config,
1511 audio_output_flags_t flags,
1512 const DeviceVector &devices,
1513 audio_io_handle_t *output) {
1514
1515 *output = AUDIO_IO_HANDLE_NONE;
1516
1517 // skip direct output selection if the request can obviously be attached to a mixed output
1518 // and not explicitly requested
1519 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1520 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1521 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1522 return NAME_NOT_FOUND;
1523 }
1524
1525 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1526 // This prevents creating an offloaded track and tearing it down immediately after start
1527 // when audioflinger detects there is an active non offloadable effect.
1528 // FIXME: We should check the audio session here but we do not have it in this context.
1529 // This may prevent offloading in rare situations where effects are left active by apps
1530 // in the background.
1531 sp<IOProfile> profile;
1532 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1533 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1534 profile = getProfileForOutput(
1535 devices, config->sample_rate, config->format, config->channel_mask,
1536 flags, true /* directOnly */);
1537 }
1538
1539 if (profile == nullptr) {
1540 return NAME_NOT_FOUND;
1541 }
1542
1543 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1544 for (size_t i = 0; i < mOutputs.size(); i++) {
1545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1546 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1547 // reuse direct output if currently open by the same client
1548 // and configured with same parameters
1549 if ((config->sample_rate == desc->getSamplingRate()) &&
1550 (config->format == desc->getFormat()) &&
1551 (config->channel_mask == desc->getChannelMask()) &&
1552 (session == desc->mDirectClientSession)) {
1553 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001554 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001555 mOutputs.keyAt(i), session);
1556 *output = mOutputs.keyAt(i);
1557 return NO_ERROR;
1558 }
1559 }
1560 }
1561
1562 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001563 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1564 return NAME_NOT_FOUND;
1565 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1566 // MMAP gracefully handles lack of an exclusive track resource by mixing
1567 // above the audio framework. For AAudio to know that the limit is reached,
1568 // return an error.
1569 return NAME_NOT_FOUND;
1570 } else {
1571 // Close outputs on this profile, if available, to free resources for this request
1572 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1573 const auto desc = mOutputs.valueAt(i);
1574 if (desc->mProfile == profile) {
1575 closeOutput(desc->mIoHandle);
1576 }
1577 }
1578 }
1579 }
1580
1581 // Unable to close streams to find free resources for this request
1582 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001583 return NAME_NOT_FOUND;
1584 }
1585
Atneya Nairb16666a2023-12-11 20:18:33 -08001586 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001587
Michael Chan6fb34492020-12-08 15:44:49 +11001588 // An MSD patch may be using the only output stream that can service this request. Release
1589 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001590 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001591
Eric Laurentf1f22e72021-07-13 14:04:14 +02001592 status_t status =
1593 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001594
1595 // only accept an output with the requested parameters
1596 if (status != NO_ERROR ||
1597 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1598 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1599 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1600 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1601 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1602 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1603 config->channel_mask, outputDesc->getChannelMask());
1604 if (*output != AUDIO_IO_HANDLE_NONE) {
1605 outputDesc->close();
1606 }
1607 // fall back to mixer output if possible when the direct output could not be open
1608 if (audio_is_linear_pcm(config->format) &&
1609 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1610 return NAME_NOT_FOUND;
1611 }
1612 *output = AUDIO_IO_HANDLE_NONE;
1613 return BAD_VALUE;
1614 }
1615 outputDesc->mDirectOpenCount = 1;
1616 outputDesc->mDirectClientSession = session;
1617
1618 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001619 setOutputDevices(__func__, outputDesc,
1620 devices,
1621 true,
1622 0,
1623 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001624 mPreviousOutputs = mOutputs;
1625 ALOGV("%s returns new direct output %d", __func__, *output);
1626 mpClientInterface->onAudioPortListUpdate();
1627 return NO_ERROR;
1628}
1629
François Gaffie11d30102018-11-02 16:09:09 +01001630audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1631 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001632 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001633 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001634 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001635 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001636 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001637 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001638 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001639{
Andy Hungc88b0642018-04-27 15:42:35 -07001640 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001641
jiabine375d412019-02-26 12:54:53 -08001642 // Discard haptic channel mask when forcing muting haptic channels.
1643 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001644 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1645 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001646
Eric Laurente552edb2014-03-10 17:42:56 -07001647 // open a direct output if required by specified parameters
1648 //force direct flag if offload flag is set: offloading implies a direct output stream
1649 // and all common behaviors are driven by checking only the direct flag
1650 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001651 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1652 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001653 }
Nadav Bar766fb022018-01-07 12:18:03 +02001654 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1655 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001656 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001657
1658 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1659
Eric Laurente83b55d2014-11-14 10:06:21 -08001660 // only allow deep buffering for music stream type
1661 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001662 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001663 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001664 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001665 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1666 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001667 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001668 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001669 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001670 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001671 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001672 audio_is_linear_pcm(config->format) &&
1673 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001674 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001675 AUDIO_OUTPUT_FLAG_DIRECT);
1676 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001677 }
Eric Laurente552edb2014-03-10 17:42:56 -07001678
Carter Hsua3abb402021-10-26 11:11:20 +08001679 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1680 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1681 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1682 }
1683
Eric Laurentf9230d52024-01-26 18:49:09 +01001684 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001685 // was specified and offload or direct playback is not explicitly requested, and there is no
1686 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001687 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001688 if (mSpatializerOutput != nullptr &&
1689 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1690 prefMixerConfigInfo == nullptr &&
1691 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1692 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001693 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001694 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001695 }
1696
Eric Laurentc529cf62020-04-17 18:19:10 -07001697 audio_config_t directConfig = *config;
1698 directConfig.channel_mask = channelMask;
1699 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1700 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001701 return output;
1702 }
1703
Eric Laurent14cbfca2016-03-17 09:42:16 -07001704 // A request for HW A/V sync cannot fallback to a mixed output because time
1705 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001706 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001707 return AUDIO_IO_HANDLE_NONE;
1708 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001709 // A request for Tuner cannot fallback to a mixed output
1710 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1711 return AUDIO_IO_HANDLE_NONE;
1712 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001713
Eric Laurente552edb2014-03-10 17:42:56 -07001714 // ignoring channel mask due to downmix capability in mixer
1715
1716 // open a non direct output
1717
1718 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001719 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001720 // get which output is suitable for the specified stream. The actual
1721 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001722 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001723 if (prefMixerConfigInfo != nullptr) {
1724 for (audio_io_handle_t outputHandle : outputs) {
1725 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1726 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1727 output = outputHandle;
1728 break;
1729 }
1730 }
1731 if (output == AUDIO_IO_HANDLE_NONE) {
1732 // No output open with the preferred profile. Open a new one.
1733 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1734 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1735 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1736 config.format = prefMixerConfigInfo->getConfigBase().format;
1737 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1738 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1739 &config, prefMixerConfigInfo->getFlags());
1740 if (preferredOutput == nullptr) {
1741 ALOGE("%s failed to open output with preferred mixer config", __func__);
1742 } else {
1743 output = preferredOutput->mIoHandle;
1744 }
1745 }
1746 } else {
1747 // at this stage we should ignore the DIRECT flag as no direct output could be
1748 // found earlier
1749 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001750 if (com::android::media::audioserver::
1751 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1752 // If the preferred mixer attributes is null, do not select the bit-perfect output
1753 // unless the bit-perfect output is the only output.
1754 // The bit-perfect output can exist while the passed in preferred mixer attributes
1755 // info is null when it is a high priority client. The high priority clients are
1756 // ringtone or alarm, which is not a bit-perfect use case.
1757 size_t i = 0;
1758 while (i < outputs.size() && outputs.size() > 1) {
1759 auto desc = mOutputs.valueFor(outputs[i]);
1760 // The output descriptor must not be null here.
1761 if (desc->isBitPerfect()) {
1762 outputs.removeItemsAt(i);
1763 } else {
1764 i += 1;
1765 }
1766 }
1767 }
jiabina84c3d32022-12-02 18:59:55 +00001768 output = selectOutput(
1769 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1770 }
Eric Laurente552edb2014-03-10 17:42:56 -07001771 }
François Gaffie11d30102018-11-02 16:09:09 +01001772 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001773 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001774 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001775
Eric Laurente552edb2014-03-10 17:42:56 -07001776 return output;
1777}
1778
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001779sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001780 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1781 mAvailableInputDevices);
1782 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1783}
1784
1785DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1786 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1787 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788}
1789
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001790const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001791 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001792 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1793 if (msdModule != 0) {
1794 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1795 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1796 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1797 const struct audio_port_config *source = &patch->mPatch.sources[j];
1798 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1799 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001800 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001801 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802 }
1803 }
1804 }
1805 return msdPatches;
1806}
1807
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001808bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1809 ssize_t index = mAudioPatches.indexOfKey(handle);
1810 if (index < 0) {
1811 return false;
1812 }
1813 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1814 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1815 if (msdModule == nullptr) {
1816 return false;
1817 }
1818 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1819 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1820 return true;
1821 }
1822 index = getMsdOutputPatches().indexOfKey(handle);
1823 if (index < 0) {
1824 return false;
1825 }
1826 return true;
1827}
1828
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001829status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1830 const InputProfileCollection &inputProfiles,
1831 const OutputProfileCollection &outputProfiles,
1832 const sp<DeviceDescriptor> &sourceDevice,
1833 const sp<DeviceDescriptor> &sinkDevice,
1834 AudioProfileVector& sourceProfiles,
1835 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001837 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 return NO_INIT;
1839 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001841 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 return NO_INIT;
1843 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001845 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1846 inProfile->supportsDevice(sourceDevice)) {
1847 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 }
1849 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001851 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001852 outProfile->supportsDevice(sinkDevice)) {
1853 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 }
1855 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001856 return NO_ERROR;
1857}
1858
1859status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1860 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1861 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1862{
Dean Wheatley16809da2022-12-09 14:55:46 +11001863 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1864 static const std::vector<audio_format_t> formatsOrder = {{
1865 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001866 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1867 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001868 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1869 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1870 // preferred).
1871 std::vector<audio_channel_mask_t> masks = {{
1872 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1873 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1874 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1875 // insert index masks (higher counts most preferred) as preferred over position masks
1876 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1877 masks.insert(
1878 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1879 }
1880 return masks;
1881 }();
1882
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001884 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1885 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001886 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1888 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001889 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001890 }
1891 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1892 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1893 sinkConfig->format = bestSinkConfig.format;
1894 // For encoded streams force direct flag to prevent downstream mixing.
1895 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1896 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001897 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1898 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001899 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001900 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1901 // raw and IEC61937 framed streams.
1902 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1903 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1904 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1906 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001907 sourceConfig->channel_mask =
1908 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1909 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1910 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001911 sourceConfig->format = bestSinkConfig.format;
1912 // Copy input stream directly without any processing (e.g. resampling).
1913 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1914 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1915 if (hwAvSync) {
1916 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1917 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1918 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1919 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1920 }
1921 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1922 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1923 sinkConfig->config_mask |= config_mask;
1924 sourceConfig->config_mask |= config_mask;
1925 return NO_ERROR;
1926}
1927
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001928PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1929 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930{
1931 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001932 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1933 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1934 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1935 if (deviceModule == nullptr) {
1936 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1937 return patchBuilder;
1938 }
1939 const InputProfileCollection inputProfiles = msdIsSource ?
1940 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1941 const OutputProfileCollection outputProfiles = msdIsSource ?
1942 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1943
1944 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1945 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1946 device : getMsdAudioOutDevices().itemAt(0);
1947 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1948
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001949 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1950 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001951 AudioProfileVector sourceProfiles;
1952 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001953 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1954 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001955 for (auto hwAvSync : { true, false }) {
1956 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1957 sourceProfiles, sinkProfiles) != NO_ERROR) {
1958 continue;
1959 }
1960 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1961 &sinkConfig) == NO_ERROR) {
1962 // Found a matching config. Re-create PatchBuilder with this config.
1963 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1964 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001965 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001966 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001967 " supporting PCM format conversion.", __func__);
1968 return patchBuilder;
1969}
1970
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001971status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001972 DeviceVector devices;
1973 if (outputDevices != nullptr && outputDevices->size() > 0) {
1974 devices.add(*outputDevices);
1975 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001976 // Use media strategy for unspecified output device. This should only
1977 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1978 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001979 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001980 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001981 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001982 }
Michael Chan6fb34492020-12-08 15:44:49 +11001983 std::vector<PatchBuilder> patchesToCreate;
1984 for (auto i = 0u; i < devices.size(); ++i) {
1985 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001986 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001987 }
1988 // Retain only the MSD patches associated with outputDevices request.
1989 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001990 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001991 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1992 auto retainedPatch = false;
1993 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1994 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1995 patchesToRemove.removeItemsAt(i);
1996 retainedPatch = true;
1997 break;
1998 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001999 }
Michael Chan6fb34492020-12-08 15:44:49 +11002000 if (retainedPatch) {
2001 it = patchesToCreate.erase(it);
2002 continue;
2003 }
2004 ++it;
2005 }
2006 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2007 return NO_ERROR;
2008 }
2009 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2010 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002011 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002012 }
Michael Chan6fb34492020-12-08 15:44:49 +11002013 status_t status = NO_ERROR;
2014 for (const auto &p : patchesToCreate) {
2015 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2016 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2017 char message[256];
2018 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2019 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2020 currStatus == NO_ERROR ? "Success" : "Error",
2021 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2022 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2023 if (currStatus == NO_ERROR) {
2024 ALOGD("%s", message);
2025 } else {
2026 ALOGE("%s", message);
2027 if (status == NO_ERROR) {
2028 status = currStatus;
2029 }
2030 }
2031 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002032 return status;
2033}
2034
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002035void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2036 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002037 for (size_t i = 0; i < msdPatches.size(); i++) {
2038 const auto& patch = msdPatches[i];
2039 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2040 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2041 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2042 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2043 releaseAudioPatch(patch->getHandle(), mUidCached);
2044 break;
2045 }
2046 }
2047 }
2048}
2049
Dorin Drimus94d94412022-02-02 09:05:02 +01002050bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002051 DeviceVector devicesToCheck =
2052 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002053 AudioPatchCollection msdPatches = getMsdOutputPatches();
2054 for (size_t i = 0; i < msdPatches.size(); i++) {
2055 const auto& patch = msdPatches[i];
2056 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2057 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2058 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2059 const auto& foundDevice = devicesToCheck.getDevice(
2060 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2061 if (foundDevice != nullptr) {
2062 devicesToCheck.remove(foundDevice);
2063 if (devicesToCheck.isEmpty()) {
2064 return true;
2065 }
2066 }
2067 }
2068 }
2069 }
2070 return false;
2071}
2072
Eric Laurente0720872014-03-11 09:30:41 -07002073audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002074 audio_output_flags_t flags,
2075 audio_format_t format,
2076 audio_channel_mask_t channelMask,
2077 uint32_t samplingRate,
2078 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002079{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002080 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2081 "%s called with format %#x", __func__, format);
2082
jiabinebb6af42020-06-09 17:31:17 -07002083 // Return the output that haptic-generating attached to when 1) session id is specified,
2084 // 2) haptic-generating effect exists for given session id and 3) the output that
2085 // haptic-generating effect attached to is in given outputs.
2086 if (sessionId != AUDIO_SESSION_NONE) {
2087 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2088 sessionId, FX_IID_HAPTICGENERATOR);
2089 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2090 return hapticGeneratingOutput;
2091 }
2092 }
2093
Eric Laurent16c66dd2019-05-01 17:54:10 -07002094 // Flags disqualifying an output: the match must happen before calling selectOutput()
2095 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2096 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2097
2098 // Flags expressing a functional request: must be honored in priority over
2099 // other criteria
2100 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2101 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002102 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2103 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002104 // Flags expressing a performance request: have lower priority than serving
2105 // requested sampling rate or channel mask
2106 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2107 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2108 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2109
2110 const audio_output_flags_t functionalFlags =
2111 (audio_output_flags_t)(flags & kFunctionalFlags);
2112 const audio_output_flags_t performanceFlags =
2113 (audio_output_flags_t)(flags & kPerformanceFlags);
2114
2115 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2116
Eric Laurente552edb2014-03-10 17:42:56 -07002117 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002118 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002119 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002120 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002122 // with tiebreak preferring the minimum number of extra functional flags
2123 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002124 // 3: the output supporting the exact channel mask
2125 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002126 // 5: the output with the highest sampling rate if the requested sample rate is
2127 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002128 // 6: the output with the highest number of requested performance flags
2129 // 7: the output with the bit depth the closest to the requested one
2130 // 8: the primary output
2131 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002132
Eric Laurent16c66dd2019-05-01 17:54:10 -07002133 // matching criteria values in priority order for best matching output so far
2134 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002135
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002136 const bool hasOrphanHaptic =
2137 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2139 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2140 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002141
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002142 for (audio_io_handle_t output : outputs) {
2143 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 // matching criteria values in priority order for current output
2145 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002146
Eric Laurent16c66dd2019-05-01 17:54:10 -07002147 if (outputDesc->isDuplicated()) {
2148 continue;
2149 }
2150 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2151 continue;
2152 }
Eric Laurent8838a382014-09-08 16:44:28 -07002153
Eric Laurent16c66dd2019-05-01 17:54:10 -07002154 // If haptic channel is specified, use the haptic output if present.
2155 // When using haptic output, same audio format and sample rate are required.
2156 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002157 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002158 // skip if haptic channel specified but output does not support it, or output support haptic
2159 // but there is no haptic channel requested AND no orphan haptic effect exist
2160 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2161 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 continue;
2163 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002164 // In the case of audio-coupled-haptic playback, there is no format conversion and
2165 // resampling in the framework, same format/channel/sampleRate for client and the output
2166 // thread is required. In the case of HapticGenerator effect, do not require format
2167 // matching.
2168 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2169 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002170 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002171 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002172 }
2173
2174 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002175 const int matchingFunctionalFlags =
2176 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2177 const int totalFunctionalFlags =
2178 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2179 // Prefer matching functional flags, but subtract unnecessary functional flags.
2180 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181
2182 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002183 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2184 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002185 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2186 channelCount <= outputChannelCount) {
2187 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002188 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2189 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002191 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002192 currentMatchCriteria[3] = outputChannelCount;
2193 }
2194
2195 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002196 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002197 int diff; // avoid unsigned integer overflow.
2198 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2199
2200 // prefer the closest output sampling rate greater than or equal to target
2201 // if none exists, prefer the closest output sampling rate less than target.
2202 //
2203 // criteria is offset to make non-negative.
2204 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002205 }
2206
2207 // performance flags match
2208 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2209
2210 // format match
2211 if (format != AUDIO_FORMAT_INVALID) {
2212 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002213 PolicyAudioPort::kFormatDistanceMax -
2214 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002215 }
2216
2217 // primary output match
2218 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2219
2220 // compare match criteria by priority then value
2221 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2222 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2223 bestMatchCriteria = currentMatchCriteria;
2224 bestOutput = output;
2225
2226 std::stringstream result;
2227 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2228 std::ostream_iterator<int>(result, " "));
2229 ALOGV("%s new bestOutput %d criteria %s",
2230 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002231 }
2232 }
2233
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002235}
2236
Eric Laurent8fc147b2018-07-22 19:13:55 -07002237status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002238{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002239 ALOGV("%s portId %d", __FUNCTION__, portId);
2240
2241 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2242 if (outputDesc == 0) {
2243 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002244 return BAD_VALUE;
2245 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002246 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002247
Eric Laurent8fc147b2018-07-22 19:13:55 -07002248 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002249 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002250
jiabin220eea12024-05-17 17:55:20 +00002251 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2252 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2253 && outputDesc->isBitPerfect()) {
2254 // Usually, APM selects bit-perfect output for high priority use cases only when
2255 // bit-perfect output is the only output that can be routed to the selected device.
2256 // However, here is no need to play high priority use cases such as ringtone and alarm
2257 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2258 // can attach to new output.
2259 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2260 __func__, client->stream());
2261 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2262 return DEAD_OBJECT;
2263 }
2264
Eric Laurent733ce942017-12-07 12:18:25 -08002265 status_t status = outputDesc->start();
2266 if (status != NO_ERROR) {
2267 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002268 }
2269
Eric Laurent97ac8712018-07-27 18:59:02 -07002270 uint32_t delayMs;
2271 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002272
2273 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002274 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002275 if (status == DEAD_OBJECT) {
2276 sp<SwAudioOutputDescriptor> desc =
2277 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2278 if (desc == nullptr) {
2279 // This is not common, it may indicate something wrong with the HAL.
2280 ALOGE("%s unable to open output with default config", __func__);
2281 return status;
2282 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002283 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002284 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002285 }
jiabina84c3d32022-12-02 18:59:55 +00002286
2287 // If the client is the first one active on preferred mixer parameters, reopen the output
2288 // if the current mixer parameters doesn't match the preferred one.
2289 if (outputDesc->devices().size() == 1) {
2290 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2291 outputDesc->devices()[0]->getId(), client->strategy());
2292 if (info != nullptr && info->getUid() == client->uid()) {
2293 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2294 info->getConfigBase(), info->getFlags())) {
2295 stopSource(outputDesc, client);
2296 outputDesc->stop();
2297 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2298 config.channel_mask = info->getConfigBase().channel_mask;
2299 config.sample_rate = info->getConfigBase().sample_rate;
2300 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002301 sp<SwAudioOutputDescriptor> desc =
2302 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2303 if (desc == nullptr) {
2304 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002305 }
jiabin220eea12024-05-17 17:55:20 +00002306 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002307 // Intentionally return error to let the client side resending request for
2308 // creating and starting.
2309 return DEAD_OBJECT;
2310 }
2311 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002312 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002313 // If it is first bit-perfect client, reroute all clients that will be routed to
2314 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2315 PortHandleVector clientsToInvalidate;
2316 for (size_t i = 0; i < mOutputs.size(); i++) {
2317 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002318 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002319 continue;
2320 }
2321 for (const auto& c : mOutputs[i]->getClientIterable()) {
2322 clientsToInvalidate.push_back(c->portId());
2323 }
2324 }
2325 if (!clientsToInvalidate.empty()) {
2326 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2327 __func__);
2328 mpClientInterface->invalidateTracks(clientsToInvalidate);
2329 }
2330 }
jiabina84c3d32022-12-02 18:59:55 +00002331 }
2332 }
2333
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002334 if (client->hasPreferredDevice()) {
2335 // playback activity with preferred device impacts routing occurred, inform upper layers
2336 mpClientInterface->onRoutingUpdated();
2337 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002338 if (delayMs != 0) {
2339 usleep(delayMs * 1000);
2340 }
2341
jiabin220eea12024-05-17 17:55:20 +00002342 if (status == NO_ERROR &&
2343 outputDesc->mPreferredAttrInfo != nullptr &&
2344 outputDesc->isBitPerfect() &&
2345 com::android::media::audioserver::
2346 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2347 // A new client is started on bit-perfect output, update all clients internal mute.
2348 updateClientsInternalMute(outputDesc);
2349 }
2350
Eric Laurentc75307b2015-03-17 15:29:32 -07002351 return status;
2352}
2353
Eric Laurent96d1dda2022-03-14 17:14:19 +01002354bool AudioPolicyManager::isLeUnicastActive() const {
2355 if (isInCall()) {
2356 return true;
2357 }
2358 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2359}
2360
2361bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2362 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2363 return false;
2364 }
2365 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2366 ALOGV("%s active %d", __func__, active);
2367 return active;
2368}
2369
Eric Laurent97ac8712018-07-27 18:59:02 -07002370status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2371 const sp<TrackClientDescriptor>& client,
2372 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002373{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002374 // cannot start playback of STREAM_TTS if any other output is being used
2375 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002376
2377 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002378 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002379 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002380 auto clientStrategy = client->strategy();
2381 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002382 if (stream == AUDIO_STREAM_TTS) {
2383 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002384 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002385 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002386 return INVALID_OPERATION;
2387 } else {
2388 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2389 }
2390 } else {
2391 // some playback other than beacon starts
2392 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2393 }
2394
Eric Laurent77305a62016-07-25 16:39:22 -07002395 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002396 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002397 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002398
François Gaffie11d30102018-11-02 16:09:09 +01002399 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002400 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002401 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002402 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002403 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002404 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002405 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002406 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002407 } else {
2408 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002409 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002410 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2411 AUDIO_FORMAT_DEFAULT);
2412 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2413 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002414 }
2415
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002416 // requiresMuteCheck is false when we can bypass mute strategy.
2417 // It covers a common case when there is no materially active audio
2418 // and muting would result in unnecessary delay and dropped audio.
2419 const uint32_t outputLatencyMs = outputDesc->latency();
2420 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002421 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002422
Eric Laurente552edb2014-03-10 17:42:56 -07002423 // increment usage count for this stream on the requested output:
2424 // NOTE that the usage count is the same for duplicated output and hardware output which is
2425 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002426 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002427
2428 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002429 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002430 // Preferred device may be exclusive, use only if no other active clients on this output
2431 devices = DeviceVector(
2432 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2433 } else {
2434 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2435 }
François Gaffie11d30102018-11-02 16:09:09 +01002436 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002437 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 }
2439 }
Eric Laurente552edb2014-03-10 17:42:56 -07002440
François Gaffiec005e562018-11-06 15:04:49 +01002441 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002442 selectOutputForMusicEffects();
2443 }
2444
François Gaffie1c878552018-11-22 16:53:21 +01002445 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002446 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002447 if (devices.isEmpty()) {
2448 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002449 }
François Gaffiec005e562018-11-06 15:04:49 +01002450 bool shouldWait =
2451 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2452 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2453 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002454 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002455 const bool needToCloseBitPerfectOutput =
2456 (com::android::media::audioserver::
2457 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2458 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2459 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002460 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002462 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002463 // An output has a shared device if
2464 // - managed by the same hw module
2465 // - supports the currently selected device
2466 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002467 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002468
Eric Laurent77305a62016-07-25 16:39:22 -07002469 // force a device change if any other output is:
2470 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002471 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002472 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002473 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002474 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002475 // change the device currently selected by the other output.
2476 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002477 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002478 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002479 force = true;
2480 }
2481 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002482 // a notification so that audio focus effect can propagate, or that a mute/unmute
2483 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002484 const uint32_t latencyMs = desc->latency();
2485 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2486
2487 if (shouldWait && isActive && (waitMs < latencyMs)) {
2488 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002489 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002490
2491 // Require mute check if another output is on a shared device
2492 // and currently active to have proper drain and avoid pops.
2493 // Note restoring AudioTracks onto this output needs to invoke
2494 // a volume ramp if there is no mute.
2495 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002496
2497 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2498 outputsToReopen.push_back(desc);
2499 }
Eric Laurente552edb2014-03-10 17:42:56 -07002500 }
2501 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002502
jiabin220eea12024-05-17 17:55:20 +00002503 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002504 // If the output is open with preferred mixer attributes, but the routed device is
2505 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2506 // changed.
2507 return DEAD_OBJECT;
2508 }
jiabin220eea12024-05-17 17:55:20 +00002509 for (auto& outputToReopen : outputsToReopen) {
2510 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2511 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002512 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302513 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2514 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002515
Eric Laurente552edb2014-03-10 17:42:56 -07002516 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002517 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002518 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002519 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002520 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002521 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002522 outputDesc->useHwGain() /*force*/)) {
2523 // request AudioService to reinitialize the volume curves asynchronously
2524 ALOGE("checkAndSetVolume failed, requesting volume range init");
2525 mpClientInterface->onVolumeRangeInitRequest();
2526 };
Eric Laurente552edb2014-03-10 17:42:56 -07002527
2528 // update the outputs if starting an output with a stream that can affect notification
2529 // routing
2530 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002531
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002532 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002533 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002534 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002535 }
Eric Laurentdc462862016-07-19 12:29:53 -07002536
2537 if (waitMs > muteWaitMs) {
2538 *delayMs = waitMs - muteWaitMs;
2539 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002540
2541 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2542 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2543 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2544 // change occurs after the MixerThread starts and causes a stream volume
2545 // glitch.
2546 //
2547 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002548 }
Eric Laurentdc462862016-07-19 12:29:53 -07002549
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002550 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002551 mEngine->getForceUse(
2552 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002553 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002554 }
2555
Eric Laurent97ac8712018-07-27 18:59:02 -07002556 // Automatically enable the remote submix input when output is started on a re routing mix
2557 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002558 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2559 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002560 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2561 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2562 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002563 "remote-submix",
2564 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002565 }
2566
Eric Laurent96d1dda2022-03-14 17:14:19 +01002567 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2568
Eric Laurente552edb2014-03-10 17:42:56 -07002569 return NO_ERROR;
2570}
2571
Eric Laurent96d1dda2022-03-14 17:14:19 +01002572void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2573 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2574 bool isUnicastActive = isLeUnicastActive();
2575
2576 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002577 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002578 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2579 for (size_t i = 0; i < mOutputs.size(); i++) {
2580 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2581 if (desc != ignoredOutput && desc->isActive()
2582 && ((isUnicastActive &&
2583 !desc->devices().
2584 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2585 || (wasUnicastActive &&
2586 !desc->devices().getDevicesFromTypes(
2587 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2588 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2589 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002590 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002591 // If the device is using preferred mixer attributes, the output need to reopen
2592 // with default configuration when the new selected devices are different from
2593 // current routing devices.
2594 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2595 continue;
2596 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302597 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002598 // re-apply device specific volume if not done by setOutputDevice()
2599 if (!force) {
2600 applyStreamVolumes(desc, newDevices.types(), delayMs);
2601 }
2602 }
2603 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002604 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002605 }
2606}
2607
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002609{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002610 ALOGV("%s portId %d", __FUNCTION__, portId);
2611
2612 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2613 if (outputDesc == 0) {
2614 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002615 return BAD_VALUE;
2616 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002617 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002618
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002619 if (client->hasPreferredDevice(true)) {
2620 // playback activity with preferred device impacts routing occurred, inform upper layers
2621 mpClientInterface->onRoutingUpdated();
2622 }
2623
Eric Laurent97ac8712018-07-27 18:59:02 -07002624 ALOGV("stopOutput() output %d, stream %d, session %d",
2625 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002626
Eric Laurent97ac8712018-07-27 18:59:02 -07002627 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002628
Eric Laurent733ce942017-12-07 12:18:25 -08002629 if (status == NO_ERROR ) {
2630 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002631 } else {
2632 return status;
2633 }
2634
2635 if (outputDesc->devices().size() == 1) {
2636 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2637 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002638 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002639 if (info != nullptr && info->getUid() == client->uid()) {
2640 info->decreaseActiveClient();
2641 if (info->getActiveClientCount() == 0) {
2642 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002643 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002644 }
2645 }
jiabin220eea12024-05-17 17:55:20 +00002646 if (com::android::media::audioserver::
2647 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2648 !outputReopened && outputDesc->isBitPerfect()) {
2649 // Only need to update the clients' internal mute when the output is bit-perfect and it
2650 // is not reopened.
2651 updateClientsInternalMute(outputDesc);
2652 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002653 }
2654 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002655}
2656
Eric Laurent97ac8712018-07-27 18:59:02 -07002657status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2658 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002659{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002660 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002661 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002662 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002663 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002664
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002665 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2666
François Gaffie1c878552018-11-22 16:53:21 +01002667 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2668 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002669 // Automatically disable the remote submix input when output is stopped on a
2670 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002671 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002672 if (isSingleDeviceType(
2673 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002674 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002675 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002676 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2677 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002678 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002679 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 }
2681 }
2682 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002683 if (client->hasPreferredDevice(true) &&
2684 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002685 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002686 forceDeviceUpdate = true;
2687 }
2688
Eric Laurente552edb2014-03-10 17:42:56 -07002689 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002690 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002691
Eric Laurente552edb2014-03-10 17:42:56 -07002692 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002693 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002694 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002695 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002696
2697 // If the routing does not change, if an output is routed on a device using HwGain
2698 // (aka setAudioPortConfig) and there are still active clients following different
2699 // volume group(s), force reapply volume
2700 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2701 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2702
Eric Laurente552edb2014-03-10 17:42:56 -07002703 // delay the device switch by twice the latency because stopOutput() is executed when
2704 // the track stop() command is received and at that time the audio track buffer can
2705 // still contain data that needs to be drained. The latency only covers the audio HAL
2706 // and kernel buffers. Also the latency does not always include additional delay in the
2707 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302708 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002709 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002710
2711 // force restoring the device selection on other active outputs if it differs from the
2712 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002713 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002714 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002715 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002716 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002717 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002718 desc->isActive() &&
2719 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002720 (newDevices != desc->devices())) {
2721 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2722 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002723
jiabin220eea12024-05-17 17:55:20 +00002724 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002725 // If the device is using preferred mixer attributes, the output need to
2726 // reopen with default configuration when the new selected devices are
2727 // different from current routing devices.
2728 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2729 continue;
2730 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302731 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002732
Eric Laurent57de36c2016-09-28 16:59:11 -07002733 // re-apply device specific volume if not done by setOutputDevice()
2734 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002735 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002736 }
Eric Laurente552edb2014-03-10 17:42:56 -07002737 }
2738 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002739 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002740 // update the outputs if stopping one with a stream that can affect notification routing
2741 handleNotificationRoutingForStream(stream);
2742 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002743
2744 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2745 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002746 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002747 }
2748
François Gaffiec005e562018-11-06 15:04:49 +01002749 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002750 selectOutputForMusicEffects();
2751 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002752
2753 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2754
Eric Laurente552edb2014-03-10 17:42:56 -07002755 return NO_ERROR;
2756 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002757 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002758 return INVALID_OPERATION;
2759 }
2760}
2761
jiabinbce0c1d2020-10-05 11:20:18 -07002762bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002763{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002764 ALOGV("%s portId %d", __FUNCTION__, portId);
2765
2766 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2767 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002768 // If an output descriptor is closed due to a device routing change,
2769 // then there are race conditions with releaseOutput from tracks
2770 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2771 // destroyed shortly thereafter.
2772 //
2773 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002774 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002775 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002776 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002777
2778 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002779
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302780 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2781 if (outputDesc->isClientActive(client)) {
2782 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2783 stopOutput(portId);
2784 }
2785
Eric Laurent8fc147b2018-07-22 19:13:55 -07002786 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2787 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002788 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002789 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002790 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002791 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002792 if (--outputDesc->mDirectOpenCount == 0) {
2793 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002794 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002795 }
2796 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302797
Andy Hung39efb7a2018-09-26 15:39:28 -07002798 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002799 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2800 // The output is pending reopened to query dynamic profiles and
2801 // there is no active clients
2802 closeOutput(outputDesc->mIoHandle);
2803 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2804 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2805 if (newOutputDesc == nullptr) {
2806 ALOGE("%s failed to open output", __func__);
2807 }
2808 return true;
2809 }
2810 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002811}
2812
Eric Laurentcaf7f482014-11-25 17:50:47 -08002813status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2814 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002815 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002816 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002817 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002818 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002819 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002820 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002821 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002822 audio_port_handle_t *portId,
2823 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002824{
François Gaffiec005e562018-11-06 15:04:49 +01002825 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002826 "flags %#x attributes=%s requested device ID %d",
2827 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2828 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002829
Eric Laurentad2e7b92017-09-14 20:06:42 -07002830 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002831 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002832 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002833 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002835 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002836 sp<RecordClientDescriptor> clientDesc;
2837 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002838 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002839 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002840
2841 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2842 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2843 return INVALID_OPERATION;
2844 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002845
Francois Gaffie716e1432019-01-14 16:58:59 +01002846 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2847 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002848 }
2849
Paul McLean466dc8e2015-04-17 13:15:36 -06002850 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002851 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002852 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002853
Eric Laurentad2e7b92017-09-14 20:06:42 -07002854 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2855 // possible
2856 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2857 *input != AUDIO_IO_HANDLE_NONE) {
2858 ssize_t index = mInputs.indexOfKey(*input);
2859 if (index < 0) {
2860 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2861 status = BAD_VALUE;
2862 goto error;
2863 }
2864 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 RecordClientVector clients = inputDesc->getClientsForSession(session);
2866 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002867 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2868 status = BAD_VALUE;
2869 goto error;
2870 }
2871 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2872 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002873 // corresponds to a new client and is only permitted from the same UID.
2874 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875 if (clients.size() > 1) {
2876 for (const auto& client : clients) {
2877 // The client map is ordered by key values (portId) and portIds are allocated
2878 // incrementaly. So the first client in this list is the one opened by audio flinger
2879 // when the mmap stream is created and should be ignored as it does not correspond
2880 // to an actual client
2881 if (client == *clients.cbegin()) {
2882 continue;
2883 }
2884 if (uid != client->uid() && !client->isSilenced()) {
2885 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2886 uid, client->portId(), client->uid());
2887 status = INVALID_OPERATION;
2888 goto error;
2889 }
Eric Laurent331679c2018-04-16 17:03:16 -07002890 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002891 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002892 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002893 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002894
Eric Laurentfecbceb2021-02-09 14:46:43 +01002895 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002896 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002897 }
2898
2899 *input = AUDIO_IO_HANDLE_NONE;
2900 *inputType = API_INPUT_INVALID;
2901
Francois Gaffie716e1432019-01-14 16:58:59 +01002902 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002903 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002904 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002905 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002906 ALOGW("%s could not find input mix for attr %s",
2907 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002908 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002909 }
jiabinc1de2df2019-05-07 14:26:40 -07002910 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2911 String8(attr->tags + strlen("addr=")),
2912 AUDIO_FORMAT_DEFAULT);
2913 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002914 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002915 __func__, attributes.source, attributes.tags);
2916 status = BAD_VALUE;
2917 goto error;
2918 }
2919
Kevin Rocard25f9b052019-02-27 15:08:54 -08002920 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2921 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2922 } else {
2923 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2924 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002925 if (virtualDeviceId) {
2926 *virtualDeviceId = policyMix->mVirtualDeviceId;
2927 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002928 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002929 if (explicitRoutingDevice != nullptr) {
2930 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002931 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002932 // Prevent from storing invalid requested device id in clients
2933 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002934 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002935 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2936 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002937 }
François Gaffie11d30102018-11-02 16:09:09 +01002938 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002939 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002940 status = BAD_VALUE;
2941 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002942 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002943 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2944 *inputType = API_INPUT_MIX_CAPTURE;
2945 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002946 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2947 // there is an external policy, but this input is attached to a mix of recorders,
2948 // meaning it receives audio injected into the framework, so the recorder doesn't
2949 // know about it and is therefore considered "legacy"
2950 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002951
2952 if (virtualDeviceId) {
2953 *virtualDeviceId = policyMix->mVirtualDeviceId;
2954 }
François Gaffie11d30102018-11-02 16:09:09 +01002955 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002956 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002957 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002958 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002959 } else {
2960 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002961 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002962
Eric Laurent599c7582015-12-07 18:05:55 -08002963 }
2964
François Gaffiec005e562018-11-06 15:04:49 +01002965 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002966 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002967 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002968 AudioProfileVector profiles;
2969 status_t ret = getProfilesForDevices(
2970 DeviceVector(device), profiles, flags, true /*isInput*/);
2971 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002972 const auto channels = profiles[0]->getChannels();
2973 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2974 config->channel_mask = *channels.begin();
2975 }
2976 const auto sampleRates = profiles[0]->getSampleRates();
2977 if (!sampleRates.empty() &&
2978 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2979 config->sample_rate = *sampleRates.begin();
2980 }
jiabinf1c73972022-04-14 16:28:52 -07002981 config->format = profiles[0]->getFormat();
2982 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002983 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002984 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002985
Marvin Ramine5a122d2023-12-07 13:57:59 +01002986
2987 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2988 *virtualDeviceId = policyMix->mVirtualDeviceId;
2989 }
2990
Eric Laurent8f42ea12018-08-08 09:08:25 -07002991exit:
2992
François Gaffiec005e562018-11-06 15:04:49 +01002993 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2994 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002995
Francois Gaffie716e1432019-01-14 16:58:59 +01002996 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002997 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002998 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999
Mikhail Naganov2996f672019-04-18 12:29:59 -07003000 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003001 requestedDeviceId, attributes.source, flags,
3002 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003003 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003004 // Move (if found) effect for the client session to its input
3005 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003006 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003007
3008 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3009 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003010
Eric Laurent599c7582015-12-07 18:05:55 -08003011 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012
3013error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003014 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003015}
3016
3017
François Gaffie11d30102018-11-02 16:09:09 +01003018audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003019 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003020 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003021 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003022 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003023 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003024{
3025 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003026 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003027 bool isSoundTrigger = false;
3028
François Gaffiec005e562018-11-06 15:04:49 +01003029 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003030 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3031 if (index >= 0) {
3032 input = mSoundTriggerSessions.valueFor(session);
3033 isSoundTrigger = true;
3034 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3035 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3036 } else {
3037 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003038 }
François Gaffiec005e562018-11-06 15:04:49 +01003039 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003040 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003041 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003042 }
3043
Carter Hsua3abb402021-10-26 11:11:20 +08003044 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3045 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3046 }
3047
Eric Laurentfe231122017-11-17 17:48:06 -08003048 // sampling rate and flags may be updated by getInputProfile
3049 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3050 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003051 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003052 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003053 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003054 // find a compatible input profile (not necessarily identical in parameters)
3055 sp<IOProfile> profile = getInputProfile(
3056 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3057 if (profile == nullptr) {
3058 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003059 }
jiabin2fd710d2022-05-02 23:20:22 +00003060
Glenn Kasten05ddca52016-02-11 08:17:12 -08003061 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003062 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003063 if (samplingRate == 0) {
3064 samplingRate = profileSamplingRate;
3065 }
Eric Laurente552edb2014-03-10 17:42:56 -07003066
Eric Laurent322b4d22015-04-03 15:57:54 -07003067 if (profile->getModuleHandle() == 0) {
3068 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003069 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003070 }
3071
Eric Laurentec376dc2021-04-08 20:41:22 +02003072 // Reuse an already opened input if a client with the same session ID already exists
3073 // on that input
3074 for (size_t i = 0; i < mInputs.size(); i++) {
3075 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3076 if (desc->mProfile != profile) {
3077 continue;
3078 }
3079 RecordClientVector clients = desc->clientsList();
3080 for (const auto &client : clients) {
3081 if (session == client->session()) {
3082 return desc->mIoHandle;
3083 }
3084 }
3085 }
3086
Eric Laurent3974e3b2017-12-07 17:58:43 -08003087 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003088 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003089 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003090 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003091 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003092 continue;
3093 }
3094 // if sound trigger, reuse input if used by other sound trigger on same session
3095 // else
3096 // reuse input if active client app is not in IDLE state
3097 //
3098 RecordClientVector clients = desc->clientsList();
3099 bool doClose = false;
3100 for (const auto& client : clients) {
3101 if (isSoundTrigger != client->isSoundTrigger()) {
3102 continue;
3103 }
3104 if (client->isSoundTrigger()) {
3105 if (session == client->session()) {
3106 return desc->mIoHandle;
3107 }
3108 continue;
3109 }
3110 if (client->active() && client->appState() != APP_STATE_IDLE) {
3111 return desc->mIoHandle;
3112 }
3113 doClose = true;
3114 }
3115 if (doClose) {
3116 closeInput(desc->mIoHandle);
3117 } else {
3118 i++;
3119 }
3120 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003121 }
3122
Eric Laurentfe231122017-11-17 17:48:06 -08003123 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003124
Eric Laurentfe231122017-11-17 17:48:06 -08003125 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3126 lConfig.sample_rate = profileSamplingRate;
3127 lConfig.channel_mask = profileChannelMask;
3128 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003129
François Gaffie11d30102018-11-02 16:09:09 +01003130 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003131
3132 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003133 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003134 (profileSamplingRate != lConfig.sample_rate) ||
3135 !audio_formats_match(profileFormat, lConfig.format) ||
3136 (profileChannelMask != lConfig.channel_mask)) {
3137 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003138 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003139 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003140 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003141 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003142 }
Eric Laurent599c7582015-12-07 18:05:55 -08003143 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003144 }
3145
Eric Laurentc722f302014-12-10 11:21:49 -08003146 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003147
Eric Laurent599c7582015-12-07 18:05:55 -08003148 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003149 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003150
Eric Laurent599c7582015-12-07 18:05:55 -08003151 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003152}
3153
Eric Laurent4eb58f12018-12-07 16:41:02 -08003154status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003155{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003156 ALOGV("%s portId %d", __FUNCTION__, portId);
3157
3158 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3159 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003161 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003162 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003163 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003164 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003165 if (client->active()) {
3166 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3167 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003168 }
3169
Eric Laurent8f42ea12018-08-08 09:08:25 -07003170 audio_session_t session = client->session();
3171
Eric Laurent4eb58f12018-12-07 16:41:02 -08003172 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003173
Eric Laurent4eb58f12018-12-07 16:41:02 -08003174 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003175
Eric Laurent4eb58f12018-12-07 16:41:02 -08003176 status_t status = inputDesc->start();
3177 if (status != NO_ERROR) {
3178 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003179 }
Eric Laurente552edb2014-03-10 17:42:56 -07003180
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003181 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003182 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003184
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 // indicate active capture to sound trigger service if starting capture from a mic on
3186 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003187 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003188 if (device != nullptr) {
3189 status = setInputDevice(input, device, true /* force */);
3190 } else {
3191 ALOGW("%s no new input device can be found for descriptor %d",
3192 __FUNCTION__, inputDesc->getId());
3193 status = BAD_VALUE;
3194 }
Eric Laurente552edb2014-03-10 17:42:56 -07003195
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003196 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003197 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003198 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003199 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003200 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3201 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003202 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003203 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003204
François Gaffie11d30102018-11-02 16:09:09 +01003205 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3206 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003207 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003208 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003210
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211 // automatically enable the remote submix output when input is started if not
3212 // used by a policy mix of type MIX_TYPE_RECORDERS
3213 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003214 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003215 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003216 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003217 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003218 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3219 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003220 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003221 if (address != "") {
3222 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003224 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003225 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003226 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003227 } else if (status != NO_ERROR) {
3228 // Restore client activity state.
3229 inputDesc->setClientActive(client, false);
3230 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003231 }
3232
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003233 ALOGV("%s input %d source = %d status = %d exit",
3234 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003235
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003236 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003237}
3238
Eric Laurent8fc147b2018-07-22 19:13:55 -07003239status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003240{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003241 ALOGV("%s portId %d", __FUNCTION__, portId);
3242
3243 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3244 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003245 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003246 return BAD_VALUE;
3247 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003248 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003249 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003250 if (!client->active()) {
3251 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003252 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003253 }
Carter Hsue6139d52021-07-08 10:30:20 +08003254 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003255 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003256
Eric Laurent8f42ea12018-08-08 09:08:25 -07003257 inputDesc->stop();
3258 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003259 auto current_source = inputDesc->source();
3260 setInputDevice(input, getNewInputDevice(inputDesc),
3261 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003263 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003264 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003265 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003266 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3267 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003268 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003269 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003270
3271 // automatically disable the remote submix output when input is stopped if not
3272 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003273 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003274 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003275 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003276 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003277 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3278 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003279 }
3280 if (address != "") {
3281 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3282 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003283 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 }
3285 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003286 resetInputDevice(input);
3287
3288 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3289 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003290 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3291 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003292 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003293 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 }
3295 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003296 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003297 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003298}
3299
Eric Laurent8fc147b2018-07-22 19:13:55 -07003300void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003301{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003302 ALOGV("%s portId %d", __FUNCTION__, portId);
3303
3304 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3305 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003306 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003307 return;
3308 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003309 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003310 audio_io_handle_t input = inputDesc->mIoHandle;
3311
Eric Laurent8f42ea12018-08-08 09:08:25 -07003312 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003313
Andy Hung39efb7a2018-09-26 15:39:28 -07003314 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003315
3316 // If no more clients are present in this session, park effects to an orphan chain
3317 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3318 if (clientsOnSession.size() == 0) {
3319 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3320 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003321 if (inputDesc->getClientCount() > 0) {
3322 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003323 return;
3324 }
3325
Eric Laurent05b90f82014-08-27 15:32:29 -07003326 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003327 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003328 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003329}
3330
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003332{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003334
3335 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003336 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003337 }
3338}
3339
Eric Laurent8f42ea12018-08-08 09:08:25 -07003340void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3341{
3342 stopInput(portId);
3343 releaseInput(portId);
3344}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003345
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003346bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3347 if (input->clientsList().size() == 0
3348 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3349 return true;
3350 }
3351 for (const auto& client : input->clientsList()) {
3352 sp<DeviceDescriptor> device =
3353 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3354 client->session());
3355 if (!input->supportedDevices().contains(device)) {
3356 return true;
3357 }
3358 }
3359 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3360 return false;
3361}
3362
Eric Laurent0dd51852019-04-19 18:18:58 -07003363void AudioPolicyManager::checkCloseInputs() {
3364 // After connecting or disconnecting an input device, close input if:
3365 // - it has no client (was just opened to check profile) OR
3366 // - none of its supported devices are connected anymore OR
3367 // - one of its clients cannot be routed to one of its supported
3368 // devices anymore. Otherwise update device selection
3369 std::vector<audio_io_handle_t> inputsToClose;
3370 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003371 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003372 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003373 }
3374 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003375 for (const audio_io_handle_t handle : inputsToClose) {
3376 ALOGV("%s closing input %d", __func__, handle);
3377 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003378 }
Eric Laurentd4692962014-05-05 18:13:44 -07003379}
3380
Vlad Popa87e0e582024-05-20 18:49:20 -07003381status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3382 const char *address __unused,
3383 bool enabled,
3384 audio_stream_type_t streamToDriveAbs)
3385{
3386 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3387 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3388 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3389 toString(streamToDriveAbs).c_str());
3390 return BAD_VALUE;
3391 }
3392
3393 if (enabled) {
3394 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3395 } else {
3396 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3397 }
3398
3399 return NO_ERROR;
3400}
3401
François Gaffie251c7f02018-11-07 10:41:08 +01003402void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003403{
3404 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003405 if (indexMin < 0 || indexMax < 0) {
3406 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3407 return;
3408 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003409 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003410
3411 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003412 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3413 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003414 continue;
3415 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003416 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003417 }
Eric Laurente552edb2014-03-10 17:42:56 -07003418}
3419
Eric Laurente0720872014-03-11 09:30:41 -07003420status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003421 int index,
3422 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003423{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003424 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003425 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3426 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3427 return NO_ERROR;
3428 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003429 ALOGV("%s: stream %s attributes=%s", __func__,
3430 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003431 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003432}
3433
Eric Laurente0720872014-03-11 09:30:41 -07003434status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003435 int *index,
3436 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003437{
François Gaffiec005e562018-11-06 15:04:49 +01003438 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3439 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003440 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003441 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003442 deviceTypes = mEngine->getOutputDevicesForStream(
3443 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003444 }
jiabin9a3361e2019-10-01 09:38:30 -07003445 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003446}
3447
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003448status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003449 int index,
3450 audio_devices_t device)
3451{
3452 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003453 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3454 if (group == VOLUME_GROUP_NONE) {
3455 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003456 return BAD_VALUE;
3457 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003458 ALOGV("%s: group %d matching with %s index %d",
3459 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003460 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003461 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003462 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003463 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3464 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3465 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3466 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003467 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3468
3469 status = setVolumeCurveIndex(index, device, curves);
3470 if (status != NO_ERROR) {
3471 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3472 return status;
3473 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003474
jiabin9a3361e2019-10-01 09:38:30 -07003475 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003476 auto curCurvAttrs = curves.getAttributes();
3477 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3478 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003479 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003480 } else if (!curves.getStreamTypes().empty()) {
3481 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003482 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003483 } else {
3484 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3485 return BAD_VALUE;
3486 }
jiabin9a3361e2019-10-01 09:38:30 -07003487 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3488 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003489
François Gaffiecfe17322018-11-07 13:41:29 +01003490 // update volume on all outputs and streams matching the following:
3491 // - The requested stream (or a stream matching for volume control) is active on the output
3492 // - The device (or devices) selected by the engine for this stream includes
3493 // the requested device
3494 // - For non default requested device, currently selected device on the output is either the
3495 // requested device or one of the devices selected by the engine for this stream
3496 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3497 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003498 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003499 for (size_t i = 0; i < mOutputs.size(); i++) {
3500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003501 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003502
jiabin9a3361e2019-10-01 09:38:30 -07003503 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3504 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003505 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003506
3507 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003508 continue;
3509 }
3510 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3511 curDevices.find(device) == curDevices.end()) {
3512 continue;
3513 }
3514 bool applyVolume = false;
3515 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3516 curSrcDevices.insert(device);
3517 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003518 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3519 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003520 } else {
3521 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3522 }
3523 if (!applyVolume) {
3524 continue; // next output
3525 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003526 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3527 // If a higher priority strategy is active, and the output is routed to a device with a
3528 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003529 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003530 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003531 // If the volume source is active with higher priority source, ensure at least Sw Muted
3532 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003533 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3534 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3535 false /*preferredDevice*/);
3536 if (activeClients.empty()) {
3537 continue;
3538 }
3539 bool isPreempted = false;
3540 bool isHigherPriority = productStrategy < strategy;
3541 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003542 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003543 ALOGV("%s: Strategy=%d (\nrequester:\n"
3544 " group %d, volumeGroup=%d attributes=%s)\n"
3545 " higher priority source active:\n"
3546 " volumeGroup=%d attributes=%s) \n"
3547 " on output %zu, bailing out", __func__, productStrategy,
3548 group, group, toString(attributes).c_str(),
3549 client->volumeSource(), toString(client->attributes()).c_str(), i);
3550 applyVolume = false;
3551 isPreempted = true;
3552 break;
3553 }
3554 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003555 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003556 applyVolume = true;
3557 }
3558 }
3559 if (isPreempted || applyVolume) {
3560 break;
3561 }
3562 }
3563 if (!applyVolume) {
3564 continue; // next output
3565 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003566 }
François Gaffieed91f582020-01-31 10:35:37 +01003567 //FIXME: workaround for truncated touch sounds
3568 // delayed volume change for system stream to be removed when the problem is
3569 // handled by system UI
3570 status_t volStatus = checkAndSetVolume(
3571 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003572 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003573 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3574 if (volStatus != NO_ERROR) {
3575 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003576 }
3577 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003578
3579 // update voice volume if the an active call route exists
3580 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3581 && (curSrcDevices.find(
3582 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3583 != curSrcDevices.end())) {
3584 bool isVoiceVolSrc;
3585 bool isBtScoVolSrc;
3586 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3587 isVoiceVolSrc, isBtScoVolSrc, __func__)
3588 && (isVoiceVolSrc || isBtScoVolSrc)) {
3589 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3590 }
3591 }
3592
François Gaffiecfe17322018-11-07 13:41:29 +01003593 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3594 return status;
3595}
3596
François Gaffieaaac0fd2018-11-22 17:56:39 +01003597status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003598 audio_devices_t device,
3599 IVolumeCurves &volumeCurves)
3600{
3601 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3602 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003603 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3604 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003605 (index > volumeCurves.getVolumeIndexMax())) {
3606 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3607 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3608 return BAD_VALUE;
3609 }
3610 if (!audio_is_output_device(device)) {
3611 return BAD_VALUE;
3612 }
3613
3614 // Force max volume if stream cannot be muted
3615 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3616
François Gaffieaaac0fd2018-11-22 17:56:39 +01003617 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003618 volumeCurves.addCurrentVolumeIndex(device, index);
3619 return NO_ERROR;
3620}
3621
3622status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3623 int &index,
3624 audio_devices_t device)
3625{
3626 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3627 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003628 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003629 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003630 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003631 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003632 }
jiabin9a3361e2019-10-01 09:38:30 -07003633 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003634}
3635
3636status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3637 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003638 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003639{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003640 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003641 return BAD_VALUE;
3642 }
jiabin9a3361e2019-10-01 09:38:30 -07003643 index = curves.getVolumeIndex(deviceTypes);
3644 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003645 return NO_ERROR;
3646}
3647
3648status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3649 int &index)
3650{
3651 index = getVolumeCurves(attr).getVolumeIndexMin();
3652 return NO_ERROR;
3653}
3654
3655status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3656 int &index)
3657{
3658 index = getVolumeCurves(attr).getVolumeIndexMax();
3659 return NO_ERROR;
3660}
3661
Eric Laurent36829f92017-04-07 19:04:42 -07003662audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003663{
3664 // select one output among several suitable for global effects.
3665 // The priority is as follows:
3666 // 1: An offloaded output. If the effect ends up not being offloadable,
3667 // AudioFlinger will invalidate the track and the offloaded output
3668 // will be closed causing the effect to be moved to a PCM output.
3669 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003670 // 3: The primary output
3671 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003672
François Gaffiec005e562018-11-06 15:04:49 +01003673 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3674 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003675 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003676
Eric Laurent36829f92017-04-07 19:04:42 -07003677 if (outputs.size() == 0) {
3678 return AUDIO_IO_HANDLE_NONE;
3679 }
Eric Laurente552edb2014-03-10 17:42:56 -07003680
Eric Laurent36829f92017-04-07 19:04:42 -07003681 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3682 bool activeOnly = true;
3683
3684 while (output == AUDIO_IO_HANDLE_NONE) {
3685 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3686 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3687 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3688
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003689 for (audio_io_handle_t output : outputs) {
3690 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003691 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003692 continue;
3693 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003694 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3695 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003696 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003697 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003698 }
3699 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003700 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003701 }
3702 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003703 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003704 }
3705 }
3706 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3707 output = outputOffloaded;
3708 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3709 output = outputDeepBuffer;
3710 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3711 output = outputPrimary;
3712 } else {
3713 output = outputs[0];
3714 }
3715 activeOnly = false;
3716 }
3717
3718 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003719 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3720 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003721 mMusicEffectOutput = output;
3722 }
3723
3724 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003725 return output;
3726}
3727
Eric Laurent36829f92017-04-07 19:04:42 -07003728audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3729{
3730 return selectOutputForMusicEffects();
3731}
3732
Eric Laurente0720872014-03-11 09:30:41 -07003733status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003734 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003735 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003736 int session,
3737 int id)
3738{
Shunkai Yao29d10572024-03-19 04:31:47 +00003739 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003740 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003741 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003742 index = mInputs.indexOfKey(io);
3743 if (index < 0) {
3744 ALOGW("registerEffect() unknown io %d", io);
3745 return INVALID_OPERATION;
3746 }
Eric Laurente552edb2014-03-10 17:42:56 -07003747 }
3748 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003749 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3750 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3751 || strategy == PRODUCT_STRATEGY_NONE));
3752 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003753}
3754
Eric Laurentc241b0d2018-11-28 09:08:49 -08003755status_t AudioPolicyManager::unregisterEffect(int id)
3756{
3757 if (mEffects.getEffect(id) == nullptr) {
3758 return INVALID_OPERATION;
3759 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003760 if (mEffects.isEffectEnabled(id)) {
3761 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3762 setEffectEnabled(id, false);
3763 }
3764 return mEffects.unregisterEffect(id);
3765}
3766
3767status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3768{
3769 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3770 if (effect == nullptr) {
3771 return INVALID_OPERATION;
3772 }
3773
3774 status_t status = mEffects.setEffectEnabled(id, enabled);
3775 if (status == NO_ERROR) {
3776 mInputs.trackEffectEnabled(effect, enabled);
3777 }
3778 return status;
3779}
3780
Eric Laurent6c796322019-04-09 14:13:17 -07003781
3782status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3783{
3784 mEffects.moveEffects(ids, io);
3785 return NO_ERROR;
3786}
3787
Eric Laurentc75307b2015-03-17 15:29:32 -07003788bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3789{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003790 auto vs = toVolumeSource(stream, false);
3791 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003792}
3793
3794bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3795{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003796 auto vs = toVolumeSource(stream, false);
3797 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003798}
3799
Eric Laurente0720872014-03-11 09:30:41 -07003800bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003801{
3802 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003803 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003804 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003805 return true;
3806 }
3807 }
3808 return false;
3809}
3810
Eric Laurent275e8e92014-11-30 15:14:47 -08003811// Register a list of custom mixes with their attributes and format.
3812// When a mix is registered, corresponding input and output profiles are
3813// added to the remote submix hw module. The profile contains only the
3814// parameters (sampling rate, format...) specified by the mix.
3815// The corresponding input remote submix device is also connected.
3816//
3817// When a remote submix device is connected, the address is checked to select the
3818// appropriate profile and the corresponding input or output stream is opened.
3819//
3820// When capture starts, getInputForAttr() will:
3821// - 1 look for a mix matching the address passed in attribtutes tags if any
3822// - 2 if none found, getDeviceForInputSource() will:
3823// - 2.1 look for a mix matching the attributes source
3824// - 2.2 if none found, default to device selection by policy rules
3825// At this time, the corresponding output remote submix device is also connected
3826// and active playback use cases can be transferred to this mix if needed when reconnecting
3827// after AudioTracks are invalidated
3828//
3829// When playback starts, getOutputForAttr() will:
3830// - 1 look for a mix matching the address passed in attribtutes tags if any
3831// - 2 if none found, look for a mix matching the attributes usage
3832// - 3 if none found, default to device and output selection by policy rules.
3833
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003834status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003835{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003836 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3837 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003838 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003839 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003840 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003841 // examine each mix's route type
3842 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003843 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003844 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3845 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3846 ALOGE("Unsupported Policy Mix %zu of %zu: "
3847 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3848 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003849 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003850 break;
3851 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003852 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3853 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003854 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003855 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3856 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003857 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003858 rSubmixModule = mHwModules.getModuleFromName(
3859 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3860 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003861 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003862 i);
3863 res = INVALID_OPERATION;
3864 break;
3865 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003866 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003867
Eric Laurent97ac8712018-07-27 18:59:02 -07003868 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003869 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003870 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003871 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003872 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3873 } else {
3874 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3875 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003876 }
François Gaffie036e1e92015-03-19 10:16:24 +01003877
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003878 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003879 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003880 res = INVALID_OPERATION;
3881 break;
3882 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003883 audio_config_t outputConfig = mix.mFormat;
3884 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003885 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3886 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003887 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3888 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003889 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003890 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3891 audio_is_linear_pcm(outputConfig.format)
3892 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003893 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003894 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3895 audio_is_linear_pcm(inputConfig.format)
3896 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003897
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003898 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003899 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003900 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003901 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003902 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003903 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003904 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003905 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3906 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003907 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003908 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003909 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003910
3911 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3912 mix.mDeviceType, mix.mDeviceAddress,
3913 String8(), AUDIO_FORMAT_DEFAULT);
3914 if (device == nullptr) {
3915 res = INVALID_OPERATION;
3916 break;
3917 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003918
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003919 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003920 // First try to find an already opened output supporting the device
3921 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003922 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003923
Eric Laurentc529cf62020-04-17 18:19:10 -07003924 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003925 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003926 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003927 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003928 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003929 } else {
3930 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003931 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003932 }
3933 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003934 // If no output found, try to find a direct output profile supporting the device
3935 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3936 sp<HwModule> module = mHwModules[i];
3937 for (size_t j = 0;
3938 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3939 j++) {
3940 sp<IOProfile> profile = module->getOutputProfiles()[j];
3941 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3942 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3943 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003944 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003945 res = INVALID_OPERATION;
3946 } else {
3947 foundOutput = true;
3948 }
3949 }
3950 }
3951 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003952 if (res != NO_ERROR) {
3953 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003954 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003955 res = INVALID_OPERATION;
3956 break;
3957 } else if (!foundOutput) {
3958 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003959 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003960 res = INVALID_OPERATION;
3961 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003962 } else {
3963 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003964 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003965 }
Eric Laurentc722f302014-12-10 11:21:49 -08003966 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003967 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003968 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003969 if (audio_flags::audio_mix_ownership()) {
3970 // Only unregister mixes that were actually registered to not accidentally unregister
3971 // mixes that already existed previously.
3972 unregisterPolicyMixes(registeredMixes);
3973 registeredMixes.clear();
3974 } else {
3975 unregisterPolicyMixes(mixes);
3976 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003977 } else if (checkOutputs) {
3978 checkForDeviceAndOutputChanges();
3979 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003980 }
3981 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003982}
3983
3984status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3985{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003986 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003987 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003988 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003989 sp<HwModule> rSubmixModule;
3990 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003991 for (const auto& mix : mixes) {
3992 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003993
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003994 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003995 rSubmixModule = mHwModules.getModuleFromName(
3996 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3997 if (rSubmixModule == 0) {
3998 res = INVALID_OPERATION;
3999 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004000 }
4001 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004002
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004003 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004004
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004005 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 res = INVALID_OPERATION;
4007 continue;
4008 }
4009
Marvin Ramin0783e202024-03-05 12:45:50 +01004010 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004011 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004012 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4013 status_t currentRes =
4014 setDeviceConnectionStateInt(device,
4015 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4016 address.c_str(),
4017 "remote-submix",
4018 AUDIO_FORMAT_DEFAULT);
4019 if (!audio_flags::audio_mix_ownership()) {
4020 res = currentRes;
4021 }
4022 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004023 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004024 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004025 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004026 }
4027 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004028 }
jiabin5740f082019-08-19 15:08:30 -07004029 rSubmixModule->removeOutputProfile(address.c_str());
4030 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004031
Kevin Rocard153f92d2018-12-18 18:33:28 -08004032 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004033 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004034 res = INVALID_OPERATION;
4035 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004036 } else {
4037 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004038 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004039 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004040 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004041
4042 if (res == NO_ERROR && checkOutputs) {
4043 checkForDeviceAndOutputChanges();
4044 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004045 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004046 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004047}
4048
Marvin Raminbdefaf02023-11-01 09:10:32 +01004049status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4050 if (!audio_flags::audio_mix_test_api()) {
4051 return INVALID_OPERATION;
4052 }
4053
4054 _aidl_return.clear();
4055 _aidl_return.reserve(mPolicyMixes.size());
4056 for (const auto &policyMix: mPolicyMixes) {
4057 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4058 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4059 policyMix->mCbFlags);
4060 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004061 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004062 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004063 }
4064
Vlad Popaa5d73f32024-03-08 16:05:38 -08004065 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004066 return OK;
4067}
4068
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004069status_t AudioPolicyManager::updatePolicyMix(
4070 const AudioMix& mix,
4071 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4072 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4073 if (res == NO_ERROR) {
4074 checkForDeviceAndOutputChanges();
4075 updateCallAndOutputRouting();
4076 }
4077 return res;
4078}
4079
Mikhail Naganov100f0122018-11-29 11:22:16 -08004080void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4081{
4082 size_t i = 0;
4083 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4084 for (const auto& fmt : mManualSurroundFormats) {
4085 if (i++ != 0) dst->append(", ");
4086 std::string sfmt;
4087 FormatConverter::toString(fmt, sfmt);
4088 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4089 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4090 }
4091}
4092
Eric Laurentc529cf62020-04-17 18:19:10 -07004093// Returns true if all devices types match the predicate and are supported by one HW module
4094bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004095 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004096 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004097 const char *context,
4098 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004099 for (size_t i = 0; i < devices.size(); i++) {
4100 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004101 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004102 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004103 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004104 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004105 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004106 return false;
4107 }
4108 }
4109 return true;
4110}
4111
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004112void AudioPolicyManager::changeOutputDevicesMuteState(
4113 const AudioDeviceTypeAddrVector& devices) {
4114 ALOGVV("%s() num devices %zu", __func__, devices.size());
4115
4116 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4117 getSoftwareOutputsForDevices(devices);
4118
4119 for (size_t i = 0; i < outputs.size(); i++) {
4120 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4121 DeviceVector prevDevices = outputDesc->devices();
4122 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4123 }
4124}
4125
4126std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4127 const AudioDeviceTypeAddrVector& devices) const
4128{
4129 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4130 DeviceVector deviceDescriptors;
4131 for (size_t j = 0; j < devices.size(); j++) {
4132 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4133 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4134 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4135 ALOGE("%s: device type %#x address %s not supported or not an output device",
4136 __func__, devices[j].mType, devices[j].getAddress());
4137 continue;
4138 }
4139 deviceDescriptors.add(desc);
4140 }
4141 for (size_t i = 0; i < mOutputs.size(); i++) {
4142 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4143 continue;
4144 }
4145 outputs.push_back(mOutputs.valueAt(i));
4146 }
4147 return outputs;
4148}
4149
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004150status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004151 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004152 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004153 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4154 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004155 }
4156 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004157 if (res != NO_ERROR) {
4158 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4159 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004160 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004161
4162 checkForDeviceAndOutputChanges();
4163 updateCallAndOutputRouting();
4164
4165 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004166}
4167
4168status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4169 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004170 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4171 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004172 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004173 __FUNCTION__, uid);
4174 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004175 }
4176
Eric Laurentc529cf62020-04-17 18:19:10 -07004177 checkForDeviceAndOutputChanges();
4178 updateCallAndOutputRouting();
4179
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004180 return res;
4181}
4182
Eric Laurent2517af32020-11-25 15:31:27 +01004183
jiabin0a488932020-08-07 17:32:40 -07004184status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4185 device_role_t role,
4186 const AudioDeviceTypeAddrVector &devices) {
4187 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4188 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004189
Eric Laurentc529cf62020-04-17 18:19:10 -07004190 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004191 return BAD_VALUE;
4192 }
jiabin0a488932020-08-07 17:32:40 -07004193 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004194 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004195 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4196 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004197 return status;
4198 }
4199
4200 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004201
4202 bool forceVolumeReeval = false;
4203 // FIXME: workaround for truncated touch sounds
4204 // to be removed when the problem is handled by system UI
4205 uint32_t delayMs = 0;
4206 if (strategy == mCommunnicationStrategy) {
4207 forceVolumeReeval = true;
4208 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4209 updateInputRouting();
4210 }
4211 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004212
4213 return NO_ERROR;
4214}
4215
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004216void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4217 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004218{
4219 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004220 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004221 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004222 // Only apply special touch sound delay once
4223 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004224 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004225 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004226 for (size_t i = 0; i < mOutputs.size(); i++) {
4227 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4228 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004229 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4230 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004231 // As done in setDeviceConnectionState, we could also fix default device issue by
4232 // preventing the force re-routing in case of default dev that distinguishes on address.
4233 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004234 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004235 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004236 // If the device is using preferred mixer attributes, the output need to reopen
4237 // with default configuration when the new selected devices are different from
4238 // current routing devices.
4239 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4240 continue;
4241 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304242
4243 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4244 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004245 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004246 // Only apply special touch sound delay once
4247 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004248 }
4249 if (forceVolumeReeval && !newDevices.isEmpty()) {
4250 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4251 }
4252 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004253 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004254 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004255}
4256
Eric Laurent2517af32020-11-25 15:31:27 +01004257void AudioPolicyManager::updateInputRouting() {
4258 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304259 // Skip for hotword recording as the input device switch
4260 // is handled within sound trigger HAL
4261 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4262 continue;
4263 }
Eric Laurent2517af32020-11-25 15:31:27 +01004264 auto newDevice = getNewInputDevice(activeDesc);
4265 // Force new input selection if the new device can not be reached via current input
4266 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4267 setInputDevice(activeDesc->mIoHandle, newDevice);
4268 } else {
4269 closeInput(activeDesc->mIoHandle);
4270 }
4271 }
4272}
4273
Paul Wang5d7cdb52022-11-22 09:45:06 +00004274status_t
4275AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4276 device_role_t role,
4277 const AudioDeviceTypeAddrVector &devices) {
4278 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4279 dumpAudioDeviceTypeAddrVector(devices).c_str());
4280
Eric Laurent78fedbf2023-03-09 14:40:44 +01004281 if (!areAllDevicesSupported(
4282 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004283 return BAD_VALUE;
4284 }
4285 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4286 if (status != NO_ERROR) {
4287 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4288 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4289 return status;
4290 }
4291
4292 checkForDeviceAndOutputChanges();
4293
4294 bool forceVolumeReeval = false;
4295 // TODO(b/263479999): workaround for truncated touch sounds
4296 // to be removed when the problem is handled by system UI
4297 uint32_t delayMs = 0;
4298 if (strategy == mCommunnicationStrategy) {
4299 forceVolumeReeval = true;
4300 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4301 updateInputRouting();
4302 }
4303 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4304
4305 return NO_ERROR;
4306}
4307
4308status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4309 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004310{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004311 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004312
Paul Wang5d7cdb52022-11-22 09:45:06 +00004313 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004314 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004315 ALOGW_IF(status != NAME_NOT_FOUND,
4316 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004317 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004318 return status;
4319 }
4320
4321 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004322
4323 bool forceVolumeReeval = false;
4324 // FIXME: workaround for truncated touch sounds
4325 // to be removed when the problem is handled by system UI
4326 uint32_t delayMs = 0;
4327 if (strategy == mCommunnicationStrategy) {
4328 forceVolumeReeval = true;
4329 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4330 updateInputRouting();
4331 }
4332 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004333
4334 return NO_ERROR;
4335}
4336
jiabin0a488932020-08-07 17:32:40 -07004337status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4338 device_role_t role,
4339 AudioDeviceTypeAddrVector &devices) {
4340 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004341}
4342
Jiabin Huang3b98d322020-09-03 17:54:16 +00004343status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4344 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4345 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4346 dumpAudioDeviceTypeAddrVector(devices).c_str());
4347
Mikhail Naganov55773032020-10-01 15:08:13 -07004348 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004349 return BAD_VALUE;
4350 }
4351 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4352 ALOGW_IF(status != NO_ERROR,
4353 "Engine could not set preferred devices %s for audio source %d role %d",
4354 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4355
4356 return status;
4357}
4358
4359status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4360 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4361 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4362 dumpAudioDeviceTypeAddrVector(devices).c_str());
4363
Mikhail Naganov55773032020-10-01 15:08:13 -07004364 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004365 return BAD_VALUE;
4366 }
4367 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4368 ALOGW_IF(status != NO_ERROR,
4369 "Engine could not add preferred devices %s for audio source %d role %d",
4370 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4371
Eric Laurent2517af32020-11-25 15:31:27 +01004372 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004373 return status;
4374}
4375
4376status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4377 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4378{
4379 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4380 dumpAudioDeviceTypeAddrVector(devices).c_str());
4381
Eric Laurent78fedbf2023-03-09 14:40:44 +01004382 if (!areAllDevicesSupported(
4383 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004384 return BAD_VALUE;
4385 }
4386
4387 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4388 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004389 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004390 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004391 if (status == NO_ERROR) {
4392 updateInputRouting();
4393 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004394 return status;
4395}
4396
4397status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4398 device_role_t role) {
4399 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4400
4401 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004402 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004403 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004404 if (status == NO_ERROR) {
4405 updateInputRouting();
4406 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004407 return status;
4408}
4409
4410status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4411 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4412 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4413}
4414
Oscar Azucena90e77632019-11-27 17:12:28 -08004415status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004416 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004417 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004418 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4419 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004420 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004421 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4422 if (status != NO_ERROR) {
4423 ALOGE("%s() could not set device affinity for userId %d",
4424 __FUNCTION__, userId);
4425 return status;
4426 }
4427
4428 // reevaluate outputs for all devices
4429 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004430 changeOutputDevicesMuteState(devices);
4431 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4432 true /* skipDelays */);
4433 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004434
4435 return NO_ERROR;
4436}
4437
4438status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004439 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004440 AudioDeviceTypeAddrVector devices;
4441 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004442 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4443 if (status != NO_ERROR) {
4444 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4445 __FUNCTION__, userId);
4446 return status;
4447 }
4448
4449 // reevaluate outputs for all devices
4450 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004451 changeOutputDevicesMuteState(devices);
4452 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4453 true /* skipDelays */);
4454 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004455
4456 return NO_ERROR;
4457}
4458
Andy Hungc29d82b2018-10-05 12:23:17 -07004459void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004460{
Andy Hungc29d82b2018-10-05 12:23:17 -07004461 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004462 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004463 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004464 std::string stateLiteral;
4465 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004466 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004467 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4468 "communications", "media", "record", "dock", "system",
4469 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4470 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4471 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004472 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4473 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4474 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4475 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4476 dst->append(" (MANUAL: ");
4477 dumpManualSurroundFormats(dst);
4478 dst->append(")");
4479 }
4480 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004481 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004482 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4483 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004484 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004485 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004486
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004487 dst->append("\n");
4488 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4489 dst->append("\n");
4490 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004491 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004492 mOutputs.dump(dst);
4493 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004494 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004495 mAudioPatches.dump(dst);
4496 mPolicyMixes.dump(dst);
4497 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004498
Kevin Rocardb99cc752019-03-21 20:52:24 -07004499 dst->appendFormat(" AllowedCapturePolicies:\n");
4500 for (auto& policy : mAllowedCapturePolicies) {
4501 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4502 }
4503
jiabina84c3d32022-12-02 18:59:55 +00004504 dst->appendFormat(" Preferred mixer audio configuration:\n");
4505 for (const auto it : mPreferredMixerAttrInfos) {
4506 dst->appendFormat(" - device port id: %d\n", it.first);
4507 for (const auto preferredMixerInfoIt : it.second) {
4508 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4509 preferredMixerInfoIt.second->dump(dst);
4510 }
4511 }
4512
François Gaffiec005e562018-11-06 15:04:49 +01004513 dst->appendFormat("\nPolicy Engine dump:\n");
4514 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004515
4516 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4517 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4518 dst->appendFormat(" - device type: %s, driving stream %d\n",
4519 dumpDeviceTypes({it.first}).c_str(),
4520 mEngine->getVolumeGroupForAttributes(it.second));
4521 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004522}
4523
4524status_t AudioPolicyManager::dump(int fd)
4525{
4526 String8 result;
4527 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004528 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004529 return NO_ERROR;
4530}
4531
Kevin Rocardb99cc752019-03-21 20:52:24 -07004532status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4533{
4534 mAllowedCapturePolicies[uid] = capturePolicy;
4535 return NO_ERROR;
4536}
4537
Eric Laurente552edb2014-03-10 17:42:56 -07004538// This function checks for the parameters which can be offloaded.
4539// This can be enhanced depending on the capability of the DSP and policy
4540// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004541audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004542{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004543 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004544 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004545 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004546 offloadInfo.format,
4547 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4548 offloadInfo.has_video);
4549
jiabin2b9d5a12021-12-10 01:06:29 +00004550 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004551 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004552 }
4553
4554 // See if there is a profile to support this.
4555 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004556 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004557 offloadInfo.sample_rate,
4558 offloadInfo.format,
4559 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004560 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4561 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004562 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4563 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4564 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004565 if (profile == nullptr) {
4566 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4567 }
4568 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4569 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4570 }
4571 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004572}
4573
Michael Chana94fbb22018-04-24 14:31:19 +10004574bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4575 const audio_attributes_t& attributes) {
4576 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004577 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004578 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4579 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004580 config.sample_rate,
4581 config.format,
4582 config.channel_mask,
4583 output_flags,
4584 true /* directOnly */);
4585 ALOGV("%s() profile %sfound with name: %s, "
4586 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4587 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004588 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004589 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004590
4591 // also try the MSD module if compatible profile not found
4592 if (profile == nullptr) {
4593 profile = getMsdProfileForOutput(outputDevices,
4594 config.sample_rate,
4595 config.format,
4596 config.channel_mask,
4597 output_flags,
4598 true /* directOnly */);
4599 ALOGV("%s() MSD profile %sfound with name: %s, "
4600 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4601 __FUNCTION__, profile != 0 ? "" : "NOT ",
4602 (profile != 0 ? profile->getTagName().c_str() : "null"),
4603 config.sample_rate, config.format, config.channel_mask, output_flags);
4604 }
4605 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004606}
4607
jiabin2b9d5a12021-12-10 01:06:29 +00004608bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4609 bool durationIgnored) {
4610 if (mMasterMono) {
4611 return false; // no offloading if mono is set.
4612 }
4613
4614 // Check if offload has been disabled
4615 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4616 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4617 return false;
4618 }
4619
4620 // Check if stream type is music, then only allow offload as of now.
4621 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4622 {
4623 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4624 return false;
4625 }
4626
4627 //TODO: enable audio offloading with video when ready
4628 const bool allowOffloadWithVideo =
4629 property_get_bool("audio.offload.video", false /* default_value */);
4630 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4631 ALOGV("%s: has_video == true, returning false", __func__);
4632 return false;
4633 }
4634
4635 //If duration is less than minimum value defined in property, return false
4636 const int min_duration_secs = property_get_int32(
4637 "audio.offload.min.duration.secs", -1 /* default_value */);
4638 if (!durationIgnored) {
4639 if (min_duration_secs >= 0) {
4640 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4641 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4642 __func__, min_duration_secs);
4643 return false;
4644 }
4645 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4646 ALOGV("%s: Offload denied by duration < default min(=%u)",
4647 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4648 return false;
4649 }
4650 }
4651
4652 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4653 // creating an offloaded track and tearing it down immediately after start when audioflinger
4654 // detects there is an active non offloadable effect.
4655 // FIXME: We should check the audio session here but we do not have it in this context.
4656 // This may prevent offloading in rare situations where effects are left active by apps
4657 // in the background.
4658 if (mEffects.isNonOffloadableEffectEnabled()) {
4659 return false;
4660 }
4661
4662 return true;
4663}
4664
4665audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4666 const audio_config_t *config) {
4667 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4668 offloadInfo.format = config->format;
4669 offloadInfo.sample_rate = config->sample_rate;
4670 offloadInfo.channel_mask = config->channel_mask;
4671 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4672 offloadInfo.has_video = false;
4673 offloadInfo.is_streaming = false;
4674 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4675
4676 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4677 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4678 audio_flags_to_audio_output_flags(attr->flags, &flags);
4679 // only retain flags that will drive compressed offload or passthrough
4680 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4681 if (offloadPossible) {
4682 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4683 }
4684 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4685
Dorin Drimusfae3c642022-03-17 18:36:30 +01004686 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004687 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004688 DeviceVector outputDevices = engineOutputDevices;
4689 // the MSD module checks for different conditions and output devices
4690 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4691 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4692 continue;
4693 }
4694 outputDevices = getMsdAudioOutDevices();
4695 }
jiabin2b9d5a12021-12-10 01:06:29 +00004696 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004697 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004698 config->sample_rate, nullptr /*updatedSamplingRate*/,
4699 config->format, nullptr /*updatedFormat*/,
4700 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004701 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004702 continue;
4703 }
4704 // reject profiles not corresponding to a device currently available
4705 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4706 continue;
4707 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004708 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4709 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004710 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004711 != AUDIO_DIRECT_NOT_SUPPORTED) {
4712 // Already reports offload gapless supported. No need to report offload support.
4713 continue;
4714 }
4715 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4716 != AUDIO_OUTPUT_FLAG_NONE) {
4717 // If offload gapless is reported, no need to report offload support.
4718 directMode = (audio_direct_mode_t) ((directMode &
4719 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4720 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4721 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004722 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004723 }
4724 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004725 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004726 }
4727 }
4728 }
4729 return directMode;
4730}
4731
Dorin Drimusf2196d82022-01-03 12:11:18 +01004732status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4733 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004734 if (mEffects.isNonOffloadableEffectEnabled()) {
4735 return OK;
4736 }
jiabinf1c73972022-04-14 16:28:52 -07004737 DeviceVector devices;
4738 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004739 if (status != OK) {
4740 return status;
4741 }
4742 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4743 if (devices.empty()) {
4744 return OK; // no output devices for the attributes
4745 }
jiabinf1c73972022-04-14 16:28:52 -07004746 return getProfilesForDevices(devices, audioProfilesVector,
4747 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004748}
4749
jiabina84c3d32022-12-02 18:59:55 +00004750status_t AudioPolicyManager::getSupportedMixerAttributes(
4751 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4752 ALOGV("%s, portId=%d", __func__, portId);
4753 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4754 if (deviceDescriptor == nullptr) {
4755 ALOGE("%s the requested device is currently unavailable", __func__);
4756 return BAD_VALUE;
4757 }
jiabin96daffc2023-05-11 17:51:55 +00004758 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4759 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4760 deviceDescriptor->type());
4761 return BAD_VALUE;
4762 }
jiabina84c3d32022-12-02 18:59:55 +00004763 for (const auto& hwModule : mHwModules) {
4764 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4765 if (curProfile->supportsDevice(deviceDescriptor)) {
4766 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4767 }
4768 }
4769 }
4770 return NO_ERROR;
4771}
4772
4773status_t AudioPolicyManager::setPreferredMixerAttributes(
4774 const audio_attributes_t *attr,
4775 audio_port_handle_t portId,
4776 uid_t uid,
4777 const audio_mixer_attributes_t *mixerAttributes) {
4778 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4779 "mixerBehavior=%d}, uid=%d, portId=%u",
4780 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4781 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4782 mixerAttributes->mixer_behavior, uid, portId);
4783 if (attr->usage != AUDIO_USAGE_MEDIA) {
4784 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4785 return BAD_VALUE;
4786 }
4787 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4788 if (deviceDescriptor == nullptr) {
4789 ALOGE("%s the requested device is currently unavailable", __func__);
4790 return BAD_VALUE;
4791 }
4792 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4793 ALOGE("%s(%d), type=%d, is not a usb output device",
4794 __func__, portId, deviceDescriptor->type());
4795 return BAD_VALUE;
4796 }
4797
4798 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4799 audio_flags_to_audio_output_flags(attr->flags, &flags);
4800 flags = (audio_output_flags_t) (flags |
4801 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4802 sp<IOProfile> profile = nullptr;
4803 DeviceVector devices(deviceDescriptor);
4804 for (const auto& hwModule : mHwModules) {
4805 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4806 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004807 && curProfile->getCompatibilityScore(
4808 devices,
4809 mixerAttributes->config.sample_rate,
4810 nullptr /*updatedSamplingRate*/,
4811 mixerAttributes->config.format,
4812 nullptr /*updatedFormat*/,
4813 mixerAttributes->config.channel_mask,
4814 nullptr /*updatedChannelMask*/,
4815 flags,
4816 false /*exactMatchRequiredForInputFlags*/)
4817 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004818 profile = curProfile;
4819 break;
4820 }
4821 }
4822 }
4823 if (profile == nullptr) {
4824 ALOGE("%s, there is no compatible profile found", __func__);
4825 return BAD_VALUE;
4826 }
4827
4828 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4829 sp<PreferredMixerAttributesInfo>::make(
4830 uid, portId, profile, flags, *mixerAttributes);
4831 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4832 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4833
4834 // If 1) there is any client from the preferred mixer configuration owner that is currently
4835 // active and matches the strategy and 2) current output is on the preferred device and the
4836 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4837 // configuration.
4838 std::vector<audio_io_handle_t> outputsToReopen;
4839 for (size_t i = 0; i < mOutputs.size(); i++) {
4840 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004841 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4842 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004843 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004844 } else {
4845 for (const auto &client: output->getActiveClients()) {
4846 if (client->uid() == uid && client->strategy() == strategy) {
4847 client->setIsInvalid();
4848 outputsToReopen.push_back(output->mIoHandle);
4849 }
jiabina84c3d32022-12-02 18:59:55 +00004850 }
4851 }
4852 }
4853 }
4854 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4855 config.sample_rate = mixerAttributes->config.sample_rate;
4856 config.channel_mask = mixerAttributes->config.channel_mask;
4857 config.format = mixerAttributes->config.format;
4858 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004859 sp<SwAudioOutputDescriptor> desc =
4860 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4861 if (desc == nullptr) {
4862 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4863 continue;
4864 }
jiabin220eea12024-05-17 17:55:20 +00004865 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004866 }
4867
4868 return NO_ERROR;
4869}
4870
4871sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004872 audio_port_handle_t devicePortId,
4873 product_strategy_t strategy,
4874 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004875 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4876 if (it == mPreferredMixerAttrInfos.end()) {
4877 return nullptr;
4878 }
jiabind9a58d32023-06-01 17:57:30 +00004879 if (activeBitPerfectPreferred) {
4880 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004881 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004882 return info;
4883 }
4884 }
jiabina84c3d32022-12-02 18:59:55 +00004885 }
jiabind9a58d32023-06-01 17:57:30 +00004886 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4887 return strategyMatchedMixerAttrInfoIt == it->second.end()
4888 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004889}
4890
4891status_t AudioPolicyManager::getPreferredMixerAttributes(
4892 const audio_attributes_t *attr,
4893 audio_port_handle_t portId,
4894 audio_mixer_attributes_t* mixerAttributes) {
4895 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4896 portId, mEngine->getProductStrategyForAttributes(*attr));
4897 if (info == nullptr) {
4898 return NAME_NOT_FOUND;
4899 }
4900 *mixerAttributes = info->getMixerAttributes();
4901 return NO_ERROR;
4902}
4903
4904status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4905 audio_port_handle_t portId,
4906 uid_t uid) {
4907 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4908 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4909 if (preferredMixerAttrInfo == nullptr) {
4910 return NAME_NOT_FOUND;
4911 }
4912 if (preferredMixerAttrInfo->getUid() != uid) {
4913 ALOGE("%s, requested uid=%d, owned uid=%d",
4914 __func__, uid, preferredMixerAttrInfo->getUid());
4915 return PERMISSION_DENIED;
4916 }
4917 mPreferredMixerAttrInfos[portId].erase(strategy);
4918 if (mPreferredMixerAttrInfos[portId].empty()) {
4919 mPreferredMixerAttrInfos.erase(portId);
4920 }
4921
4922 // Reconfig existing output
4923 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4924 for (size_t i = 0; i < mOutputs.size(); i++) {
4925 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4926 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4927 }
4928 }
4929 for (const auto output : potentialOutputsToReopen) {
4930 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4931 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4932 preferredMixerAttrInfo->getFlags())) {
4933 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4934 }
4935 }
4936 return NO_ERROR;
4937}
4938
Eric Laurent6a94d692014-05-20 11:18:06 -07004939status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4940 audio_port_type_t type,
4941 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004942 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004943 unsigned int *generation)
4944{
jiabin19cdba52020-11-24 11:28:58 -08004945 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4946 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 return BAD_VALUE;
4948 }
4949 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004950 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 *num_ports = 0;
4952 }
4953
4954 size_t portsWritten = 0;
4955 size_t portsMax = *num_ports;
4956 *num_ports = 0;
4957 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004958 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4959 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004961 for (const auto& dev : mAvailableOutputDevices) {
4962 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004963 continue;
4964 }
4965 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004966 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004967 }
4968 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 }
4971 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004972 for (const auto& dev : mAvailableInputDevices) {
4973 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004974 continue;
4975 }
4976 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004977 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004978 }
4979 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 }
4982 }
4983 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4984 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4985 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4986 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4987 }
4988 *num_ports += mInputs.size();
4989 }
4990 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004991 size_t numOutputs = 0;
4992 for (size_t i = 0; i < mOutputs.size(); i++) {
4993 if (!mOutputs[i]->isDuplicated()) {
4994 numOutputs++;
4995 if (portsWritten < portsMax) {
4996 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4997 }
4998 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 }
Eric Laurent84c70242014-06-23 08:46:27 -07005000 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 }
5002 }
jiabina84c3d32022-12-02 18:59:55 +00005003
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005005 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 return NO_ERROR;
5007}
5008
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005009status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5010 std::vector<media::AudioPortFw>* _aidl_return) {
5011 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5012 audio_port_v7 port;
5013 dev->toAudioPort(&port);
5014 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5015 _aidl_return->push_back(std::move(aidlPort));
5016 return OK;
5017 };
5018
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005019 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005020 for (const auto& dev : module->getDeclaredDevices()) {
5021 if (role == media::AudioPortRole::NONE ||
5022 ((role == media::AudioPortRole::SOURCE)
5023 == audio_is_input_device(dev->type()))) {
5024 RETURN_STATUS_IF_ERROR(pushPort(dev));
5025 }
5026 }
5027 }
5028 return OK;
5029}
5030
jiabin19cdba52020-11-24 11:28:58 -08005031status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005032{
Eric Laurent99fcae42018-05-17 16:59:18 -07005033 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5034 return BAD_VALUE;
5035 }
5036 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5037 if (dev != 0) {
5038 dev->toAudioPort(port);
5039 return NO_ERROR;
5040 }
5041 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5042 if (dev != 0) {
5043 dev->toAudioPort(port);
5044 return NO_ERROR;
5045 }
5046 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5047 if (out != 0) {
5048 out->toAudioPort(port);
5049 return NO_ERROR;
5050 }
5051 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5052 if (in != 0) {
5053 in->toAudioPort(port);
5054 return NO_ERROR;
5055 }
5056 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005057}
5058
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005059status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5060 audio_patch_handle_t *handle,
5061 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005062{
François Gaffieafd4cea2019-11-18 15:50:22 +01005063 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 if (handle == NULL || patch == NULL) {
5065 return BAD_VALUE;
5066 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005068 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005069 return BAD_VALUE;
5070 }
5071 // only one source per audio patch supported for now
5072 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 return INVALID_OPERATION;
5074 }
Eric Laurent874c42872014-08-08 15:13:39 -07005075 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005076 return INVALID_OPERATION;
5077 }
Eric Laurent874c42872014-08-08 15:13:39 -07005078 for (size_t i = 0; i < patch->num_sinks; i++) {
5079 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5080 return INVALID_OPERATION;
5081 }
5082 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005083
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005084 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5085 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5086 if (srcDevice == nullptr || sinkDevice == nullptr) {
5087 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5088 return BAD_VALUE;
5089 }
5090 ALOGV("%s between source %s and sink %s", __func__,
5091 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5092 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5093 // Default attributes, default volume priority, not to infer with non raw audio patches.
5094 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5095 const struct audio_port_config *source = &patch->sources[0];
5096 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005097 new SourceClientDescriptor(
5098 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5099 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005100 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005101 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005102
5103 status_t status =
5104 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5105
5106 if (status != NO_ERROR) {
5107 return INVALID_OPERATION;
5108 }
5109 mAudioSources.add(portId, sourceDesc);
5110 return NO_ERROR;
5111}
5112
5113status_t AudioPolicyManager::connectAudioSourceToSink(
5114 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5115 const struct audio_patch *patch,
5116 audio_patch_handle_t &handle,
5117 uid_t uid, uint32_t delayMs)
5118{
5119 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5120 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5121 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5122 return INVALID_OPERATION;
5123 }
5124 sourceDesc->connect(handle, sinkDevice);
5125 if (isMsdPatch(handle)) {
5126 return NO_ERROR;
5127 }
5128 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5129 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5130 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5131 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5132 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5133 goto FailurePatchAdded;
5134 }
5135 status = swOutput->start();
5136 if (status != NO_ERROR) {
5137 goto FailureSourceAdded;
5138 }
5139 swOutput->addClient(sourceDesc);
5140 status = startSource(swOutput, sourceDesc, &delayMs);
5141 if (status != NO_ERROR) {
5142 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5143 goto FailureSourceActive;
5144 }
5145 if (delayMs != 0) {
5146 usleep(delayMs * 1000);
5147 }
5148 return NO_ERROR;
5149
5150FailureSourceActive:
5151 swOutput->stop();
5152 releaseOutput(sourceDesc->portId());
5153FailureSourceAdded:
5154 sourceDesc->setSwOutput(nullptr);
5155FailurePatchAdded:
5156 releaseAudioPatchInternal(handle);
5157 return INVALID_OPERATION;
5158}
5159
5160status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5161 audio_patch_handle_t *handle,
5162 uid_t uid, uint32_t delayMs,
5163 const sp<SourceClientDescriptor>& sourceDesc)
5164{
5165 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005166 sp<AudioPatch> patchDesc;
5167 ssize_t index = mAudioPatches.indexOfKey(*handle);
5168
François Gaffieafd4cea2019-11-18 15:50:22 +01005169 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5170 patch->sources[0].role,
5171 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005172#if LOG_NDEBUG == 0
5173 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005174 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5175 patch->sinks[i].role,
5176 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005177 }
5178#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005179
5180 if (index >= 0) {
5181 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005182 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5183 __func__, mUidCached, patchDesc->getUid(), uid);
5184 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 return INVALID_OPERATION;
5186 }
5187 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005188 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 }
5190
5191 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005192 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005194 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005195 return BAD_VALUE;
5196 }
Eric Laurent84c70242014-06-23 08:46:27 -07005197 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5198 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 if (patchDesc != 0) {
5200 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005201 ALOGV("%s source id differs for patch current id %d new id %d",
5202 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 return BAD_VALUE;
5204 }
5205 }
Eric Laurent874c42872014-08-08 15:13:39 -07005206 DeviceVector devices;
5207 for (size_t i = 0; i < patch->num_sinks; i++) {
5208 // Only support mix to devices connection
5209 // TODO add support for mix to mix connection
5210 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005211 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005212 return INVALID_OPERATION;
5213 }
5214 sp<DeviceDescriptor> devDesc =
5215 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5216 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005218 return BAD_VALUE;
5219 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005220
jiabin66acc432024-02-06 00:57:36 +00005221 if (outputDesc->mProfile->getCompatibilityScore(
5222 DeviceVector(devDesc),
5223 patch->sources[0].sample_rate,
5224 nullptr, // updatedSamplingRate
5225 patch->sources[0].format,
5226 nullptr, // updatedFormat
5227 patch->sources[0].channel_mask,
5228 nullptr, // updatedChannelMask
5229 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005230 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005231 return INVALID_OPERATION;
5232 }
5233 devices.add(devDesc);
5234 }
5235 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 return INVALID_OPERATION;
5237 }
Eric Laurent874c42872014-08-08 15:13:39 -07005238
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005240 ALOGV("%s setting device %s on output %d",
5241 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305242 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 index = mAudioPatches.indexOfKey(*handle);
5244 if (index >= 0) {
5245 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005246 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 }
5248 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005249 patchDesc->setUid(uid);
5250 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005252 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 return INVALID_OPERATION;
5254 }
5255 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5256 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5257 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005258 // only one sink supported when connecting an input device to a mix
5259 if (patch->num_sinks > 1) {
5260 return INVALID_OPERATION;
5261 }
François Gaffie53615e22015-03-19 09:24:12 +01005262 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 if (inputDesc == NULL) {
5264 return BAD_VALUE;
5265 }
5266 if (patchDesc != 0) {
5267 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5268 return BAD_VALUE;
5269 }
5270 }
François Gaffie11d30102018-11-02 16:09:09 +01005271 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005273 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 return BAD_VALUE;
5275 }
5276
jiabin66acc432024-02-06 00:57:36 +00005277 if (inputDesc->mProfile->getCompatibilityScore(
5278 DeviceVector(device),
5279 patch->sinks[0].sample_rate,
5280 nullptr, /*updatedSampleRate*/
5281 patch->sinks[0].format,
5282 nullptr, /*updatedFormat*/
5283 patch->sinks[0].channel_mask,
5284 nullptr, /*updatedChannelMask*/
5285 // FIXME for the parameter type,
5286 // and the NONE
5287 (audio_output_flags_t)
5288 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 return INVALID_OPERATION;
5290 }
5291 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005293 device->toString().c_str(), inputDesc->mIoHandle);
5294 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005295 index = mAudioPatches.indexOfKey(*handle);
5296 if (index >= 0) {
5297 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005298 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 }
5300 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 patchDesc->setUid(uid);
5302 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 return INVALID_OPERATION;
5306 }
5307 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5308 // device to device connection
5309 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005310 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 return BAD_VALUE;
5312 }
5313 }
François Gaffie11d30102018-11-02 16:09:09 +01005314 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005316 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005317 return BAD_VALUE;
5318 }
Eric Laurent874c42872014-08-08 15:13:39 -07005319
Eric Laurent6a94d692014-05-20 11:18:06 -07005320 //update source and sink with our own data as the data passed in the patch may
5321 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005322 PatchBuilder patchBuilder;
5323 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005324
5325 // if first sink is to MSD, establish single MSD patch
5326 if (getMsdAudioOutDevices().contains(
5327 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5328 ALOGV("%s patching to MSD", __FUNCTION__);
5329 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5330 goto installPatch;
5331 }
5332
François Gaffieafd4cea2019-11-18 15:50:22 +01005333 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5334 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005335
Eric Laurent874c42872014-08-08 15:13:39 -07005336 for (size_t i = 0; i < patch->num_sinks; i++) {
5337 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005339 return INVALID_OPERATION;
5340 }
François Gaffie11d30102018-11-02 16:09:09 +01005341 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005342 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005343 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005344 return BAD_VALUE;
5345 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005346 audio_port_config sinkPortConfig = {};
5347 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5348 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005349
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005350 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5351 // volume management purpose (tracking activity)
5352 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5353 // in config XML to reach the sink so that is can be declared as available.
5354 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005355 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005356 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005357 // take care of dynamic routing for SwOutput selection,
5358 audio_attributes_t attributes = sourceDesc->attributes();
5359 audio_stream_type_t stream = sourceDesc->stream();
5360 audio_attributes_t resultAttr;
5361 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5362 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005363 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5364 config.channel_mask =
5365 (audio_channel_mask_get_representation(sourceMask)
5366 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5367 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005368 config.format = sourceDesc->config().format;
5369 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5370 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5371 bool isRequestedDeviceForExclusiveUse = false;
5372 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005373 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005374 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005375 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5376 &stream, sourceDesc->uid(), &config, &flags,
5377 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005378 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005379 if (output == AUDIO_IO_HANDLE_NONE) {
5380 ALOGV("%s no output for device %s",
5381 __FUNCTION__, sinkDevice->toString().c_str());
5382 return INVALID_OPERATION;
5383 }
5384 outputDesc = mOutputs.valueFor(output);
5385 if (outputDesc->isDuplicated()) {
5386 ALOGE("%s output is duplicated", __func__);
5387 return INVALID_OPERATION;
5388 }
François Gaffie7e39df22022-04-26 12:48:49 +02005389 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5390 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005391 } else {
5392 // Same for "raw patches" aka created from createAudioPatch API
5393 SortedVector<audio_io_handle_t> outputs =
5394 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5395 // if the sink device is reachable via an opened output stream, request to
5396 // go via this output stream by adding a second source to the patch
5397 // description
5398 output = selectOutput(outputs);
5399 if (output == AUDIO_IO_HANDLE_NONE) {
5400 ALOGE("%s no output available for internal patch sink", __func__);
5401 return INVALID_OPERATION;
5402 }
5403 outputDesc = mOutputs.valueFor(output);
5404 if (outputDesc->isDuplicated()) {
5405 ALOGV("%s output for device %s is duplicated",
5406 __func__, sinkDevice->toString().c_str());
5407 return INVALID_OPERATION;
5408 }
François Gaffie7e39df22022-04-26 12:48:49 +02005409 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005410 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005411 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005412 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005413 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005414 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005415 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5416 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005417 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5418 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005419 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005420 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005421 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005422 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005423 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005424 return INVALID_OPERATION;
5425 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005426 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005427 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005428 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005429 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005430 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005431 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005432 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005433 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5434 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005435 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005436 }
Eric Laurent83b88082014-06-20 18:31:16 -07005437 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005438 }
5439 // TODO: check from routing capabilities in config file and other conflicting patches
5440
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005441installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005442 status_t status = installPatch(
5443 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005444 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005445 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005446 return INVALID_OPERATION;
5447 }
5448 } else {
5449 return BAD_VALUE;
5450 }
5451 } else {
5452 return BAD_VALUE;
5453 }
5454 return NO_ERROR;
5455}
5456
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005457status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005458{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005459 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005460 ssize_t index = mAudioPatches.indexOfKey(handle);
5461
5462 if (index < 0) {
5463 return BAD_VALUE;
5464 }
5465 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005466 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5467 __func__, mUidCached, patchDesc->getUid(), uid);
5468 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005469 return INVALID_OPERATION;
5470 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005471 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5472 for (size_t i = 0; i < mAudioSources.size(); i++) {
5473 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5474 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5475 portId = sourceDesc->portId();
5476 break;
5477 }
5478 }
5479 return portId != AUDIO_PORT_HANDLE_NONE ?
5480 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005481}
Eric Laurent6a94d692014-05-20 11:18:06 -07005482
François Gaffieafd4cea2019-11-18 15:50:22 +01005483status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005484 uint32_t delayMs,
5485 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005486{
5487 ALOGV("%s patch %d", __func__, handle);
5488 if (mAudioPatches.indexOfKey(handle) < 0) {
5489 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5490 return BAD_VALUE;
5491 }
5492 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005493 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005494 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005495 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005496 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005497 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005498 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005499 return BAD_VALUE;
5500 }
5501
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305502 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005503 getNewOutputDevices(outputDesc, true /*fromCache*/),
5504 true,
5505 0,
5506 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005507 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5508 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005509 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005511 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005512 return BAD_VALUE;
5513 }
5514 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005515 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005516 true,
5517 NULL);
5518 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005519 status_t status =
5520 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5521 ALOGV("%s patch panel returned %d patchHandle %d",
5522 __func__, status, patchDesc->getAfHandle());
5523 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005524 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005525 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005526 // SW or HW Bridge
5527 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5528 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005529 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005530 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5531 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5532 outputDesc = sourceDesc->swOutput().promote();
5533 }
5534 if (outputDesc == nullptr) {
5535 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5536 // releaseOutput has already called closeOutput in case of direct output
5537 return NO_ERROR;
5538 }
François Gaffie7e39df22022-04-26 12:48:49 +02005539 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005540 // While using a HwBridge, force reconsidering device only if not reusing an existing
5541 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005542 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005543 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5544 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5545 // Reconsider device only for cases:
5546 // 1 / Active Output
5547 // 2 / Inactive Output previously hosting HwBridge
5548 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5549 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5550 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305551 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005552 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5553 outputDesc->devices(),
5554 force,
5555 0,
5556 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 } else {
5558 return BAD_VALUE;
5559 }
5560 } else {
5561 return BAD_VALUE;
5562 }
5563 return NO_ERROR;
5564}
5565
5566status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5567 struct audio_patch *patches,
5568 unsigned int *generation)
5569{
François Gaffie53615e22015-03-19 09:24:12 +01005570 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005571 return BAD_VALUE;
5572 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005573 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005574 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005575}
5576
Eric Laurente1715a42014-05-20 11:30:42 -07005577status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005578{
Eric Laurente1715a42014-05-20 11:30:42 -07005579 ALOGV("setAudioPortConfig()");
5580
5581 if (config == NULL) {
5582 return BAD_VALUE;
5583 }
5584 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5585 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005586 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5587 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005588 }
5589
Eric Laurenta121f902014-06-03 13:32:54 -07005590 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005591 if (config->type == AUDIO_PORT_TYPE_MIX) {
5592 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005593 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005594 if (outputDesc == NULL) {
5595 return BAD_VALUE;
5596 }
Eric Laurent84c70242014-06-23 08:46:27 -07005597 ALOG_ASSERT(!outputDesc->isDuplicated(),
5598 "setAudioPortConfig() called on duplicated output %d",
5599 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005600 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005601 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005602 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005603 if (inputDesc == NULL) {
5604 return BAD_VALUE;
5605 }
Eric Laurenta121f902014-06-03 13:32:54 -07005606 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005607 } else {
5608 return BAD_VALUE;
5609 }
5610 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5611 sp<DeviceDescriptor> deviceDesc;
5612 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5613 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5614 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5615 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5616 } else {
5617 return BAD_VALUE;
5618 }
5619 if (deviceDesc == NULL) {
5620 return BAD_VALUE;
5621 }
Eric Laurenta121f902014-06-03 13:32:54 -07005622 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005623 } else {
5624 return BAD_VALUE;
5625 }
5626
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005627 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005628 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5629 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005630 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005631 audioPortConfig->toAudioPortConfig(&newConfig, config);
5632 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005633 }
Eric Laurenta121f902014-06-03 13:32:54 -07005634 if (status != NO_ERROR) {
5635 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005636 }
Eric Laurente1715a42014-05-20 11:30:42 -07005637
5638 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005639}
5640
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005641void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5642{
Eric Laurentd60560a2015-04-10 11:31:20 -07005643 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005644 clearAudioPatches(uid);
5645 clearSessionRoutes(uid);
5646}
5647
Eric Laurent6a94d692014-05-20 11:18:06 -07005648void AudioPolicyManager::clearAudioPatches(uid_t uid)
5649{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005650 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005651 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005652 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005653 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005654 }
5655 }
5656}
5657
François Gaffiec005e562018-11-06 15:04:49 +01005658void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005659{
François Gaffiec005e562018-11-06 15:04:49 +01005660 // Take the first attributes following the product strategy as it is used to retrieve the routed
5661 // device. All attributes wihin a strategy follows the same "routing strategy"
5662 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5663 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005664 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005665 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005666 for (size_t j = 0; j < mOutputs.size(); j++) {
5667 if (mOutputs.keyAt(j) == ouptutToSkip) {
5668 continue;
5669 }
5670 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005671 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005672 continue;
5673 }
5674 // If the default device for this strategy is on another output mix,
5675 // invalidate all tracks in this strategy to force re connection.
5676 // Otherwise select new device on the output mix.
5677 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005678 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005679 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005680 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005681 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005682 // If the device is using preferred mixer attributes, the output need to reopen
5683 // with default configuration when the new selected devices are different from
5684 // current routing devices.
5685 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5686 continue;
5687 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305688 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005689 }
5690 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005691 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005692}
5693
5694void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5695{
5696 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005697 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005698 for (size_t i = 0; i < mOutputs.size(); i++) {
5699 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005700 for (const auto& client : outputDesc->getClientIterable()) {
5701 if (client->hasPreferredDevice() && client->uid() == uid) {
5702 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005703 auto clientStrategy = client->strategy();
5704 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5705 end(affectedStrategies)) {
5706 continue;
5707 }
5708 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005709 }
5710 }
5711 }
5712 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005713 for (const auto& strategy : affectedStrategies) {
5714 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005715 }
5716
5717 // remove input routes associated with this uid
5718 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005719 for (size_t i = 0; i < mInputs.size(); i++) {
5720 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005721 for (const auto& client : inputDesc->getClientIterable()) {
5722 if (client->hasPreferredDevice() && client->uid() == uid) {
5723 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5724 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005725 }
5726 }
5727 }
5728 // reroute inputs if necessary
5729 SortedVector<audio_io_handle_t> inputsToClose;
5730 for (size_t i = 0; i < mInputs.size(); i++) {
5731 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005732 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005733 inputsToClose.add(inputDesc->mIoHandle);
5734 }
5735 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005736 for (const auto& input : inputsToClose) {
5737 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005738 }
5739}
5740
Eric Laurentd60560a2015-04-10 11:31:20 -07005741void AudioPolicyManager::clearAudioSources(uid_t uid)
5742{
5743 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005744 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5745 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005746 stopAudioSource(mAudioSources.keyAt(i));
5747 }
5748 }
5749}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005750
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005751status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5752 audio_io_handle_t *ioHandle,
5753 audio_devices_t *device)
5754{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005755 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5756 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005757 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005758 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5759 if (deviceDesc == nullptr) {
5760 return INVALID_OPERATION;
5761 }
5762 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005763
François Gaffiedf372692015-03-19 10:43:27 +01005764 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005765}
5766
Eric Laurentd60560a2015-04-10 11:31:20 -07005767status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005768 const audio_attributes_t *attributes,
5769 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005770 uid_t uid) {
5771 return startAudioSourceInternal(source, attributes, portId, uid,
5772 false /*internal*/, false /*isCallRx*/);
5773}
5774
5775status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5776 const audio_attributes_t *attributes,
5777 audio_port_handle_t *portId,
5778 uid_t uid, bool internal, bool isCallRx)
Eric Laurent554a2772015-04-10 11:29:24 -07005779{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005780 ALOGV("%s", __FUNCTION__);
5781 *portId = AUDIO_PORT_HANDLE_NONE;
5782
5783 if (source == NULL || attributes == NULL || portId == NULL) {
5784 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5785 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005786 return BAD_VALUE;
5787 }
5788
Eric Laurentd60560a2015-04-10 11:31:20 -07005789 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5790 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005791 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5792 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005793 return INVALID_OPERATION;
5794 }
5795
François Gaffie11d30102018-11-02 16:09:09 +01005796 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005797 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005798 String8(source->ext.device.address),
5799 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005800 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005801 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005802 return BAD_VALUE;
5803 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005804
jiabin4ef93452019-09-10 14:29:54 -07005805 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005806
François Gaffieaaac0fd2018-11-22 17:56:39 +01005807 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005808 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005809 mEngine->getStreamTypeForAttributes(*attributes),
5810 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005811 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005812
5813 status_t status = connectAudioSource(sourceDesc);
5814 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005815 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005816 }
5817 return status;
5818}
5819
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005820status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005821{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005822 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005823
5824 // make sure we only have one patch per source.
5825 disconnectAudioSource(sourceDesc);
5826
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005827 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005828 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5829 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5830 sourceDesc->srcDevice()->type(),
5831 String8(sourceDesc->srcDevice()->address().c_str()),
5832 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005833 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005834 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005835 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005836 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005837 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5838 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5839 return INVALID_OPERATION;
5840 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005841 PatchBuilder patchBuilder;
5842 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5843 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005844
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005845 return connectAudioSourceToSink(
5846 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005847}
5848
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005849status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005850{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005851 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5852 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005853 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005854 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005855 return BAD_VALUE;
5856 }
5857 status_t status = disconnectAudioSource(sourceDesc);
5858
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005859 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005860 return status;
5861}
5862
Andy Hung2ddee192015-12-18 17:34:44 -08005863status_t AudioPolicyManager::setMasterMono(bool mono)
5864{
5865 if (mMasterMono == mono) {
5866 return NO_ERROR;
5867 }
5868 mMasterMono = mono;
5869 // if enabling mono we close all offloaded devices, which will invalidate the
5870 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5871 // for recreating the new AudioTrack as non-offloaded PCM.
5872 //
5873 // If disabling mono, we leave all tracks as is: we don't know which clients
5874 // and tracks are able to be recreated as offloaded. The next "song" should
5875 // play back offloaded.
5876 if (mMasterMono) {
5877 Vector<audio_io_handle_t> offloaded;
5878 for (size_t i = 0; i < mOutputs.size(); ++i) {
5879 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5880 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5881 offloaded.push(desc->mIoHandle);
5882 }
5883 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005884 for (const auto& handle : offloaded) {
5885 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005886 }
5887 }
5888 // update master mono for all remaining outputs
5889 for (size_t i = 0; i < mOutputs.size(); ++i) {
5890 updateMono(mOutputs.keyAt(i));
5891 }
5892 return NO_ERROR;
5893}
5894
5895status_t AudioPolicyManager::getMasterMono(bool *mono)
5896{
5897 *mono = mMasterMono;
5898 return NO_ERROR;
5899}
5900
Eric Laurentac9cef52017-06-09 15:46:26 -07005901float AudioPolicyManager::getStreamVolumeDB(
5902 audio_stream_type_t stream, int index, audio_devices_t device)
5903{
jiabin9a3361e2019-10-01 09:38:30 -07005904 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005905}
5906
jiabin81772902018-04-02 17:52:27 -07005907status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5908 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005909 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005910{
Kriti Dang6537def2021-03-02 13:46:59 +01005911 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5912 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005913 return BAD_VALUE;
5914 }
Kriti Dang6537def2021-03-02 13:46:59 +01005915 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5916 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005917
5918 size_t formatsWritten = 0;
5919 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005920
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005921 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005922 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5923 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005924 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005925 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005926 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005927 bool formatEnabled = true;
5928 switch (forceUse) {
5929 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005930 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005931 break;
5932 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5933 formatEnabled = false;
5934 break;
5935 default: // AUTO or ALWAYS => true
5936 break;
jiabin81772902018-04-02 17:52:27 -07005937 }
5938 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5939 }
jiabin81772902018-04-02 17:52:27 -07005940 }
5941 return NO_ERROR;
5942}
5943
Kriti Dang6537def2021-03-02 13:46:59 +01005944status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5945 audio_format_t *surroundFormats) {
5946 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5947 return BAD_VALUE;
5948 }
5949 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5950 __func__, *numSurroundFormats, surroundFormats);
5951
5952 size_t formatsWritten = 0;
5953 size_t formatsMax = *numSurroundFormats;
5954 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5955
5956 // Return formats from all device profiles that have already been resolved by
5957 // checkOutputsForDevice().
5958 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5959 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5960 audio_devices_t deviceType = device->type();
5961 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5962 // returns formats reported by HDMI devices.
5963 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5964 continue;
5965 }
5966 // Formats reported by sink devices
5967 std::unordered_set<audio_format_t> formatset;
5968 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5969 formatset.insert(it->second.begin(), it->second.end());
5970 }
5971
5972 // Formats hard-coded in the in policy configuration file (if any).
5973 FormatVector encodedFormats = device->encodedFormats();
5974 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5975 // Filter the formats which are supported by the vendor hardware.
5976 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005977 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005978 formats.insert(*it);
5979 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005980 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005981 if (pair.second.count(*it) != 0) {
5982 formats.insert(pair.first);
5983 break;
5984 }
5985 }
5986 }
5987 }
5988 }
5989 *numSurroundFormats = formats.size();
5990 for (const auto& format: formats) {
5991 if (formatsWritten < formatsMax) {
5992 surroundFormats[formatsWritten++] = format;
5993 }
5994 }
5995 return NO_ERROR;
5996}
5997
jiabin81772902018-04-02 17:52:27 -07005998status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5999{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006000 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006001 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6002 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006003 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006004 return BAD_VALUE;
6005 }
6006
Mikhail Naganov100f0122018-11-29 11:22:16 -08006007 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6008 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006009 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006010 return INVALID_OPERATION;
6011 }
6012
Mikhail Naganov100f0122018-11-29 11:22:16 -08006013 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006014 return NO_ERROR;
6015 }
6016
Mikhail Naganov100f0122018-11-29 11:22:16 -08006017 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006018 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006019 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006020 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006021 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006022 }
6023 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006024 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006025 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006026 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006027 }
6028 }
6029
6030 sp<SwAudioOutputDescriptor> outputDesc;
6031 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006032 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6033 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006034 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6035 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006036 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006037 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006038 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6039 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6040 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006041 name.c_str(),
6042 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006043 if (status != NO_ERROR) {
6044 continue;
6045 }
6046 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6047 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6048 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006049 name.c_str(),
6050 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006051 profileUpdated |= (status == NO_ERROR);
6052 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006053 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006054 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006055 AUDIO_DEVICE_IN_HDMI);
6056 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6057 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006058 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006059 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006060 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6061 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6062 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006063 name.c_str(),
6064 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006065 if (status != NO_ERROR) {
6066 continue;
6067 }
6068 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6069 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6070 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006071 name.c_str(),
6072 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006073 profileUpdated |= (status == NO_ERROR);
6074 }
6075
jiabin81772902018-04-02 17:52:27 -07006076 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006077 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006078 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006079 }
6080
6081 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6082}
6083
Eric Laurent5ada82e2019-08-29 17:53:54 -07006084void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006085{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006086 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006087 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006088 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006089 }
6090}
6091
jiabin6012f912018-11-02 17:06:30 -07006092bool AudioPolicyManager::isHapticPlaybackSupported()
6093{
6094 for (const auto& hwModule : mHwModules) {
6095 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6096 for (const auto &outProfile : outputProfiles) {
6097 struct audio_port audioPort;
6098 outProfile->toAudioPort(&audioPort);
6099 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6100 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6101 return true;
6102 }
6103 }
6104 }
6105 }
6106 return false;
6107}
6108
Carter Hsu325a8eb2022-01-19 19:56:51 +08006109bool AudioPolicyManager::isUltrasoundSupported()
6110{
6111 bool hasUltrasoundOutput = false;
6112 bool hasUltrasoundInput = false;
6113 for (const auto& hwModule : mHwModules) {
6114 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6115 if (!hasUltrasoundOutput) {
6116 for (const auto &outProfile : outputProfiles) {
6117 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6118 hasUltrasoundOutput = true;
6119 break;
6120 }
6121 }
6122 }
6123
6124 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6125 if (!hasUltrasoundInput) {
6126 for (const auto &inputProfile : inputProfiles) {
6127 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6128 hasUltrasoundInput = true;
6129 break;
6130 }
6131 }
6132 }
6133
6134 if (hasUltrasoundOutput && hasUltrasoundInput)
6135 return true;
6136 }
6137 return false;
6138}
6139
Atneya Nair698f5ef2022-12-15 16:15:09 -08006140bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6141{
6142 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6143 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6144 for (const auto& hwModule : mHwModules) {
6145 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6146 for (const auto &inputProfile : inputProfiles) {
6147 if ((inputProfile->getFlags() & mask) == mask) {
6148 return true;
6149 }
6150 }
6151 }
6152 return false;
6153}
6154
Eric Laurent8340e672019-11-06 11:01:08 -08006155bool AudioPolicyManager::isCallScreenModeSupported()
6156{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006157 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006158}
6159
6160
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006161status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006162{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006163 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006164 if (!sourceDesc->isConnected()) {
6165 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6166 return NO_ERROR;
6167 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006168 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6169 if (swOutput != 0) {
6170 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006171 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006172 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006173 }
jiabinbce0c1d2020-10-05 11:20:18 -07006174 if (releaseOutput(sourceDesc->portId())) {
6175 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6176 // no need to release audio patch here but just return NO_ERROR.
6177 return NO_ERROR;
6178 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006179 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006180 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006181 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006182 // close Hwoutput and remove from mHwOutputs
6183 } else {
6184 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6185 }
6186 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006187 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006188 sourceDesc->disconnect();
6189 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006190}
6191
François Gaffiec005e562018-11-06 15:04:49 +01006192sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6193 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006194{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006195 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006196 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006197 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006198 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006199 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6200 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006201 source = sourceDesc;
6202 break;
6203 }
6204 }
6205 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006206}
6207
Eric Laurentb4f42a92022-01-17 17:37:31 +01006208bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006209 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006210 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006211{
6212 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6213 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006214 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006215 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006216 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6217 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6218 return false;
6219 }
6220 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6221 return false;
6222 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006223 }
6224
Eric Laurentd332bc82023-08-04 11:45:23 +02006225 // The caller can have the audio config criteria ignored by either passing a null ptr or
6226 // the AUDIO_CONFIG_INITIALIZER value.
6227 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006228 // some positional channel masks and PCM format and for stereo if low latency performance
6229 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006230
6231 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006232 static const bool stereo_spatialization_enabled =
6233 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006234 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006235 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006236 ? audio_channel_mask_contains_stereo(config->channel_mask)
6237 : audio_is_channel_mask_spatialized(config->channel_mask);
6238 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006239 return false;
6240 }
6241 if (!audio_is_linear_pcm(config->format)) {
6242 return false;
6243 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006244 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6245 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6246 return false;
6247 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006248 }
6249
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006250 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006251 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006252 if (profile == nullptr) {
6253 return false;
6254 }
6255
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006256 return true;
6257}
6258
Shunkai Yao4c3af932024-04-26 04:12:21 +00006259// The Spatializer output is compatible with Haptic use cases if:
6260// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6261// with client if client haptic channel bits were set, or
6262// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6263// including the haptic bits or creating the HapticGenerator effect for same session.
6264bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6265 const audio_config_t* config, audio_session_t sessionId) const {
6266 const auto clientHapticChannel =
6267 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6268 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6269 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6270
6271 if (threadOutputHapticChannel) {
6272 // check format and sampleRate match if client haptic channel mask exist
6273 if (clientHapticChannel) {
6274 return mSpatializerOutput->getFormat() == config->format &&
6275 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6276 }
6277 return true;
6278 } else {
6279 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6280 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6281 // HapticGenerator effect for this session) are not supported.
6282 return clientHapticChannel == 0 &&
6283 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6284 }
6285}
6286
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006287void AudioPolicyManager::checkVirtualizerClientRoutes() {
6288 std::set<audio_stream_type_t> streamsToInvalidate;
6289 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006290 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6291 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006292 audio_attributes_t attr = client->attributes();
6293 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6294 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6295 audio_config_base_t clientConfig = client->config();
6296 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006297 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006298 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006299 streamsToInvalidate.insert(client->stream());
6300 }
6301 }
6302 }
6303
jiabinc44b3462022-12-08 12:52:31 -08006304 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006305}
6306
Eric Laurente191d1b2022-04-15 11:59:25 +02006307
6308bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6309 const sp<SwAudioOutputDescriptor>& outputDesc) {
6310 if (outputDesc->isDuplicated()) {
6311 return false;
6312 }
6313 DeviceVector devices = outputDesc->supportedDevices();
6314 for (size_t i = 0; i < mOutputs.size(); i++) {
6315 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6316 if (desc == outputDesc || desc->isDuplicated()) {
6317 continue;
6318 }
6319 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6320 if (!sharedDevices.isEmpty()
6321 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6322 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6323 return false;
6324 }
6325 }
6326 return true;
6327}
6328
6329
Eric Laurentfa0f6742021-08-17 18:39:44 +02006330status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006331 const audio_attributes_t *attr,
6332 audio_io_handle_t *output) {
6333 *output = AUDIO_IO_HANDLE_NONE;
6334
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006335 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6336 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6337 audio_config_t *configPtr = nullptr;
6338 audio_config_t config;
6339 if (mixerConfig != nullptr) {
6340 config = audio_config_initializer(mixerConfig);
6341 configPtr = &config;
6342 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006343 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006344 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006345 return BAD_VALUE;
6346 }
6347
6348 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006349 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006350 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006351 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006352 return BAD_VALUE;
6353 }
6354
Eric Laurente191d1b2022-04-15 11:59:25 +02006355 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006356 for (size_t i = 0; i < mOutputs.size(); i++) {
6357 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006358 if (!desc->isDuplicated()
6359 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6360 spatializerOutputs.push_back(desc);
6361 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006362 }
6363 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006364 mSpatializerOutput.clear();
6365 bool outputsChanged = false;
6366 for (const auto& desc : spatializerOutputs) {
6367 if (desc->mProfile == profile
6368 && (configPtr == nullptr
6369 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6370 mSpatializerOutput = desc;
6371 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6372 } else {
6373 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6374 " and devices %s", __func__, desc->mIoHandle,
6375 configPtr != nullptr ? configPtr->channel_mask : 0,
6376 devices.toString().c_str());
6377 closeOutput(desc->mIoHandle);
6378 outputsChanged = true;
6379 }
Eric Laurent39095982021-08-24 18:29:27 +02006380 }
6381
Eric Laurente191d1b2022-04-15 11:59:25 +02006382 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006383 sp<SwAudioOutputDescriptor> desc =
6384 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006385 if (desc != nullptr) {
6386 mSpatializerOutput = desc;
6387 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006388 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006389 }
6390
6391 checkVirtualizerClientRoutes();
6392
Eric Laurente191d1b2022-04-15 11:59:25 +02006393 if (outputsChanged) {
6394 mPreviousOutputs = mOutputs;
6395 mpClientInterface->onAudioPortListUpdate();
6396 }
6397
6398 if (mSpatializerOutput == nullptr) {
6399 ALOGV("%s could not open spatializer output with requested config", __func__);
6400 return BAD_VALUE;
6401 }
Eric Laurent39095982021-08-24 18:29:27 +02006402 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006403 ALOGV("%s returning new spatializer output %d", __func__, *output);
6404 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006405}
6406
Eric Laurentfa0f6742021-08-17 18:39:44 +02006407status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6408 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006409 return INVALID_OPERATION;
6410 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006411 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006412 return BAD_VALUE;
6413 }
Eric Laurent39095982021-08-24 18:29:27 +02006414
Eric Laurente191d1b2022-04-15 11:59:25 +02006415 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6416 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6417 closeOutput(mSpatializerOutput->mIoHandle);
6418 //from now on mSpatializerOutput is null
6419 checkVirtualizerClientRoutes();
6420 }
Eric Laurent39095982021-08-24 18:29:27 +02006421
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006422 return NO_ERROR;
6423}
6424
Eric Laurente552edb2014-03-10 17:42:56 -07006425// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006426// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006427// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006428uint32_t AudioPolicyManager::nextAudioPortGeneration()
6429{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006430 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006431}
6432
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006433AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006434 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006435 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006436 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006437 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006438 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006439 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006440 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006441 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006442 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006443 mAudioPortGeneration(1),
6444 mBeaconMuteRefCount(0),
6445 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006446 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006447 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006448 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006449 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006450{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006451}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006452
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006453status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006454 if (mEngine == nullptr) {
6455 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006456 }
6457 mEngine->setObserver(this);
6458 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006459 if (status != NO_ERROR) {
6460 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6461 return status;
6462 }
François Gaffie2110e042015-03-24 08:41:51 +01006463
jiabin29230182023-04-04 21:02:36 +00006464 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6465 // at the end of this function.
6466 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006467 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6468 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6469
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006470 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006471 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006472 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006473
Eric Laurent3a4311c2014-03-17 12:00:47 -07006474 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006475 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6476 defaultOutputDevice == nullptr ||
6477 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6478 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6479 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006480 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006481 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006482 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006483
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006484 // Silence ALOGV statements
6485 property_set("log.tag." LOG_TAG, "D");
6486
Eric Laurente552edb2014-03-10 17:42:56 -07006487 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006488 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006489}
6490
Eric Laurente0720872014-03-11 09:30:41 -07006491AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006492{
Eric Laurente552edb2014-03-10 17:42:56 -07006493 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006494 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006495 }
6496 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006497 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006498 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006499 mAvailableOutputDevices.clear();
6500 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006501 mOutputs.clear();
6502 mInputs.clear();
6503 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006504 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006505 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006506}
6507
Eric Laurente0720872014-03-11 09:30:41 -07006508status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006509{
Eric Laurent87ffa392015-05-22 10:32:38 -07006510 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006511}
6512
Eric Laurente552edb2014-03-10 17:42:56 -07006513// ---
6514
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006515void AudioPolicyManager::onNewAudioModulesAvailable()
6516{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006517 DeviceVector newDevices;
6518 onNewAudioModulesAvailableInt(&newDevices);
6519 if (!newDevices.empty()) {
6520 nextAudioPortGeneration();
6521 mpClientInterface->onAudioPortListUpdate();
6522 }
6523}
6524
6525void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6526{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006527 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006528 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6529 continue;
6530 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006531 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006532 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6533 handle != AUDIO_MODULE_HANDLE_NONE) {
6534 hwModule->setHandle(handle);
6535 } else {
6536 ALOGW("could not load HW module %s", hwModule->getName());
6537 continue;
6538 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006539 }
6540 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006541 // open all output streams needed to access attached devices.
6542 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006543 // This also validates mAvailableOutputDevices list
6544 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6545 if (!outProfile->canOpenNewIo()) {
6546 ALOGE("Invalid Output profile max open count %u for profile %s",
6547 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6548 continue;
6549 }
6550 if (!outProfile->hasSupportedDevices()) {
6551 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6552 continue;
6553 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006554 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6555 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006556 mTtsOutputAvailable = true;
6557 }
6558
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006559 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006560 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006561 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006562 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6563 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006564 } else {
6565 // choose first device present in profile's SupportedDevices also part of
6566 // mAvailableOutputDevices.
6567 if (availProfileDevices.isEmpty()) {
6568 continue;
6569 }
6570 supportedDevice = availProfileDevices.itemAt(0);
6571 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006572 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006573 continue;
6574 }
6575 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6576 mpClientInterface);
6577 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006578 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6579 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006580 AUDIO_STREAM_DEFAULT,
6581 AUDIO_OUTPUT_FLAG_NONE, &output);
6582 if (status != NO_ERROR) {
6583 ALOGW("Cannot open output stream for devices %s on hw module %s",
6584 supportedDevice->toString().c_str(), hwModule->getName());
6585 continue;
6586 }
6587 for (const auto &device : availProfileDevices) {
6588 // give a valid ID to an attached device once confirmed it is reachable
6589 if (!device->isAttached()) {
6590 device->attach(hwModule);
6591 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006592 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006593 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006594 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6595 }
6596 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006597 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006598 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6599 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006600 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006601 }
Eric Laurent39095982021-08-24 18:29:27 +02006602 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006603 outputDesc->close();
6604 } else {
6605 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306606 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006607 DeviceVector(supportedDevice),
6608 true,
6609 0,
6610 NULL);
6611 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006612 }
6613 // open input streams needed to access attached devices to validate
6614 // mAvailableInputDevices list
6615 for (const auto& inProfile : hwModule->getInputProfiles()) {
6616 if (!inProfile->canOpenNewIo()) {
6617 ALOGE("Invalid Input profile max open count %u for profile %s",
6618 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6619 continue;
6620 }
6621 if (!inProfile->hasSupportedDevices()) {
6622 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6623 continue;
6624 }
6625 // chose first device present in profile's SupportedDevices also part of
6626 // available input devices
6627 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006628 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006629 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006630 ALOGV("%s: Input device list is empty! for profile %s",
6631 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006632 continue;
6633 }
6634 sp<AudioInputDescriptor> inputDesc =
6635 new AudioInputDescriptor(inProfile, mpClientInterface);
6636
6637 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6638 status_t status = inputDesc->open(nullptr,
6639 availProfileDevices.itemAt(0),
6640 AUDIO_SOURCE_MIC,
6641 AUDIO_INPUT_FLAG_NONE,
6642 &input);
6643 if (status != NO_ERROR) {
6644 ALOGW("Cannot open input stream for device %s on hw module %s",
6645 availProfileDevices.toString().c_str(),
6646 hwModule->getName());
6647 continue;
6648 }
6649 for (const auto &device : availProfileDevices) {
6650 // give a valid ID to an attached device once confirmed it is reachable
6651 if (!device->isAttached()) {
6652 device->attach(hwModule);
6653 device->importAudioPortAndPickAudioProfile(inProfile, true);
6654 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006655 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006656 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6657 }
6658 }
6659 inputDesc->close();
6660 }
6661 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006662
6663 // Check if spatializer outputs can be closed until used.
6664 // mOutputs vector never contains duplicated outputs at this point.
6665 std::vector<audio_io_handle_t> outputsClosed;
6666 for (size_t i = 0; i < mOutputs.size(); i++) {
6667 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6668 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6669 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6670 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006671 nextAudioPortGeneration();
6672 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6673 if (index >= 0) {
6674 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6675 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6676 patchDesc->getAfHandle(), 0);
6677 mAudioPatches.removeItemsAt(index);
6678 mpClientInterface->onAudioPatchListUpdate();
6679 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006680 desc->close();
6681 }
6682 }
6683 for (auto output : outputsClosed) {
6684 removeOutput(output);
6685 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006686}
6687
Eric Laurent98e38192018-02-15 18:31:53 -08006688void AudioPolicyManager::addOutput(audio_io_handle_t output,
6689 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006690{
Eric Laurent1c333e22014-05-20 10:48:17 -07006691 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006692 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006693 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006694 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006695 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006696}
6697
François Gaffie53615e22015-03-19 09:24:12 +01006698void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6699{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006700 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6701 ALOGV("%s: removing primary output", __func__);
6702 mPrimaryOutput = nullptr;
6703 }
François Gaffie53615e22015-03-19 09:24:12 +01006704 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006705 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006706}
6707
Eric Laurent98e38192018-02-15 18:31:53 -08006708void AudioPolicyManager::addInput(audio_io_handle_t input,
6709 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006710{
Eric Laurent1c333e22014-05-20 10:48:17 -07006711 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006712 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006713}
Eric Laurente552edb2014-03-10 17:42:56 -07006714
François Gaffie11d30102018-11-02 16:09:09 +01006715status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006716 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006717 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006718{
François Gaffie11d30102018-11-02 16:09:09 +01006719 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006720 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006721 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006722
François Gaffie11d30102018-11-02 16:09:09 +01006723 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006724 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006725 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006726 }
Eric Laurente552edb2014-03-10 17:42:56 -07006727
Eric Laurent3b73df72014-03-11 09:06:29 -07006728 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006729 // first call getAudioPort to get the supported attributes from the HAL
6730 struct audio_port_v7 port = {};
6731 device->toAudioPort(&port);
6732 status_t status = mpClientInterface->getAudioPort(&port);
6733 if (status == NO_ERROR) {
6734 device->importAudioPort(port);
6735 }
6736
6737 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006738 for (size_t i = 0; i < mOutputs.size(); i++) {
6739 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006740 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006741 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006742 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6743 mOutputs.keyAt(i), device->toString().c_str());
6744 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006745 }
6746 }
6747 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006748 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006749 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006750 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6751 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006752 if (profile->supportsDevice(device)) {
6753 profiles.add(profile);
6754 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6755 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006756 }
6757 }
6758 }
6759
Eric Laurent7b279bb2015-12-14 10:18:23 -08006760 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006761
Eric Laurente552edb2014-03-10 17:42:56 -07006762 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006763 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006764 return BAD_VALUE;
6765 }
6766
6767 // open outputs for matching profiles if needed. Direct outputs are also opened to
6768 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6769 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006770 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006771
6772 // nothing to do if one output is already opened for this profile
6773 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006774 for (j = 0; j < outputs.size(); j++) {
6775 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006776 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006777 // matching profile: save the sample rates, format and channel masks supported
6778 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006779 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006780 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006781 }
Eric Laurente552edb2014-03-10 17:42:56 -07006782 break;
6783 }
6784 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006785 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006786 continue;
6787 }
6788
Eric Laurent3974e3b2017-12-07 17:58:43 -08006789 if (!profile->canOpenNewIo()) {
6790 ALOGW("Max Output number %u already opened for this profile %s",
6791 profile->maxOpenCount, profile->getTagName().c_str());
6792 continue;
6793 }
6794
Eric Laurent83efe1c2017-07-09 16:51:08 -07006795 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006796 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006797 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6798 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006799 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006800 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006801 profiles.removeAt(profile_index);
6802 profile_index--;
6803 } else {
6804 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006805 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006806 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006807 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6808 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006809 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006810 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006811
François Gaffie11d30102018-11-02 16:09:09 +01006812 if (device_distinguishes_on_address(deviceType)) {
6813 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6814 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306815 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6816 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006817 }
Eric Laurente552edb2014-03-10 17:42:56 -07006818 ALOGV("checkOutputsForDevice(): adding output %d", output);
6819 }
6820 }
6821
6822 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006823 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006824 return BAD_VALUE;
6825 }
Eric Laurentd4692962014-05-05 18:13:44 -07006826 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006827 // check if one opened output is not needed any more after disconnecting one device
6828 for (size_t i = 0; i < mOutputs.size(); i++) {
6829 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006830 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006831 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006832 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006833 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006834 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006835 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006836 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6837 mOutputs.keyAt(i));
6838 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006839 }
Eric Laurente552edb2014-03-10 17:42:56 -07006840 }
6841 }
Eric Laurentd4692962014-05-05 18:13:44 -07006842 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006843 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006844 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6845 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006846 if (!profile->supportsDevice(device)) {
6847 continue;
6848 }
6849 ALOGV("checkOutputsForDevice(): "
6850 "clearing direct output profile %zu on module %s",
6851 j, hwModule->getName());
6852 profile->clearAudioProfiles();
6853 if (!profile->hasDynamicAudioProfile()) {
6854 continue;
6855 }
6856 // When a device is disconnected, if there is an IOProfile that contains dynamic
6857 // profiles and supports the disconnected device, call getAudioPort to repopulate
6858 // the capabilities of the devices that is supported by the IOProfile.
6859 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6860 if (supportedDevice == device ||
6861 !mAvailableOutputDevices.contains(supportedDevice)) {
6862 continue;
6863 }
6864 struct audio_port_v7 port;
6865 supportedDevice->toAudioPort(&port);
6866 status_t status = mpClientInterface->getAudioPort(&port);
6867 if (status == NO_ERROR) {
6868 supportedDevice->importAudioPort(port);
6869 }
Eric Laurente552edb2014-03-10 17:42:56 -07006870 }
6871 }
6872 }
6873 }
6874 return NO_ERROR;
6875}
6876
François Gaffie11d30102018-11-02 16:09:09 +01006877status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006878 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006879{
François Gaffie11d30102018-11-02 16:09:09 +01006880 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006881 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006882 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006883 }
6884
Eric Laurentd4692962014-05-05 18:13:44 -07006885 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006886 sp<AudioInputDescriptor> desc;
6887
jiabinbf5f4262023-04-12 21:48:34 +00006888 // first call getAudioPort to get the supported attributes from the HAL
6889 struct audio_port_v7 port = {};
6890 device->toAudioPort(&port);
6891 status_t status = mpClientInterface->getAudioPort(&port);
6892 if (status == NO_ERROR) {
6893 device->importAudioPort(port);
6894 }
6895
Eric Laurent0dd51852019-04-19 18:18:58 -07006896 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006897 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006898 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006899 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006900 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006901 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006902 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006903
François Gaffie11d30102018-11-02 16:09:09 +01006904 if (profile->supportsDevice(device)) {
6905 profiles.add(profile);
6906 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6907 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006908 }
6909 }
6910 }
6911
Eric Laurent0dd51852019-04-19 18:18:58 -07006912 if (profiles.isEmpty()) {
6913 ALOGW("%s: No input profile available for device %s",
6914 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006915 return BAD_VALUE;
6916 }
6917
6918 // open inputs for matching profiles if needed. Direct inputs are also opened to
6919 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6920 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6921
Eric Laurent1c333e22014-05-20 10:48:17 -07006922 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006923
Eric Laurentd4692962014-05-05 18:13:44 -07006924 // nothing to do if one input is already opened for this profile
6925 size_t input_index;
6926 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6927 desc = mInputs.valueAt(input_index);
6928 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006929 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006930 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006931 }
Eric Laurentd4692962014-05-05 18:13:44 -07006932 break;
6933 }
6934 }
6935 if (input_index != mInputs.size()) {
6936 continue;
6937 }
6938
Eric Laurent3974e3b2017-12-07 17:58:43 -08006939 if (!profile->canOpenNewIo()) {
6940 ALOGW("Max Input number %u already opened for this profile %s",
6941 profile->maxOpenCount, profile->getTagName().c_str());
6942 continue;
6943 }
6944
Eric Laurentfe231122017-11-17 17:48:06 -08006945 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006946 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006947 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006948
Eric Laurentcf2c0212014-07-25 16:20:43 -07006949 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006950 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006951 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006952 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006953 mpClientInterface->setParameters(input, String8(param));
6954 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006955 }
jiabin12537fc2023-10-12 17:56:08 +00006956 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006957 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006958 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006959 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006960 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006961 }
6962
Eric Laurent0dd51852019-04-19 18:18:58 -07006963 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006964 addInput(input, desc);
6965 }
6966 } // endif input != 0
6967
Eric Laurentcf2c0212014-07-25 16:20:43 -07006968 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006969 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006970 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006971 profiles.removeAt(profile_index);
6972 profile_index--;
6973 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006974 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006975 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006976 }
Eric Laurentd4692962014-05-05 18:13:44 -07006977 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006978
6979 if (checkCloseInput(desc)) {
6980 ALOGV("%s closing input %d", __func__, input);
6981 closeInput(input);
6982 }
Eric Laurentd4692962014-05-05 18:13:44 -07006983 }
6984 } // end scan profiles
6985
6986 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006987 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006988 return BAD_VALUE;
6989 }
6990 } else {
6991 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006992 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006993 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006994 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006995 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006996 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006997 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006998 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006999 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
7000 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007001 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007002 }
7003 }
7004 }
7005 } // end disconnect
7006
7007 return NO_ERROR;
7008}
7009
7010
Eric Laurente0720872014-03-11 09:30:41 -07007011void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007012{
7013 ALOGV("closeOutput(%d)", output);
7014
François Gaffie1c878552018-11-22 16:53:21 +01007015 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7016 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007017 ALOGW("closeOutput() unknown output %d", output);
7018 return;
7019 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007020 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007021 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007022
Eric Laurente552edb2014-03-10 17:42:56 -07007023 // look for duplicated outputs connected to the output being removed.
7024 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007025 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7026 if (dupOutput->isDuplicated() &&
7027 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7028 sp<SwAudioOutputDescriptor> remainingOutput =
7029 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007030 // As all active tracks on duplicated output will be deleted,
7031 // and as they were also referenced on the other output, the reference
7032 // count for their stream type must be adjusted accordingly on
7033 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007034 const bool wasActive = remainingOutput->isActive();
7035 // Note: no-op on the closing output where all clients has already been set inactive
7036 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007037 // stop() will be a no op if the output is still active but is needed in case all
7038 // active streams refcounts where cleared above
7039 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007040 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007041 }
Eric Laurente552edb2014-03-10 17:42:56 -07007042 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7043 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7044
7045 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007046 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007047 }
7048 }
7049
Eric Laurent05b90f82014-08-27 15:32:29 -07007050 nextAudioPortGeneration();
7051
François Gaffie1c878552018-11-22 16:53:21 +01007052 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007053 if (index >= 0) {
7054 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007055 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7056 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007057 mAudioPatches.removeItemsAt(index);
7058 mpClientInterface->onAudioPatchListUpdate();
7059 }
7060
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007061 if (closingOutputWasActive) {
7062 closingOutput->stop();
7063 }
François Gaffie1c878552018-11-22 16:53:21 +01007064 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007065 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007066 for (const auto device : closingOutput->devices()) {
7067 device->setPreferredConfig(nullptr);
7068 }
7069 }
Eric Laurente552edb2014-03-10 17:42:56 -07007070
François Gaffie53615e22015-03-19 09:24:12 +01007071 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007072 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007073 if (closingOutput == mSpatializerOutput) {
7074 mSpatializerOutput.clear();
7075 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007076
7077 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7078 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007079 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007080 bool directOutputOpen = false;
7081 for (size_t i = 0; i < mOutputs.size(); i++) {
7082 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7083 directOutputOpen = true;
7084 break;
7085 }
7086 }
7087 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007088 ALOGV("no direct outputs open, reset MSD patches");
7089 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7090 // how output devices for patching are resolved. Avoid by caching and reusing the
7091 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7092 // devices to patch to. This may be complicated by the fact that devices may become
7093 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007094 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007095 }
7096 }
jiabin220eea12024-05-17 17:55:20 +00007097
7098 if (closingOutput->mPreferredAttrInfo != nullptr) {
7099 closingOutput->mPreferredAttrInfo->resetActiveClient();
7100 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007101}
7102
7103void AudioPolicyManager::closeInput(audio_io_handle_t input)
7104{
7105 ALOGV("closeInput(%d)", input);
7106
7107 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7108 if (inputDesc == NULL) {
7109 ALOGW("closeInput() unknown input %d", input);
7110 return;
7111 }
7112
Eric Laurent6a94d692014-05-20 11:18:06 -07007113 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007114
François Gaffie11d30102018-11-02 16:09:09 +01007115 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007116 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007117 if (index >= 0) {
7118 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007119 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7120 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007121 mAudioPatches.removeItemsAt(index);
7122 mpClientInterface->onAudioPatchListUpdate();
7123 }
7124
François Gaffie6ebbce02023-07-19 13:27:53 +02007125 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007126 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007127 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007128
François Gaffie11d30102018-11-02 16:09:09 +01007129 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7130 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007131 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007132 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007133 }
Eric Laurente552edb2014-03-10 17:42:56 -07007134}
7135
François Gaffie11d30102018-11-02 16:09:09 +01007136SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7137 const DeviceVector &devices,
7138 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007139{
7140 SortedVector<audio_io_handle_t> outputs;
7141
François Gaffie11d30102018-11-02 16:09:09 +01007142 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007143 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007144 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007145 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007146 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007147 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007148 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007149 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007150 outputs.add(openOutputs.keyAt(i));
7151 }
7152 }
7153 return outputs;
7154}
7155
Mikhail Naganov37977152018-07-11 15:54:44 -07007156void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7157{
7158 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7159 // output is suspended before any tracks are moved to it
7160 checkA2dpSuspend();
7161 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007162 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007163 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007164 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007165 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007166 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7167 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7168 // configuration changes will ultimately be rerouted correctly. We can still avoid
7169 // unnecessary rerouting by caching and reusing the arguments to
7170 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7171 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007172 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007173 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007174 // an event that changed routing likely occurred, inform upper layers
7175 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007176}
7177
François Gaffiec005e562018-11-06 15:04:49 +01007178bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7179 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007180{
François Gaffiec005e562018-11-06 15:04:49 +01007181 return mEngine->getProductStrategyForAttributes(lAttr) ==
7182 mEngine->getProductStrategyForAttributes(rAttr);
7183}
7184
Francois Gaffieff1eb522020-05-06 18:37:04 +02007185void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7186{
7187 for (size_t i = 0; i < mAudioSources.size(); i++) {
7188 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7189 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007190 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007191 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007192 connectAudioSource(sourceDesc);
7193 }
7194 }
7195}
7196
7197void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7198{
7199 for (size_t i = 0; i < mAudioSources.size(); i++) {
7200 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7201 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7202 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7203 disconnectAudioSource(sourceDesc);
7204 }
7205 }
7206}
7207
François Gaffiec005e562018-11-06 15:04:49 +01007208void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7209{
7210 auto psId = mEngine->getProductStrategyForAttributes(attr);
7211
7212 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7213 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007214
François Gaffie11d30102018-11-02 16:09:09 +01007215 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7216 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007217
Eric Laurentc209fe42020-06-05 18:11:23 -07007218 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007219 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007220 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007221 // take into account dynamic audio policies related changes: if a client is now associated
7222 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007223 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007224 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7225 if (desc->isDuplicated()) {
7226 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007227 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007228 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7229 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7230 continue;
7231 }
7232 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007233 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007234 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7235 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7236 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007237 if (status != OK) {
7238 continue;
7239 }
yucliuf4de36d2020-09-14 14:57:56 -07007240 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007241 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007242 maxLatency = desc->latency();
7243 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007244 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007245 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007246 }
7247 }
7248
Eric Laurent56ed8842022-11-15 16:04:41 +01007249 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007250 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7251 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007252 for (audio_io_handle_t srcOut : srcOutputs) {
7253 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007254 if (desc == nullptr) continue;
7255
7256 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007257 maxLatency = desc->latency();
7258 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007259
Eric Laurent56ed8842022-11-15 16:04:41 +01007260 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007261 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007262 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007263 // a client on a non direct outputs has necessarily a linear PCM format
7264 // so we can call selectOutput() safely
7265 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7266 client->flags(),
7267 client->config().format,
7268 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007269 client->config().sample_rate,
7270 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007271 if (newOutput != srcOut) {
7272 invalidate = true;
7273 break;
7274 }
7275 } else {
7276 sp<IOProfile> profile = getProfileForOutput(newDevices,
7277 client->config().sample_rate,
7278 client->config().format,
7279 client->config().channel_mask,
7280 client->flags(),
7281 true /* directOnly */);
7282 if (profile != desc->mProfile) {
7283 invalidate = true;
7284 break;
7285 }
7286 }
7287 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007288 // mute strategy while moving tracks from one output to another
7289 if (invalidate) {
7290 invalidatedOutputs.push_back(desc);
7291 if (desc->isStrategyActive(psId)) {
7292 setStrategyMute(psId, true, desc);
7293 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7294 newDevices.types());
7295 }
Eric Laurente552edb2014-03-10 17:42:56 -07007296 }
François Gaffiec005e562018-11-06 15:04:49 +01007297 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007298 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007299 connectAudioSource(source);
7300 }
Eric Laurente552edb2014-03-10 17:42:56 -07007301 }
7302
Eric Laurent56ed8842022-11-15 16:04:41 +01007303 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7304 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7305 std::to_string(srcOutputs[0]).c_str(),
7306 std::to_string(dstOutputs[0]).c_str());
7307
François Gaffiec005e562018-11-06 15:04:49 +01007308 // Move effects associated to this stream from previous output to new output
7309 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007310 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007311 }
François Gaffiec005e562018-11-06 15:04:49 +01007312 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007313 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007314 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007315 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007316 desc->setTracksInvalidatedStatusByStrategy(psId);
7317 }
Eric Laurente552edb2014-03-10 17:42:56 -07007318 }
7319 }
7320}
7321
Eric Laurente0720872014-03-11 09:30:41 -07007322void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007323{
François Gaffiec005e562018-11-06 15:04:49 +01007324 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7325 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7326 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007327 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007328 }
Eric Laurente552edb2014-03-10 17:42:56 -07007329}
7330
Kevin Rocard153f92d2018-12-18 18:33:28 -08007331void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007332 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007333 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007334 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007335 for (size_t i = 0; i < mOutputs.size(); i++) {
7336 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7337 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007338 sp<AudioPolicyMix> primaryMix;
7339 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007340 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007341 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7342 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7343 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007344 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7345 for (auto &secondaryMix : secondaryMixes) {
7346 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7347 if (outputDesc != nullptr &&
7348 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7349 secondaryDescs.push_back(outputDesc);
7350 }
7351 }
7352
jiabinc44b3462022-12-08 12:52:31 -08007353 if (status != OK &&
7354 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7355 // When it failed to query secondary output, only invalidate the client that is not
7356 // MMAP. The reason is that MMAP stream will not support secondary output.
7357 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007358 } else if (!std::equal(
7359 client->getSecondaryOutputs().begin(),
7360 client->getSecondaryOutputs().end(),
7361 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007362 if (!audio_is_linear_pcm(client->config().format)) {
7363 // If the format is not PCM, the tracks should be invalidated to get correct
7364 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007365 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007366 } else {
7367 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7368 std::vector<audio_io_handle_t> secondaryOutputIds;
7369 for (const auto &secondaryDesc: secondaryDescs) {
7370 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7371 weakSecondaryDescs.push_back(secondaryDesc);
7372 }
7373 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7374 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007375 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007376 }
7377 }
7378 }
jiabin10a03f12021-05-07 23:46:28 +00007379 if (!trackSecondaryOutputs.empty()) {
7380 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7381 }
jiabinc44b3462022-12-08 12:52:31 -08007382 if (!clientsToInvalidate.empty()) {
7383 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7384 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007385 }
7386}
7387
Eric Laurent2517af32020-11-25 15:31:27 +01007388bool AudioPolicyManager::isScoRequestedForComm() const {
7389 AudioDeviceTypeAddrVector devices;
7390 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7391 for (const auto &device : devices) {
7392 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7393 return true;
7394 }
7395 }
7396 return false;
7397}
7398
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007399bool AudioPolicyManager::isHearingAidUsedForComm() const {
7400 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7401 true /*fromCache*/);
7402 for (const auto &device : devices) {
7403 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7404 return true;
7405 }
7406 }
7407 return false;
7408}
7409
7410
Eric Laurente0720872014-03-11 09:30:41 -07007411void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
François Gaffie53615e22015-03-19 09:24:12 +01007413 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007414 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007415 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007416 return;
7417 }
7418
Eric Laurent3a4311c2014-03-17 12:00:47 -07007419 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007420 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7421 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007422 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007423
7424 // if suspended, restore A2DP output if:
7425 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007426 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007427 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007428 //
Eric Laurentf732e072016-08-03 19:30:28 -07007429 // if not suspended, suspend A2DP output if:
7430 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007431 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007432 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007433 //
7434 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007435 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007436 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007437 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007438 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007439
7440 mpClientInterface->restoreOutput(a2dpOutput);
7441 mA2dpSuspended = false;
7442 }
7443 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007444 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007445 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007446 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007447 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007448
7449 mpClientInterface->suspendOutput(a2dpOutput);
7450 mA2dpSuspended = true;
7451 }
7452 }
7453}
7454
François Gaffie11d30102018-11-02 16:09:09 +01007455DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7456 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007457{
François Gaffiedb1755b2023-09-01 11:50:35 +02007458 if (outputDesc == nullptr) {
7459 return DeviceVector{};
7460 }
François Gaffie11d30102018-11-02 16:09:09 +01007461
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007462 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007463 if (index >= 0) {
7464 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007465 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007466 ALOGV("%s device %s forced by patch %d", __func__,
7467 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7468 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007469 }
7470 }
7471
Dean Wheatley514b4312020-06-17 21:45:00 +10007472 // Do not retrieve engine device for outputs through MSD
7473 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7474 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7475 return outputDesc->devices();
7476 }
7477
Eric Laurent97ac8712018-07-27 18:59:02 -07007478 // Honor explicit routing requests only if no client using default routing is active on this
7479 // input: a specific app can not force routing for other apps by setting a preferred device.
7480 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007481 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007482 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007483 if (device != nullptr) {
7484 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007485 }
7486
François Gaffiea807ef92018-11-05 10:44:33 +01007487 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7488 // of setForceUse / Default Bus device here
7489 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7490 if (device != nullptr) {
7491 return DeviceVector(device);
7492 }
7493
François Gaffiedb1755b2023-09-01 11:50:35 +02007494 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007495 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7496 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307497 auto hasStreamActive = [&](auto stream) {
7498 return hasStream(streams, stream) && isStreamActive(stream, 0);
7499 };
Eric Laurent484e9272018-06-07 17:29:23 -07007500
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307501 auto doGetOutputDevicesForVoice = [&]() {
7502 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007503 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307504 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007505 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7506 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307507 };
7508
7509 // With low-latency playing on speaker, music on WFD, when the first low-latency
7510 // output is stopped, getNewOutputDevices checks for a product strategy
7511 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007512 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307513 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7514 // stream is associated to the output descriptor.
7515 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7516 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7517 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7518 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007519 // Retrieval of devices for voice DL is done on primary output profile, cannot
7520 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007521 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007522 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7523 break;
7524 }
Eric Laurente552edb2014-03-10 17:42:56 -07007525 }
François Gaffiec005e562018-11-06 15:04:49 +01007526 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007527 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007528}
7529
François Gaffie11d30102018-11-02 16:09:09 +01007530sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7531 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007532{
François Gaffie11d30102018-11-02 16:09:09 +01007533 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007534
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007535 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007536 if (index >= 0) {
7537 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007538 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007539 ALOGV("getNewInputDevice() device %s forced by patch %d",
7540 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7541 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007542 }
7543 }
7544
Eric Laurent97ac8712018-07-27 18:59:02 -07007545 // Honor explicit routing requests only if no client using default routing is active on this
7546 // input: a specific app can not force routing for other apps by setting a preferred device.
7547 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007548 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7549 if (device != nullptr) {
7550 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007551 }
7552
Eric Laurentdc95a252018-04-12 12:46:56 -07007553 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007554 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007555 audio_attributes_t attributes;
7556 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007557 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007558 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7559 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007560 attributes = topClient->attributes();
7561 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007562 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007563 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007564 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7565 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007566 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007567 }
7568
Francois Gaffie716e1432019-01-14 16:58:59 +01007569 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7570 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007571 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007572 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007573 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007574 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007575
Eric Laurente552edb2014-03-10 17:42:56 -07007576 return device;
7577}
7578
Eric Laurent794fde22016-03-11 09:50:45 -08007579bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7580 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007581 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007582}
7583
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007584status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007585 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007586 if (devices == nullptr) {
7587 return BAD_VALUE;
7588 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007589
Andy Hung6d23c0f2022-02-16 09:37:15 -08007590 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007591 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7592 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007593 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007594 for (const auto& device : curDevices) {
7595 devices->push_back(device->getDeviceTypeAddr());
7596 }
7597 return NO_ERROR;
7598}
7599
Eric Laurente0720872014-03-11 09:30:41 -07007600void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007601 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007602 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007603 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007604 updateDevicesAndOutputs();
7605 break;
7606 default:
7607 break;
7608 }
7609}
7610
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007611uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007612
7613 // skip beacon mute management if a dedicated TTS output is available
7614 if (mTtsOutputAvailable) {
7615 return 0;
7616 }
7617
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007618 switch(event) {
7619 case STARTING_OUTPUT:
7620 mBeaconMuteRefCount++;
7621 break;
7622 case STOPPING_OUTPUT:
7623 if (mBeaconMuteRefCount > 0) {
7624 mBeaconMuteRefCount--;
7625 }
7626 break;
7627 case STARTING_BEACON:
7628 mBeaconPlayingRefCount++;
7629 break;
7630 case STOPPING_BEACON:
7631 if (mBeaconPlayingRefCount > 0) {
7632 mBeaconPlayingRefCount--;
7633 }
7634 break;
7635 }
7636
7637 if (mBeaconMuteRefCount > 0) {
7638 // any playback causes beacon to be muted
7639 return setBeaconMute(true);
7640 } else {
7641 // no other playback: unmute when beacon starts playing, mute when it stops
7642 return setBeaconMute(mBeaconPlayingRefCount == 0);
7643 }
7644}
7645
7646uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7647 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7648 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7649 // keep track of muted state to avoid repeating mute/unmute operations
7650 if (mBeaconMuted != mute) {
7651 // mute/unmute AUDIO_STREAM_TTS on all outputs
7652 ALOGV("\t muting %d", mute);
7653 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007654 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7655 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7656 ALOGV("\t no tts volume source available");
7657 return 0;
7658 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007659 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007660 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007661 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007662 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007663 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007664 maxLatency = latency;
7665 }
7666 }
7667 mBeaconMuted = mute;
7668 return maxLatency;
7669 }
7670 return 0;
7671}
7672
Eric Laurente0720872014-03-11 09:30:41 -07007673void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007674{
François Gaffiec005e562018-11-06 15:04:49 +01007675 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007676 mPreviousOutputs = mOutputs;
7677}
7678
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007679uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007680 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007681 uint32_t delayMs)
7682{
7683 // mute/unmute strategies using an incompatible device combination
7684 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7685 // if unmuting, unmute only after the specified delay
7686 if (outputDesc->isDuplicated()) {
7687 return 0;
7688 }
7689
7690 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007691 DeviceVector devices = outputDesc->devices();
7692 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007693
François Gaffiec005e562018-11-06 15:04:49 +01007694 auto productStrategies = mEngine->getOrderedProductStrategies();
7695 for (const auto &productStrategy : productStrategies) {
7696 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7697 DeviceVector curDevices =
7698 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7699 curDevices = curDevices.filter(outputDesc->supportedDevices());
7700 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007701 bool doMute = false;
7702
François Gaffiec005e562018-11-06 15:04:49 +01007703 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007704 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007705 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7706 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007707 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007708 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007709 }
Eric Laurent99401132014-05-07 19:48:15 -07007710 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007711 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007712 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007713 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007714 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007715 continue;
7716 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307717 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007718 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7719 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7720 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007721 if (mute) {
7722 // FIXME: should not need to double latency if volume could be applied
7723 // immediately by the audioflinger mixer. We must account for the delay
7724 // between now and the next time the audioflinger thread for this output
7725 // will process a buffer (which corresponds to one buffer size,
7726 // usually 1/2 or 1/4 of the latency).
7727 if (muteWaitMs < desc->latency() * 2) {
7728 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007729 }
7730 }
7731 }
7732 }
7733 }
7734 }
7735
Eric Laurent99401132014-05-07 19:48:15 -07007736 // temporary mute output if device selection changes to avoid volume bursts due to
7737 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007738 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007739 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007740
Eric Laurentdc462862016-07-19 12:29:53 -07007741 if (muteWaitMs < tempMuteWaitMs) {
7742 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007743 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007744
7745 // If recommended duration is defined, replace temporary mute duration to avoid
7746 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7747 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7748 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7749 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7750 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7751
François Gaffieaaac0fd2018-11-22 17:56:39 +01007752 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7753 // make sure that we do not start the temporary mute period too early in case of
7754 // delayed device change
7755 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7756 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007757 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007758 }
7759 }
7760
Eric Laurente552edb2014-03-10 17:42:56 -07007761 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7762 if (muteWaitMs > delayMs) {
7763 muteWaitMs -= delayMs;
7764 usleep(muteWaitMs * 1000);
7765 return muteWaitMs;
7766 }
7767 return 0;
7768}
7769
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307770uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7771 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007772 const DeviceVector &devices,
7773 bool force,
7774 int delayMs,
7775 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007776 bool requiresMuteCheck, bool requiresVolumeCheck,
7777 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007778{
jiabin3ff8d7d2022-12-13 06:27:44 +00007779 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307780 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7781 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7782 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007783 uint32_t muteWaitMs;
7784
7785 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307786 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007787 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307788 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007789 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007790 return muteWaitMs;
7791 }
Eric Laurente552edb2014-03-10 17:42:56 -07007792
7793 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007794 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007795 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007796 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007797
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307798 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7799 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007800
7801 if (!filteredDevices.isEmpty()) {
7802 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007803 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007804
7805 // if the outputs are not materially active, there is no need to mute.
7806 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007807 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007808 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307809 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7810 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007811 muteWaitMs = 0;
7812 }
Eric Laurente552edb2014-03-10 17:42:56 -07007813
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007814 bool outputRouted = outputDesc->isRouted();
7815
Eric Laurent79ea9582020-06-11 18:49:24 -07007816 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7817 // output profile or if new device is not supported AND previous device(s) is(are) still
7818 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007819 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307820 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7821 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007822 // restore previous device after evaluating strategy mute state
7823 outputDesc->setDevices(prevDevices);
7824 return muteWaitMs;
7825 }
7826
Eric Laurente552edb2014-03-10 17:42:56 -07007827 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007828 // the requested device is AUDIO_DEVICE_NONE
7829 // OR the requested device is the same as current device
7830 // AND force is not specified
7831 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007832 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007833 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307834 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7835 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7836 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007837 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307838 ALOGV("%s %s setting same device on routed output, force apply volumes",
7839 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007840 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7841 }
Eric Laurente552edb2014-03-10 17:42:56 -07007842 return muteWaitMs;
7843 }
7844
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307845 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7846 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007847
Eric Laurente552edb2014-03-10 17:42:56 -07007848 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007849 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007850 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007851 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007852 PatchBuilder patchBuilder;
7853 patchBuilder.addSource(outputDesc);
7854 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7855 for (const auto &filteredDevice : filteredDevices) {
7856 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007857 }
7858
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007859 // Add half reported latency to delayMs when muteWaitMs is null in order
7860 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007861 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7862 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7863 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007864 }
Eric Laurente552edb2014-03-10 17:42:56 -07007865
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007866 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7867 if (!skipMuteDelay) {
7868 // update stream volumes according to new device
7869 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7870 }
Eric Laurente552edb2014-03-10 17:42:56 -07007871
7872 return muteWaitMs;
7873}
7874
Eric Laurentc75307b2015-03-17 15:29:32 -07007875status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007876 int delayMs,
7877 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007878{
Eric Laurent6a94d692014-05-20 11:18:06 -07007879 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007880 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7881 return INVALID_OPERATION;
7882 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007883 if (patchHandle) {
7884 index = mAudioPatches.indexOfKey(*patchHandle);
7885 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007886 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007887 }
7888 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007889 return INVALID_OPERATION;
7890 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007891 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007892 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007893 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007894 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007895 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007896 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007897 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007898 return status;
7899}
7900
7901status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007902 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007903 bool force,
7904 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007905{
7906 status_t status = NO_ERROR;
7907
Eric Laurent1f2f2232014-06-02 12:01:23 -07007908 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007909 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7910 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007911
François Gaffie11d30102018-11-02 16:09:09 +01007912 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007913 PatchBuilder patchBuilder;
7914 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007915 // AUDIO_SOURCE_HOTWORD is for internal use only:
7916 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007917 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7918 auto result = usecase;
7919 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7920 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7921 }
7922 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007923 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007924 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007925 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007926 }
7927 }
7928 return status;
7929}
7930
Eric Laurent6a94d692014-05-20 11:18:06 -07007931status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7932 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007933{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007934 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007935 ssize_t index;
7936 if (patchHandle) {
7937 index = mAudioPatches.indexOfKey(*patchHandle);
7938 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007939 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007940 }
7941 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007942 return INVALID_OPERATION;
7943 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007944 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007945 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007946 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007947 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007948 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007949 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007950 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007951 return status;
7952}
7953
François Gaffie11d30102018-11-02 16:09:09 +01007954sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007955 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007956 audio_format_t& format,
7957 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007958 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007959{
7960 // Choose an input profile based on the requested capture parameters: select the first available
7961 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007962 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007963
Atneya Nair0f0a8032022-12-12 16:20:12 -08007964 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7965 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7966 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7967
7968 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007969
jiabin2fd710d2022-05-02 23:20:22 +00007970 for (;;) {
7971 sp<IOProfile> firstInexact = nullptr;
7972 uint32_t updatedSamplingRate = 0;
7973 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7974 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7975 for (const auto& hwModule : mHwModules) {
7976 for (const auto& profile : hwModule->getInputProfiles()) {
7977 // profile->log();
7978 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007979 if (profile->getCompatibilityScore(
7980 DeviceVector(device),
7981 samplingRate,
7982 &updatedSamplingRate,
7983 format,
7984 &updatedFormat,
7985 channelMask,
7986 &updatedChannelMask,
7987 // FIXME ugly cast
7988 (audio_output_flags_t) flags,
7989 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7990 samplingRate = updatedSamplingRate;
7991 format = updatedFormat;
7992 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007993 return profile;
7994 }
jiabin66acc432024-02-06 00:57:36 +00007995 if (firstInexact == nullptr
7996 && profile->getCompatibilityScore(
7997 DeviceVector(device),
7998 samplingRate,
7999 &updatedSamplingRate,
8000 format,
8001 &updatedFormat,
8002 channelMask,
8003 &updatedChannelMask,
8004 // FIXME ugly cast
8005 (audio_output_flags_t) flags,
8006 false /*exactMatchRequiredForInputFlags*/)
8007 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008008 firstInexact = profile;
8009 }
8010 }
8011 }
8012
8013 if (firstInexact != nullptr) {
8014 samplingRate = updatedSamplingRate;
8015 format = updatedFormat;
8016 channelMask = updatedChannelMask;
8017 return firstInexact;
8018 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8019 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8020 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8021 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8022 flags = AUDIO_INPUT_FLAG_NONE;
8023 } else { // fail
8024 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8025 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8026 samplingRate, format, channelMask, oriFlags);
8027 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008028 }
8029 }
jiabin2fd710d2022-05-02 23:20:22 +00008030
8031 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008032}
8033
Vlad Popa87e0e582024-05-20 18:49:20 -07008034float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8035 VolumeSource volumeSource,
8036 int index,
8037 const DeviceTypeSet &deviceTypes)
8038{
8039 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8040 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8041 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8042
8043 if (com_android_media_audio_abs_volume_index_fix()) {
8044 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8045 mAbsoluteVolumeDrivingStreams.end()) {
8046 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8047 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8048 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8049 ALOGD("%s: no group matching with %s", __FUNCTION__,
8050 toString(attributesToDriveAbs).c_str());
8051 return volumeDb;
8052 }
8053
8054 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8055 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8056 if (vsToDriveAbs == volumeSource) {
8057 // attenuation is applied by the abs volume controller
8058 return volumeDbMax;
8059 } else {
8060 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8061 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8062 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8063 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8064 curvesAbs.getVolumeIndexMax());
8065 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8066 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8067 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8068 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8069 return newVolumeDb;
8070 }
8071 }
8072 return volumeDb;
8073 } else {
8074 return volumeDb;
8075 }
8076}
8077
François Gaffieaaac0fd2018-11-22 17:56:39 +01008078float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8079 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008080 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008081 const DeviceTypeSet& deviceTypes,
8082 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008083{
Vlad Popa87e0e582024-05-20 18:49:20 -07008084 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008085 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8086 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8087
8088 if (!computeInternalInteraction) {
8089 return volumeDb;
8090 }
8091
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008092 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8093 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8094 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8095 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008096 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8097 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8098 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8099 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8100 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008101 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008102 mOutputs.isActive(ringVolumeSrc, 0)) {
8103 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008104 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8105 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008106 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008107 }
8108
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008109 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008110 if ((volumeSource != callVolumeSrc && (isInCall() ||
8111 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008112 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008113 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8114 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008115 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8116 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8117 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008118 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008119 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008120 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008121 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008122 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8123 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008124 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008125 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8126 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8127 // programmatically muted.
8128 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8129 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8130 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008131 bool exemptFromCapping =
8132 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8133 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008134 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8135 volumeSource, volumeDb);
8136 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008137 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8138 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8139 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008140 }
8141 }
Eric Laurente552edb2014-03-10 17:42:56 -07008142 // if a headset is connected, apply the following rules to ring tones and notifications
8143 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008144 // - always attenuate notifications volume by 6dB
8145 // - attenuate ring tones volume by 6dB unless music is not playing and
8146 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008147 // - if music is playing, always limit the volume to current music volume,
8148 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008149 if (!Intersection(deviceTypes,
8150 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8151 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008152 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8153 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008154 ((volumeSource == alarmVolumeSrc ||
8155 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008156 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8157 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8158 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008159 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8160 curves.canBeMuted()) {
8161
Eric Laurente552edb2014-03-10 17:42:56 -07008162 // when the phone is ringing we must consider that music could have been paused just before
8163 // by the music application and behave as if music was active if the last music track was
8164 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008165 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8166 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008167 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008168 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008169 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8170 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008171 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008172 float musicVolDb = computeVolume(musicCurves,
8173 musicVolumeSrc,
8174 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008175 musicDevice,
8176 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008177 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8178 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8179 if (volumeDb > minVolDb) {
8180 volumeDb = minVolDb;
8181 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008182 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008183 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8184 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008185 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8186 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8187 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8188 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008189 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008190 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008191 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8192 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008193 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8194 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008195 }
8196 }
jiabin9a3361e2019-10-01 09:38:30 -07008197 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008198 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008199 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008200 }
8201 }
8202
François Gaffie43c73442018-11-08 08:21:55 +01008203 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008204}
8205
Eric Laurent3839bc02018-07-10 18:33:34 -07008206int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008207 VolumeSource fromVolumeSource,
8208 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008209{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008210 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008211 return srcIndex;
8212 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008213 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8214 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008215 float minSrc = (float)srcCurves.getVolumeIndexMin();
8216 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8217 float minDst = (float)dstCurves.getVolumeIndexMin();
8218 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008219
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008220 // preserve mute request or correct range
8221 if (srcIndex < minSrc) {
8222 if (srcIndex == 0) {
8223 return 0;
8224 }
8225 srcIndex = minSrc;
8226 } else if (srcIndex > maxSrc) {
8227 srcIndex = maxSrc;
8228 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008229 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8230}
8231
François Gaffieaaac0fd2018-11-22 17:56:39 +01008232status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8233 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008234 int index,
8235 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008236 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008237 int delayMs,
8238 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008239{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008240 // do not change actual attributes volume if the attributes is muted
8241 if (outputDesc->isMuted(volumeSource)) {
8242 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8243 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008244 return NO_ERROR;
8245 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008246
Eric Laurentae6e88c2024-01-10 14:42:57 +01008247 bool isVoiceVolSrc;
8248 bool isBtScoVolSrc;
8249 if (!isVolumeConsistentForCalls(
8250 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008251 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008252 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008253 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008254 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008255
jiabin9a3361e2019-10-01 09:38:30 -07008256 if (deviceTypes.empty()) {
8257 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008258 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008259 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008260 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008261 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008262
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008263 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8264 ALOGE("invalid volume index range");
8265 return BAD_VALUE;
8266 }
8267
jiabin9a3361e2019-10-01 09:38:30 -07008268 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8269 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008270 // Force VoIP volume to max for bluetooth SCO device except if muted
8271 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008272 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008273 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008274 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008275 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008276 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8277 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008278
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008279 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008280 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008281 }
Eric Laurente552edb2014-03-10 17:42:56 -07008282 return NO_ERROR;
8283}
8284
Eric Laurentae6e88c2024-01-10 14:42:57 +01008285void AudioPolicyManager::setVoiceVolume(
8286 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8287 float voiceVolume;
8288 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8289 // by the headset
8290 if (isVoiceVolSrc) {
8291 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8292 } else {
8293 voiceVolume = index == 0 ? 0.0 : 1.0;
8294 }
8295 if (voiceVolume != mLastVoiceVolume) {
8296 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8297 mLastVoiceVolume = voiceVolume;
8298 }
8299}
8300
8301bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8302 const DeviceTypeSet& deviceTypes,
8303 bool& isVoiceVolSrc,
8304 bool& isBtScoVolSrc,
8305 const char* caller) {
8306 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8307 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8308 const bool isScoRequested = isScoRequestedForComm();
8309 const bool isHAUsed = isHearingAidUsedForComm();
8310
8311 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8312 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8313
8314 if ((callVolSrc != btScoVolSrc) &&
8315 ((isVoiceVolSrc && isScoRequested) ||
8316 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8317 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8318 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8319 volumeSource, isScoRequested ? " " : " not ");
8320 return false;
8321 }
8322 return true;
8323}
8324
Eric Laurentc75307b2015-03-17 15:29:32 -07008325void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008326 const DeviceTypeSet& deviceTypes,
8327 int delayMs,
8328 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008329{
jiabincd510522020-01-22 09:40:55 -08008330 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008331 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8332 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8333 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008334 curves.getVolumeIndex(deviceTypes),
8335 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008336 }
8337}
8338
François Gaffiec005e562018-11-06 15:04:49 +01008339void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8340 bool on,
8341 const sp<AudioOutputDescriptor>& outputDesc,
8342 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008343 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008344{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008345 std::vector<VolumeSource> sourcesToMute;
8346 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8347 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8348 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008349 VolumeSource source = toVolumeSource(attributes, false);
8350 if ((source != VOLUME_SOURCE_NONE) &&
8351 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8352 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008353 sourcesToMute.push_back(source);
8354 }
Eric Laurente552edb2014-03-10 17:42:56 -07008355 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008356 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008357 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008358 }
8359
Eric Laurente552edb2014-03-10 17:42:56 -07008360}
8361
François Gaffieaaac0fd2018-11-22 17:56:39 +01008362void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8363 bool on,
8364 const sp<AudioOutputDescriptor>& outputDesc,
8365 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008366 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008367{
jiabin9a3361e2019-10-01 09:38:30 -07008368 if (deviceTypes.empty()) {
8369 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008370 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008371 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008372 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008373 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008374 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008375 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008376 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8377 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008378 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008379 }
8380 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008381 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8382 // ignored
8383 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008384 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008385 if (!outputDesc->isMuted(volumeSource)) {
8386 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008387 return;
8388 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008389 if (outputDesc->decMuteCount(volumeSource) == 0) {
8390 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008391 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008392 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008393 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008394 delayMs);
8395 }
8396 }
8397}
8398
François Gaffie53615e22015-03-19 09:24:12 +01008399bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8400{
François Gaffiec005e562018-11-06 15:04:49 +01008401 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008402 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8403 return true;
8404 }
8405
8406 // has known usage?
8407 switch (paa->usage) {
8408 case AUDIO_USAGE_UNKNOWN:
8409 case AUDIO_USAGE_MEDIA:
8410 case AUDIO_USAGE_VOICE_COMMUNICATION:
8411 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8412 case AUDIO_USAGE_ALARM:
8413 case AUDIO_USAGE_NOTIFICATION:
8414 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8415 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8416 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8417 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8418 case AUDIO_USAGE_NOTIFICATION_EVENT:
8419 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8420 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8421 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8422 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008423 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008424 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008425 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008426 case AUDIO_USAGE_EMERGENCY:
8427 case AUDIO_USAGE_SAFETY:
8428 case AUDIO_USAGE_VEHICLE_STATUS:
8429 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008430 break;
8431 default:
8432 return false;
8433 }
8434 return true;
8435}
8436
François Gaffie2110e042015-03-24 08:41:51 +01008437audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8438{
8439 return mEngine->getForceUse(usage);
8440}
8441
Eric Laurent96d1dda2022-03-14 17:14:19 +01008442bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008443 return isStateInCall(mEngine->getPhoneState());
8444}
8445
Eric Laurent96d1dda2022-03-14 17:14:19 +01008446bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008447 return is_state_in_call(state);
8448}
8449
Eric Laurentf9cccec2022-11-16 19:12:00 +01008450bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008451 audio_mode_t mode = mEngine->getPhoneState();
8452 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008453 || (mode == AUDIO_MODE_CALL_SCREEN)
8454 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008455}
8456
Eric Laurentf9cccec2022-11-16 19:12:00 +01008457bool AudioPolicyManager::isInCallOrScreening() const {
8458 audio_mode_t mode = mEngine->getPhoneState();
8459 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8460}
8461
Eric Laurentd60560a2015-04-10 11:31:20 -07008462void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8463{
8464 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008465 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008466 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008467 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008468 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008469 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008470 }
8471 }
8472
8473 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8474 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8475 bool release = false;
8476 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8477 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8478 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8479 source->ext.device.type == deviceDesc->type()) {
8480 release = true;
8481 }
8482 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008483 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008484 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8485 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8486 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008487 sink->ext.device.type == deviceDesc->type() &&
8488 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8489 || strncmp(sink->ext.device.address, address,
8490 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008491 release = true;
8492 }
8493 }
8494 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008495 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8496 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008497 }
8498 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008499
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008500 mInputs.clearSessionRoutesForDevice(deviceDesc);
8501
Francois Gaffie716e1432019-01-14 16:58:59 +01008502 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008503}
8504
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008505void AudioPolicyManager::modifySurroundFormats(
8506 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008507 std::unordered_set<audio_format_t> enforcedSurround(
8508 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008509 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008510 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008511 allSurround.insert(pair.first);
8512 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8513 }
Phil Burk09bc4612016-02-24 15:58:15 -08008514
8515 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8516 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008517 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008518 // This is the resulting set of formats depending on the surround mode:
8519 // 'all surround' = allSurround
8520 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8521 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8522 // 'manual surround' = mManualSurroundFormats
8523 // AUTO: formats v 'enforced surround'
8524 // ALWAYS: formats v 'all surround' v 'enforced surround'
8525 // NEVER: formats ^ 'non-surround'
8526 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008527
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008528 std::unordered_set<audio_format_t> formatSet;
8529 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8530 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008531 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008532 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008533 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008534 formatSet.insert(*formatIter);
8535 }
8536 }
8537 } else {
8538 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8539 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008540 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008541
jiabin81772902018-04-02 17:52:27 -07008542 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008543 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008544 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8545 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8546 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008547 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008548 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8549 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8550 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008551 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008552 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008553 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008554 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008555 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008556 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008557}
8558
jiabin06e4bab2019-07-29 10:13:34 -07008559void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8560 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008561 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8562 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8563
8564 // If NEVER, then remove support for channelMasks > stereo.
8565 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008566 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8567 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008568 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008569 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008570 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008571 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008572 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008573 }
8574 }
jiabin81772902018-04-02 17:52:27 -07008575 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8576 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8577 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008578 bool supports5dot1 = false;
8579 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008580 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008581 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8582 supports5dot1 = true;
8583 break;
8584 }
8585 }
8586 // If not then add 5.1 support.
8587 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008588 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008589 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008590 }
Phil Burk09bc4612016-02-24 15:58:15 -08008591 }
8592}
8593
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008594void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008595 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008596 const sp<IOProfile>& profile) {
8597 if (!profile->hasDynamicAudioProfile()) {
8598 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008599 }
François Gaffie112b0af2015-11-19 16:13:25 +01008600
jiabin12537fc2023-10-12 17:56:08 +00008601 audio_port_v7 devicePort;
8602 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008603
jiabin12537fc2023-10-12 17:56:08 +00008604 audio_port_v7 mixPort;
8605 profile->toAudioPort(&mixPort);
8606 mixPort.ext.mix.handle = ioHandle;
8607
8608 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8609 if (status != NO_ERROR) {
8610 ALOGE("%s failed to query the attributes of the mix port", __func__);
8611 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008612 }
jiabin12537fc2023-10-12 17:56:08 +00008613
8614 std::set<audio_format_t> supportedFormats;
8615 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8616 supportedFormats.insert(mixPort.audio_profiles[i].format);
8617 }
8618 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8619 mReportedFormatsMap[devDesc] = formats;
8620
8621 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8622 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8623 modifySurroundFormats(devDesc, &formats);
8624 size_t modifiedNumProfiles = 0;
8625 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8626 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8627 formats.end()) {
8628 // Skip the format that is not present after modifying surround formats.
8629 continue;
8630 }
8631 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8632 sizeof(struct audio_profile));
8633 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8634 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8635 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8636 modifySurroundChannelMasks(&channels);
8637 std::copy(channels.begin(), channels.end(),
8638 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8639 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8640 }
8641 mixPort.num_audio_profiles = modifiedNumProfiles;
8642 }
8643 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008644}
Eric Laurentd60560a2015-04-10 11:31:20 -07008645
Mikhail Naganovdc769682018-05-04 15:34:08 -07008646status_t AudioPolicyManager::installPatch(const char *caller,
8647 audio_patch_handle_t *patchHandle,
8648 AudioIODescriptorInterface *ioDescriptor,
8649 const struct audio_patch *patch,
8650 int delayMs)
8651{
8652 ssize_t index = mAudioPatches.indexOfKey(
8653 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8654 *patchHandle : ioDescriptor->getPatchHandle());
8655 sp<AudioPatch> patchDesc;
8656 status_t status = installPatch(
8657 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8658 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008659 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008660 }
8661 return status;
8662}
8663
8664status_t AudioPolicyManager::installPatch(const char *caller,
8665 ssize_t index,
8666 audio_patch_handle_t *patchHandle,
8667 const struct audio_patch *patch,
8668 int delayMs,
8669 uid_t uid,
8670 sp<AudioPatch> *patchDescPtr)
8671{
8672 sp<AudioPatch> patchDesc;
8673 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8674 if (index >= 0) {
8675 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008676 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008677 }
8678
8679 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8680 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8681 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8682 if (status == NO_ERROR) {
8683 if (index < 0) {
8684 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008685 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008686 } else {
8687 patchDesc->mPatch = *patch;
8688 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008689 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008690 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008691 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008692 }
8693 nextAudioPortGeneration();
8694 mpClientInterface->onAudioPatchListUpdate();
8695 }
8696 if (patchDescPtr) *patchDescPtr = patchDesc;
8697 return status;
8698}
8699
jiabinbce0c1d2020-10-05 11:20:18 -07008700bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8701{
8702 const TrackClientVector activeClients = output->getActiveClients();
8703 if (activeClients.empty()) {
8704 return true;
8705 }
8706 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8707 if (index < 0) {
8708 ALOGE("%s, no audio patch found while there are active clients on output %d",
8709 __func__, output->getId());
8710 return false;
8711 }
8712 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8713 DeviceVector routedDevices;
8714 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8715 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8716 patchDesc->mPatch.sinks[i].id);
8717 if (device == nullptr) {
8718 ALOGE("%s, no audio device found with id(%d)",
8719 __func__, patchDesc->mPatch.sinks[i].id);
8720 return false;
8721 }
8722 routedDevices.add(device);
8723 }
8724 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008725 if (client->isInvalid()) {
8726 // No need to take care about invalidated clients.
8727 continue;
8728 }
jiabinbce0c1d2020-10-05 11:20:18 -07008729 sp<DeviceDescriptor> preferredDevice =
8730 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8731 if (mEngine->getOutputDevicesForAttributes(
8732 client->attributes(), preferredDevice, false) == routedDevices) {
8733 return false;
8734 }
8735 }
8736 return true;
8737}
8738
8739sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008740 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008741 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8742 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008743{
8744 for (const auto& device : devices) {
8745 // TODO: This should be checking if the profile supports the device combo.
8746 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008747 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8748 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008749 return nullptr;
8750 }
8751 }
8752 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8753 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008754 status_t status = desc->open(halConfig, mixerConfig, devices,
8755 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008756 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008757 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008758 return nullptr;
8759 }
jiabin14b50cc2023-12-13 19:01:52 +00008760 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8761 auto portConfig = desc->getConfig();
8762 for (const auto& device : devices) {
8763 device->setPreferredConfig(&portConfig);
8764 }
8765 }
jiabinbce0c1d2020-10-05 11:20:18 -07008766
8767 // Here is where the out_set_parameters() for card & device gets called
8768 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8769 const audio_devices_t deviceType = device->type();
8770 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008771 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008772 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8773 mpClientInterface->setParameters(output, String8(param));
8774 free(param);
8775 }
jiabin12537fc2023-10-12 17:56:08 +00008776 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008777 if (!profile->hasValidAudioProfile()) {
8778 ALOGW("%s() missing param", __func__);
8779 desc->close();
8780 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008781 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8782 // Reopen the output with the best audio profile picked by APM when the profile supports
8783 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008784 desc->close();
8785 output = AUDIO_IO_HANDLE_NONE;
8786 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8787 profile->pickAudioProfile(
8788 config.sample_rate, config.channel_mask, config.format);
8789 config.offload_info.sample_rate = config.sample_rate;
8790 config.offload_info.channel_mask = config.channel_mask;
8791 config.offload_info.format = config.format;
8792
jiabina84c3d32022-12-02 18:59:55 +00008793 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008794 if (status != NO_ERROR) {
8795 return nullptr;
8796 }
8797 }
8798
8799 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008800 setOutputDevices(__func__, desc,
8801 devices,
8802 true,
8803 0,
8804 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008805 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8806 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8807
jiabinbce0c1d2020-10-05 11:20:18 -07008808 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8809 sp<AudioPolicyMix> policyMix;
8810 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8811 policyMix->setOutput(desc);
8812 desc->mPolicyMix = policyMix;
8813 } else {
8814 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008815 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008816 }
8817
baek.kim -61c20122022-07-27 10:05:32 +00008818 } else if (hasPrimaryOutput() && speaker != nullptr
8819 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008820 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8821 // no duplicated output for:
8822 // - direct outputs
8823 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008824 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008825 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8826
8827 //TODO: configure audio effect output stage here
8828
8829 // open a duplicating output thread for the new output and the primary output
8830 sp<SwAudioOutputDescriptor> dupOutputDesc =
8831 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8832 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8833 if (status == NO_ERROR) {
8834 // add duplicated output descriptor
8835 addOutput(duplicatedOutput, dupOutputDesc);
8836 } else {
8837 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8838 mPrimaryOutput->mIoHandle, output);
8839 desc->close();
8840 removeOutput(output);
8841 nextAudioPortGeneration();
8842 return nullptr;
8843 }
8844 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008845 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8846 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8847 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008848 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008849 }
jiabinbce0c1d2020-10-05 11:20:18 -07008850 return desc;
8851}
8852
jiabinf1c73972022-04-14 16:28:52 -07008853status_t AudioPolicyManager::getDevicesForAttributes(
8854 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8855 // Devices are determined in the following precedence:
8856 //
8857 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8858 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8859 //
8860 // If no such dynamic policy then
8861 // 2) Devices containing an active client using setPreferredDevice
8862 // with same strategy as the attributes.
8863 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8864 //
8865 // If no corresponding active client with setPreferredDevice then
8866 // 3) Devices associated with the strategy determined by the attributes
8867 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8868 //
8869 // See related getOutputForAttrInt().
8870
8871 // check dynamic policies but only for primary descriptors (secondary not used for audible
8872 // audio routing, only used for duplication for playback capture)
8873 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008874 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008875 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008876 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8877 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8878 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008879 if (status != OK) {
8880 return status;
8881 }
8882
8883 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8884 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8885 // as they are unaffected by device/stream volume
8886 // (per SwAudioOutputDescriptor::isFixedVolume()).
8887 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8888 ) {
8889 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8890 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8891 devices.add(deviceDesc);
8892 } else {
8893 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8894 // which selects setPreferredDevice if active. This means forVolume call
8895 // will take an active setPreferredDevice, if such exists.
8896
8897 devices = mEngine->getOutputDevicesForAttributes(
8898 attr, nullptr /* preferredDevice */, false /* fromCache */);
8899 }
8900
8901 if (forVolume) {
8902 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8903 // for single volume control in AudioService (such relationship should exist if
8904 // SPEAKER_SAFE is present).
8905 //
8906 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8907 DeviceVector speakerSafeDevices =
8908 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8909 if (!speakerSafeDevices.isEmpty()) {
8910 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8911 devices.remove(speakerSafeDevices);
8912 }
8913 }
8914
8915 return NO_ERROR;
8916}
8917
8918status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8919 AudioProfileVector& audioProfiles,
8920 uint32_t flags,
8921 bool isInput) {
8922 for (const auto& hwModule : mHwModules) {
8923 // the MSD module checks for different conditions
8924 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8925 continue;
8926 }
8927 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8928 : hwModule->getOutputProfiles();
8929 for (const auto& profile : ioProfiles) {
8930 if (!profile->areAllDevicesSupported(devices) ||
8931 !profile->isCompatibleProfileForFlags(
8932 flags, false /*exactMatchRequiredForInputFlags*/)) {
8933 continue;
8934 }
8935 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8936 }
8937 }
8938
8939 if (!isInput) {
8940 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8941 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8942 if (msdModule != nullptr) {
8943 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8944 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8945 for (const auto &profile: msdModule->getOutputProfiles()) {
8946 if (!profile->asAudioPort()->isDirectOutput()) {
8947 continue;
8948 }
8949 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8950 }
8951 } else {
8952 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8953 }
8954 }
8955 }
8956
8957 return NO_ERROR;
8958}
8959
jiabin3ff8d7d2022-12-13 06:27:44 +00008960sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8961 const audio_config_t *config,
8962 audio_output_flags_t flags,
8963 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008964 closeOutput(outputDesc->mIoHandle);
8965 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8966 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8967 if (preferredOutput == nullptr) {
8968 ALOGE("%s failed to reopen output device=%d, caller=%s",
8969 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008970 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008971 return preferredOutput;
8972}
8973
8974void AudioPolicyManager::reopenOutputsWithDevices(
8975 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8976 for (const auto& [output, devices] : outputsToReopen) {
8977 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8978 closeOutput(output);
8979 openOutputWithProfileAndDevice(desc->mProfile, devices);
8980 }
jiabina84c3d32022-12-02 18:59:55 +00008981}
8982
jiabinc44b3462022-12-08 12:52:31 -08008983PortHandleVector AudioPolicyManager::getClientsForStream(
8984 audio_stream_type_t streamType) const {
8985 PortHandleVector clients;
8986 for (size_t i = 0; i < mOutputs.size(); ++i) {
8987 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8988 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8989 }
8990 return clients;
8991}
8992
8993void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8994 PortHandleVector clients;
8995 for (auto stream : streams) {
8996 PortHandleVector clientsForStream = getClientsForStream(stream);
8997 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8998 }
8999 mpClientInterface->invalidateTracks(clients);
9000}
9001
jiabin220eea12024-05-17 17:55:20 +00009002void AudioPolicyManager::updateClientsInternalMute(
9003 const sp<android::SwAudioOutputDescriptor> &desc) {
9004 if (!desc->isBitPerfect() ||
9005 !com::android::media::audioserver::
9006 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9007 // This is only used for bit perfect output now.
9008 return;
9009 }
9010 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9011 bool bitPerfectClientInternalMute = false;
9012 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9013 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9014 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9015 bitPerfectClient = client;
9016 continue;
9017 }
9018 bool muted = false;
9019 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9020 // System sound is muted.
9021 muted = true;
9022 } else {
9023 bitPerfectClientInternalMute = true;
9024 }
9025 if (client->setInternalMute(muted)) {
9026 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9027 if (!result.ok()) {
9028 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9029 continue;
9030 }
9031 media::TrackInternalMuteInfo info;
9032 info.portId = result.value();
9033 info.muted = client->getInternalMute();
9034 clientsInternalMute.push_back(std::move(info));
9035 }
9036 }
9037 if (bitPerfectClient != nullptr &&
9038 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9039 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9040 if (result.ok()) {
9041 media::TrackInternalMuteInfo info;
9042 info.portId = result.value();
9043 info.muted = bitPerfectClient->getInternalMute();
9044 clientsInternalMute.push_back(std::move(info));
9045 } else {
9046 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9047 __func__, bitPerfectClient->portId());
9048 }
9049 }
9050 if (!clientsInternalMute.empty()) {
9051 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9052 status != NO_ERROR) {
9053 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9054 }
9055 }
9056}
9057
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009058} // namespace android