blob: a39e0832ae2fe935afbc3302c0a7cef8a96aeb3e [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;
812 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
813 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
814 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200815 ALOGE_IF(mCallRxSourceClient == nullptr,
816 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200817}
818
Francois Gaffie601801d2021-06-22 13:27:39 +0200819void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 if (clientDesc == nullptr) {
822 return;
823 }
824 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
825 "%s error stopping audio source", __func__);
826 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200827}
828
829void AudioPolicyManager::connectTelephonyTxAudioSource(
830 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
831 uint32_t delayMs)
832{
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200834 if (srcDevice == nullptr || sinkDevice == nullptr) {
835 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
836 return;
837 }
838 PatchBuilder patchBuilder;
839 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
840 ALOGV("%s between source %s and sink %s", __func__,
841 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200843 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
844
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200845 struct audio_port_config source = {};
846 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100847 mCallTxSourceClient = new SourceClientDescriptor(
848 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
849 mCommunnicationStrategy, toVolumeSource(aa), true);
850 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
851
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
853 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
855 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200856 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
857 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200858 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200859 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200860}
861
Eric Laurente0720872014-03-11 09:30:41 -0700862void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700863{
864 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100865 // store previous phone state for management of sonification strategy below
866 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100867 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100868
869 if (mEngine->setPhoneState(state) != NO_ERROR) {
870 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700871 return;
872 }
François Gaffie2110e042015-03-24 08:41:51 +0100873 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700874 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700875 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700876 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800877 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700878 }
879
François Gaffie2110e042015-03-24 08:41:51 +0100880 /**
881 * Switching to or from incall state or switching between telephony and VoIP lead to force
882 * routing command.
883 */
Eric Laurent74b71512019-11-06 17:21:57 -0800884 bool force = ((isStateInCall(oldState) != isStateInCall(state))
885 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700886
887 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700888 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 int delayMs = 0;
891 if (isStateInCall(state)) {
892 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100893 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
894 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700896 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 // mute media and sonification strategies and delay device switch by the largest
898 // latency of any output where either strategy is active.
899 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100900 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
901 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
902 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 (delayMs < (int)desc->latency()*2)) {
904 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700905 }
François Gaffiec005e562018-11-06 15:04:49 +0100906 setStrategyMute(musicStrategy, true, desc);
907 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
908 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
909 nullptr, true /*fromCache*/).types());
910 setStrategyMute(sonificationStrategy, true, desc);
911 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
912 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
913 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700914 }
915 }
916
François Gaffiedb1755b2023-09-01 11:50:35 +0200917 if (state == AUDIO_MODE_IN_CALL) {
918 (void)updateCallRouting(false /*fromCache*/, delayMs);
919 } else {
920 if (oldState == AUDIO_MODE_IN_CALL) {
921 disconnectTelephonyAudioSource(mCallRxSourceClient);
922 disconnectTelephonyAudioSource(mCallTxSourceClient);
923 }
924 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100925 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
926 // force routing command to audio hardware when ending call
927 // even if no device change is needed
928 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
929 rxDevices = mPrimaryOutput->devices();
930 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530931 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700932 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700933 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700934
jiabin3ff8d7d2022-12-13 06:27:44 +0000935 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700936 // reevaluate routing on all outputs in case tracks have been started during the call
937 for (size_t i = 0; i < mOutputs.size(); i++) {
938 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100939 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000940 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
941 && desc->mPreferredAttrInfo != nullptr) {
942 // If the output is using preferred mixer attributes and the audio mode is not normal,
943 // the output need to reopen with default configuration.
944 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
945 continue;
946 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200947 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
948 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530949 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200950 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700951 }
952 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000953 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700954
Eric Laurent96d1dda2022-03-14 17:14:19 +0100955 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
956
Eric Laurente552edb2014-03-10 17:42:56 -0700957 if (isStateInCall(state)) {
958 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700959 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800960 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962
963 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100964 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
965 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700966}
967
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700968audio_mode_t AudioPolicyManager::getPhoneState() {
969 return mEngine->getPhoneState();
970}
971
Eric Laurente0720872014-03-11 09:30:41 -0700972void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100973 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700974{
François Gaffie2110e042015-03-24 08:41:51 +0100975 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700976 if (config == mEngine->getForceUse(usage)) {
977 return;
978 }
Eric Laurente552edb2014-03-10 17:42:56 -0700979
François Gaffie2110e042015-03-24 08:41:51 +0100980 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
981 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
982 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700983 }
François Gaffie2110e042015-03-24 08:41:51 +0100984 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
985 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
986 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700987
988 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700989 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800990
Eric Laurent22fcda22019-05-17 16:28:47 -0700991 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
992 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800993 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700994 }
995
Eric Laurentdc462862016-07-19 12:29:53 -0700996 //FIXME: workaround for truncated touch sounds
997 // to be removed when the problem is handled by system UI
998 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700999 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1000 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1001 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001002
1003 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001004 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001005}
1006
Eric Laurente0720872014-03-11 09:30:41 -07001007void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001008{
1009 ALOGV("setSystemProperty() property %s, value %s", property, value);
1010}
1011
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012// Find an MSD output profile compatible with the parameters passed.
1013// When "directOnly" is set, restrict search to profiles for direct outputs.
1014sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1015 const DeviceVector& devices,
1016 uint32_t samplingRate,
1017 audio_format_t format,
1018 audio_channel_mask_t channelMask,
1019 audio_output_flags_t flags,
1020 bool directOnly)
1021{
1022 flags = getRelevantFlags(flags, directOnly);
1023
1024 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1025 if (msdModule != nullptr) {
1026 // for the msd module check if there are patches to the output devices
1027 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1028 HwModuleCollection modules;
1029 modules.add(msdModule);
1030 return searchCompatibleProfileHwModules(
1031 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1032 flags, directOnly);
1033 }
1034 }
1035 return nullptr;
1036}
1037
Michael Chana94fbb22018-04-24 14:31:19 +10001038// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1039// search to profiles for direct outputs.
1040sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001041 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001042 uint32_t samplingRate,
1043 audio_format_t format,
1044 audio_channel_mask_t channelMask,
1045 audio_output_flags_t flags,
1046 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001047{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001048 flags = getRelevantFlags(flags, directOnly);
1049
1050 return searchCompatibleProfileHwModules(
1051 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1052}
1053
1054audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1055 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001056 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 // only retain flags that will drive the direct output profile selection
1058 // if explicitly requested
1059 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001060 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001061 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1062 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001063 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001064 return flags;
1065}
Eric Laurent861a6282015-05-18 15:40:16 -07001066
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1068 const HwModuleCollection& hwModules,
1069 const DeviceVector& devices,
1070 uint32_t samplingRate,
1071 audio_format_t format,
1072 audio_channel_mask_t channelMask,
1073 audio_output_flags_t flags,
1074 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001075 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001076 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001077 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001078 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 samplingRate, NULL /*updatedSamplingRate*/,
1080 format, NULL /*updatedFormat*/,
1081 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001082 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001083 continue;
1084 }
1085 // reject profiles not corresponding to a device currently available
1086 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1087 continue;
1088 }
1089 // reject profiles if connected device does not support codec
1090 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1091 continue;
1092 }
1093 if (!directOnly) {
1094 return curProfile;
1095 }
1096
1097 // when searching for direct outputs, if several profiles are compatible, give priority
1098 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001099 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001100 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001101 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001102 }
1103 profile = curProfile;
1104 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1105 break;
1106 }
Eric Laurente552edb2014-03-10 17:42:56 -07001107 }
1108 }
Eric Laurent861a6282015-05-18 15:40:16 -07001109 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001110}
1111
Eric Laurentfa0f6742021-08-17 18:39:44 +02001112sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001113 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114{
1115 for (const auto& hwModule : mHwModules) {
1116 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001117 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001118 continue;
1119 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001121 // reject profiles not corresponding to a device currently available
1122 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1123 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1124 continue;
1125 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001126 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1127 != devices.size()) {
1128 continue;
1129 }
1130 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001131 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1132 return curProfile;
1133 }
1134 }
1135 return nullptr;
1136}
1137
Eric Laurentf4e63452017-11-06 19:31:46 +00001138audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001139{
François Gaffiec005e562018-11-06 15:04:49 +01001140 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001141
1142 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1143 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1144 // format, flags, etc. This may result in some discrepancy for functions that utilize
1145 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1146 // and AudioSystem::getOutputSamplingRate().
1147
François Gaffie11d30102018-11-02 16:09:09 +01001148 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001149 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1150 if (stream == AUDIO_STREAM_MUSIC &&
1151 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1152 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1153 }
1154 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001155
François Gaffie11d30102018-11-02 16:09:09 +01001156 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1157 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001158 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001159}
1160
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1162 const audio_attributes_t *srcAttr,
1163 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001164{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001165 if (srcAttr != NULL) {
1166 if (!isValidAttributes(srcAttr)) {
1167 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1168 __func__,
1169 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1170 srcAttr->tags);
1171 return BAD_VALUE;
1172 }
1173 *dstAttr = *srcAttr;
1174 } else {
1175 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1176 ALOGE("%s: invalid stream type", __func__);
1177 return BAD_VALUE;
1178 }
François Gaffiec005e562018-11-06 15:04:49 +01001179 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001180 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001181
1182 // Only honor audibility enforced when required. The client will be
1183 // forced to reconnect if the forced usage changes.
1184 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001185 dstAttr->flags = static_cast<audio_flags_mask_t>(
1186 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001187 }
1188
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001189 return NO_ERROR;
1190}
1191
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192status_t AudioPolicyManager::getOutputForAttrInt(
1193 audio_attributes_t *resultAttr,
1194 audio_io_handle_t *output,
1195 audio_session_t session,
1196 const audio_attributes_t *attr,
1197 audio_stream_type_t *stream,
1198 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001199 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 audio_output_flags_t *flags,
1201 audio_port_handle_t *selectedDeviceId,
1202 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001204 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001205 bool *isSpatialized,
1206 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207{
François Gaffiec005e562018-11-06 15:04:49 +01001208 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001209 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001210 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001211 const sp<DeviceDescriptor> requestedDevice =
1212 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1213
Eric Laurent8a1095a2019-11-08 14:44:16 -08001214 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001215 *isSpatialized = false;
1216
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001217 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1218 if (status != NO_ERROR) {
1219 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001220 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001221 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001222 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001223 }
François Gaffiec005e562018-11-06 15:04:49 +01001224 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001225
François Gaffiec005e562018-11-06 15:04:49 +01001226 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1227 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001228
Oscar Azucena873d10f2023-01-12 18:34:42 -08001229 bool usePrimaryOutputFromPolicyMixes = false;
1230
Kevin Rocard153f92d2018-12-18 18:33:28 -08001231 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1232 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1233 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001235 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1236 .channel_mask = config->channel_mask,
1237 .format = config->format,
1238 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001239 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001240 mAvailableOutputDevices, requestedDevice, primaryMix,
1241 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001242 if (status != OK) {
1243 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001244 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001245
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001247 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1248 && !audio_is_linear_pcm(config->format)) {
1249 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 return BAD_VALUE;
1251 }
1252 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001253 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1255 primaryMix->mDeviceAddress,
1256 AUDIO_FORMAT_DEFAULT);
1257 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001258 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001259 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1260 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001261 // if a direct output can be opened to deliver the track's multi-channel content to the
1262 // output rather than being downmixed by the primary output, then use this direct
1263 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1264 // mix.
1265 bool tryDirectForChannelMask = policyDesc != nullptr
1266 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1267 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001268 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 audio_io_handle_t newOutput;
1270 status = openDirectOutput(
1271 *stream, session, config,
1272 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001273 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001274 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001275 policyDesc = mOutputs.valueFor(newOutput);
1276 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001277 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001278 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001279 policyDesc = nullptr;
1280 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 }
1282 if (policyDesc != nullptr) {
1283 policyDesc->mPolicyMix = primaryMix;
1284 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001285 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1286 : AUDIO_PORT_HANDLE_NONE;
1287 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1288 // Remove direct flag as it is not on a direct output.
1289 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1290 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001291
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001292 ALOGV("getOutputForAttr() returns output %d", *output);
1293 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1294 *outputType = API_OUT_MIX_PLAYBACK;
1295 } else {
1296 *outputType = API_OUTPUT_LEGACY;
1297 }
1298 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001299 } else {
1300 if (policyMixDevice != nullptr) {
1301 ALOGE("%s, try to use primary mix but no output found", __func__);
1302 return INVALID_OPERATION;
1303 }
1304 // Fallback to default engine selection as the selected primary mix device is not
1305 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001306 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001307 }
François Gaffiec005e562018-11-06 15:04:49 +01001308 // Virtual sources must always be dynamicaly or explicitly routed
1309 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1310 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1311 return BAD_VALUE;
1312 }
1313 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1314 // in order to let the choice of the order to future vendor engine
1315 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001316
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001317 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001318 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001319 }
1320
Nadav Barb2f18162018-07-18 13:01:53 +03001321 // Set incall music only if device was explicitly set, and fallback to the device which is
1322 // chosen by the engine if not.
1323 // FIXME: provide a more generic approach which is not device specific and move this back
1324 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001325 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001326 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001327 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001328 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001329 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001330 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001331 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001332 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001333 }
1334 }
1335
François Gaffiec005e562018-11-06 15:04:49 +01001336 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1337 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1338 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001339
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001340 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001341 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001342 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001343 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001344 ALOGV("%s() Using MSD devices %s instead of devices %s",
1345 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 } else {
1347 *output = AUDIO_IO_HANDLE_NONE;
1348 }
1349 }
1350 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001351 sp<PreferredMixerAttributesInfo> info = nullptr;
1352 if (outputDevices.size() == 1) {
1353 info = getPreferredMixerAttributesInfo(
1354 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001355 mEngine->getProductStrategyForAttributes(*resultAttr),
1356 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001357 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1358 // and it is currently active.
1359 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001360 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001361 info = nullptr;
1362 }
jiabin220eea12024-05-17 17:55:20 +00001363 if (com::android::media::audioserver::
1364 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1365 if (info != nullptr && info->getUid() == uid &&
1366 info->configMatches(*config) &&
1367 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1368 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1369 [this, &outputDevices](audio_usage_t usage) {
1370 return mOutputs.isUsageActiveOnDevice(
1371 usage, outputDevices[0]); }))) {
1372 // Bit-perfect request is not allowed when the phone mode is not normal or
1373 // there is any higher priority user case active.
1374 return INVALID_OPERATION;
1375 }
1376 }
jiabina84c3d32022-12-02 18:59:55 +00001377 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001378 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001379 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001380 // The client will be active if the client is currently preferred mixer owner and the
1381 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001382 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001383 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001384 && info->getUid() == uid
1385 && *output != AUDIO_IO_HANDLE_NONE
1386 // When bit-perfect output is selected for the preferred mixer attributes owner,
1387 // only need to consider the config matches.
1388 && mOutputs.valueFor(*output)->isConfigurationMatched(
1389 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001390
1391 if (*isBitPerfect) {
1392 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1393 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001395 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001396 AudioProfileVector profiles;
1397 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1398 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001399 const auto channels = profiles[0]->getChannels();
1400 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1401 config->channel_mask = *channels.begin();
1402 }
1403 const auto sampleRates = profiles[0]->getSampleRates();
1404 if (!sampleRates.empty() &&
1405 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1406 config->sample_rate = *sampleRates.begin();
1407 }
jiabinf1c73972022-04-14 16:28:52 -07001408 config->format = profiles[0]->getFormat();
1409 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001410 return INVALID_OPERATION;
1411 }
Paul McLeanaa981192015-03-21 09:55:15 -07001412
François Gaffiec005e562018-11-06 15:04:49 +01001413 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001414 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001415 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001416 *selectedDeviceId = outputDevice->getId();
1417 break;
1418 }
1419 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001420
Eric Laurent8a1095a2019-11-08 14:44:16 -08001421 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1422 *outputType = API_OUTPUT_TELEPHONY_TX;
1423 } else {
1424 *outputType = API_OUTPUT_LEGACY;
1425 }
1426
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1428
1429 return NO_ERROR;
1430}
1431
1432status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1433 audio_io_handle_t *output,
1434 audio_session_t session,
1435 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001436 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001437 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001438 audio_output_flags_t *flags,
1439 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001440 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001441 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001442 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001443 bool *isSpatialized,
1444 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001445{
1446 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1447 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1448 return INVALID_OPERATION;
1449 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001450 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001451 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001452 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001454 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001455 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001456 const sp<DeviceDescriptor> requestedDevice =
1457 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1458
1459 // Prevent from storing invalid requested device id in clients
1460 const audio_port_handle_t sanitizedRequestedPortId =
1461 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1462 *selectedDeviceId = sanitizedRequestedPortId;
1463
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001465 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001466 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1467 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001468 if (status != NO_ERROR) {
1469 return status;
1470 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001471 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001472 if (secondaryOutputs != nullptr) {
1473 for (auto &secondaryMix : secondaryMixes) {
1474 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1475 if (outputDesc != nullptr &&
1476 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1477 secondaryOutputs->push_back(outputDesc->mIoHandle);
1478 weakSecondaryOutputDescs.push_back(outputDesc);
1479 }
1480 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001481 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001482
Eric Laurent8fc147b2018-07-22 19:13:55 -07001483 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001484 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001485 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001486 };
jiabin4ef93452019-09-10 14:29:54 -07001487 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001488
Eric Laurentc209fe42020-06-05 18:11:23 -07001489 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001490 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001491 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001492 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001493 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001494 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001495 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001496 std::move(weakSecondaryOutputDescs),
1497 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001498 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001499
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001500 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1501 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001502
Eric Laurente83b55d2014-11-14 10:06:21 -08001503 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001504}
1505
Eric Laurentc529cf62020-04-17 18:19:10 -07001506status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1507 audio_session_t session,
1508 const audio_config_t *config,
1509 audio_output_flags_t flags,
1510 const DeviceVector &devices,
1511 audio_io_handle_t *output) {
1512
1513 *output = AUDIO_IO_HANDLE_NONE;
1514
1515 // skip direct output selection if the request can obviously be attached to a mixed output
1516 // and not explicitly requested
1517 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1518 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1519 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1520 return NAME_NOT_FOUND;
1521 }
1522
1523 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1524 // This prevents creating an offloaded track and tearing it down immediately after start
1525 // when audioflinger detects there is an active non offloadable effect.
1526 // FIXME: We should check the audio session here but we do not have it in this context.
1527 // This may prevent offloading in rare situations where effects are left active by apps
1528 // in the background.
1529 sp<IOProfile> profile;
1530 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1531 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1532 profile = getProfileForOutput(
1533 devices, config->sample_rate, config->format, config->channel_mask,
1534 flags, true /* directOnly */);
1535 }
1536
1537 if (profile == nullptr) {
1538 return NAME_NOT_FOUND;
1539 }
1540
1541 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1542 for (size_t i = 0; i < mOutputs.size(); i++) {
1543 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1544 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1545 // reuse direct output if currently open by the same client
1546 // and configured with same parameters
1547 if ((config->sample_rate == desc->getSamplingRate()) &&
1548 (config->format == desc->getFormat()) &&
1549 (config->channel_mask == desc->getChannelMask()) &&
1550 (session == desc->mDirectClientSession)) {
1551 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001552 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001553 mOutputs.keyAt(i), session);
1554 *output = mOutputs.keyAt(i);
1555 return NO_ERROR;
1556 }
1557 }
1558 }
1559
1560 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001561 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1562 return NAME_NOT_FOUND;
1563 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1564 // MMAP gracefully handles lack of an exclusive track resource by mixing
1565 // above the audio framework. For AAudio to know that the limit is reached,
1566 // return an error.
1567 return NAME_NOT_FOUND;
1568 } else {
1569 // Close outputs on this profile, if available, to free resources for this request
1570 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1571 const auto desc = mOutputs.valueAt(i);
1572 if (desc->mProfile == profile) {
1573 closeOutput(desc->mIoHandle);
1574 }
1575 }
1576 }
1577 }
1578
1579 // Unable to close streams to find free resources for this request
1580 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001581 return NAME_NOT_FOUND;
1582 }
1583
Atneya Nairb16666a2023-12-11 20:18:33 -08001584 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001585
Michael Chan6fb34492020-12-08 15:44:49 +11001586 // An MSD patch may be using the only output stream that can service this request. Release
1587 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001588 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001589
Eric Laurentf1f22e72021-07-13 14:04:14 +02001590 status_t status =
1591 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001592
1593 // only accept an output with the requested parameters
1594 if (status != NO_ERROR ||
1595 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1596 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1597 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1598 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1599 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1600 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1601 config->channel_mask, outputDesc->getChannelMask());
1602 if (*output != AUDIO_IO_HANDLE_NONE) {
1603 outputDesc->close();
1604 }
1605 // fall back to mixer output if possible when the direct output could not be open
1606 if (audio_is_linear_pcm(config->format) &&
1607 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1608 return NAME_NOT_FOUND;
1609 }
1610 *output = AUDIO_IO_HANDLE_NONE;
1611 return BAD_VALUE;
1612 }
1613 outputDesc->mDirectOpenCount = 1;
1614 outputDesc->mDirectClientSession = session;
1615
1616 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001617 setOutputDevices(__func__, outputDesc,
1618 devices,
1619 true,
1620 0,
1621 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001622 mPreviousOutputs = mOutputs;
1623 ALOGV("%s returns new direct output %d", __func__, *output);
1624 mpClientInterface->onAudioPortListUpdate();
1625 return NO_ERROR;
1626}
1627
François Gaffie11d30102018-11-02 16:09:09 +01001628audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1629 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001630 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001631 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001632 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001633 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001634 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001635 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001636 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001637{
Andy Hungc88b0642018-04-27 15:42:35 -07001638 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001639
jiabine375d412019-02-26 12:54:53 -08001640 // Discard haptic channel mask when forcing muting haptic channels.
1641 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001642 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1643 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001644
Eric Laurente552edb2014-03-10 17:42:56 -07001645 // open a direct output if required by specified parameters
1646 //force direct flag if offload flag is set: offloading implies a direct output stream
1647 // and all common behaviors are driven by checking only the direct flag
1648 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001649 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1650 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001651 }
Nadav Bar766fb022018-01-07 12:18:03 +02001652 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1653 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001654 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001655
1656 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1657
Eric Laurente83b55d2014-11-14 10:06:21 -08001658 // only allow deep buffering for music stream type
1659 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001660 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001661 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001662 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001663 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1664 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001665 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001666 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001667 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001668 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001669 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001670 audio_is_linear_pcm(config->format) &&
1671 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001672 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001673 AUDIO_OUTPUT_FLAG_DIRECT);
1674 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001675 }
Eric Laurente552edb2014-03-10 17:42:56 -07001676
Carter Hsua3abb402021-10-26 11:11:20 +08001677 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1678 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1679 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1680 }
1681
Eric Laurentf9230d52024-01-26 18:49:09 +01001682 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001683 // was specified and offload or direct playback is not explicitly requested, and there is no
1684 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001685 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001686 if (mSpatializerOutput != nullptr &&
1687 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1688 prefMixerConfigInfo == nullptr &&
1689 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1690 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001691 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001692 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001693 }
1694
Eric Laurentc529cf62020-04-17 18:19:10 -07001695 audio_config_t directConfig = *config;
1696 directConfig.channel_mask = channelMask;
1697 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1698 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001699 return output;
1700 }
1701
Eric Laurent14cbfca2016-03-17 09:42:16 -07001702 // A request for HW A/V sync cannot fallback to a mixed output because time
1703 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001704 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001705 return AUDIO_IO_HANDLE_NONE;
1706 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001707 // A request for Tuner cannot fallback to a mixed output
1708 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1709 return AUDIO_IO_HANDLE_NONE;
1710 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001711
Eric Laurente552edb2014-03-10 17:42:56 -07001712 // ignoring channel mask due to downmix capability in mixer
1713
1714 // open a non direct output
1715
1716 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001717 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001718 // get which output is suitable for the specified stream. The actual
1719 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001720 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001721 if (prefMixerConfigInfo != nullptr) {
1722 for (audio_io_handle_t outputHandle : outputs) {
1723 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1724 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1725 output = outputHandle;
1726 break;
1727 }
1728 }
1729 if (output == AUDIO_IO_HANDLE_NONE) {
1730 // No output open with the preferred profile. Open a new one.
1731 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1732 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1733 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1734 config.format = prefMixerConfigInfo->getConfigBase().format;
1735 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1736 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1737 &config, prefMixerConfigInfo->getFlags());
1738 if (preferredOutput == nullptr) {
1739 ALOGE("%s failed to open output with preferred mixer config", __func__);
1740 } else {
1741 output = preferredOutput->mIoHandle;
1742 }
1743 }
1744 } else {
1745 // at this stage we should ignore the DIRECT flag as no direct output could be
1746 // found earlier
1747 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001748 if (com::android::media::audioserver::
1749 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1750 // If the preferred mixer attributes is null, do not select the bit-perfect output
1751 // unless the bit-perfect output is the only output.
1752 // The bit-perfect output can exist while the passed in preferred mixer attributes
1753 // info is null when it is a high priority client. The high priority clients are
1754 // ringtone or alarm, which is not a bit-perfect use case.
1755 size_t i = 0;
1756 while (i < outputs.size() && outputs.size() > 1) {
1757 auto desc = mOutputs.valueFor(outputs[i]);
1758 // The output descriptor must not be null here.
1759 if (desc->isBitPerfect()) {
1760 outputs.removeItemsAt(i);
1761 } else {
1762 i += 1;
1763 }
1764 }
1765 }
jiabina84c3d32022-12-02 18:59:55 +00001766 output = selectOutput(
1767 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1768 }
Eric Laurente552edb2014-03-10 17:42:56 -07001769 }
François Gaffie11d30102018-11-02 16:09:09 +01001770 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001771 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001772 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001773
Eric Laurente552edb2014-03-10 17:42:56 -07001774 return output;
1775}
1776
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001777sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001778 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1779 mAvailableInputDevices);
1780 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1781}
1782
1783DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1784 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1785 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786}
1787
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001789 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001790 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1791 if (msdModule != 0) {
1792 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1793 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1794 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1795 const struct audio_port_config *source = &patch->mPatch.sources[j];
1796 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1797 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001798 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001799 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
1801 }
1802 }
1803 return msdPatches;
1804}
1805
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001806bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1807 ssize_t index = mAudioPatches.indexOfKey(handle);
1808 if (index < 0) {
1809 return false;
1810 }
1811 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1812 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1813 if (msdModule == nullptr) {
1814 return false;
1815 }
1816 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1817 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1818 return true;
1819 }
1820 index = getMsdOutputPatches().indexOfKey(handle);
1821 if (index < 0) {
1822 return false;
1823 }
1824 return true;
1825}
1826
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1828 const InputProfileCollection &inputProfiles,
1829 const OutputProfileCollection &outputProfiles,
1830 const sp<DeviceDescriptor> &sourceDevice,
1831 const sp<DeviceDescriptor> &sinkDevice,
1832 AudioProfileVector& sourceProfiles,
1833 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001834 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 return NO_INIT;
1837 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 return NO_INIT;
1841 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1844 inProfile->supportsDevice(sourceDevice)) {
1845 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001846 }
1847 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001849 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850 outProfile->supportsDevice(sinkDevice)) {
1851 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 }
1853 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 return NO_ERROR;
1855}
1856
1857status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1858 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1859 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1860{
Dean Wheatley16809da2022-12-09 14:55:46 +11001861 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1862 static const std::vector<audio_format_t> formatsOrder = {{
1863 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001864 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1865 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001866 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1867 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1868 // preferred).
1869 std::vector<audio_channel_mask_t> masks = {{
1870 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1871 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1872 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1873 // insert index masks (higher counts most preferred) as preferred over position masks
1874 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1875 masks.insert(
1876 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1877 }
1878 return masks;
1879 }();
1880
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001882 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1883 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1886 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001887 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 }
1889 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1890 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1891 sinkConfig->format = bestSinkConfig.format;
1892 // For encoded streams force direct flag to prevent downstream mixing.
1893 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1894 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001895 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1896 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001898 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1899 // raw and IEC61937 framed streams.
1900 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1901 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1902 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1904 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001905 sourceConfig->channel_mask =
1906 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1907 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1908 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001909 sourceConfig->format = bestSinkConfig.format;
1910 // Copy input stream directly without any processing (e.g. resampling).
1911 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1912 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1913 if (hwAvSync) {
1914 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1915 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1916 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1917 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1918 }
1919 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1920 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1921 sinkConfig->config_mask |= config_mask;
1922 sourceConfig->config_mask |= config_mask;
1923 return NO_ERROR;
1924}
1925
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1927 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001928{
1929 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001930 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1931 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1932 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1933 if (deviceModule == nullptr) {
1934 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1935 return patchBuilder;
1936 }
1937 const InputProfileCollection inputProfiles = msdIsSource ?
1938 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1939 const OutputProfileCollection outputProfiles = msdIsSource ?
1940 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1941
1942 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1943 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1944 device : getMsdAudioOutDevices().itemAt(0);
1945 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1946
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1948 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 AudioProfileVector sourceProfiles;
1950 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1952 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 for (auto hwAvSync : { true, false }) {
1954 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1955 sourceProfiles, sinkProfiles) != NO_ERROR) {
1956 continue;
1957 }
1958 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1959 &sinkConfig) == NO_ERROR) {
1960 // Found a matching config. Re-create PatchBuilder with this config.
1961 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001964 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001965 " supporting PCM format conversion.", __func__);
1966 return patchBuilder;
1967}
1968
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001970 DeviceVector devices;
1971 if (outputDevices != nullptr && outputDevices->size() > 0) {
1972 devices.add(*outputDevices);
1973 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001974 // Use media strategy for unspecified output device. This should only
1975 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1976 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001977 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001978 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001979 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001980 }
Michael Chan6fb34492020-12-08 15:44:49 +11001981 std::vector<PatchBuilder> patchesToCreate;
1982 for (auto i = 0u; i < devices.size(); ++i) {
1983 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001984 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001985 }
1986 // Retain only the MSD patches associated with outputDevices request.
1987 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001988 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001989 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1990 auto retainedPatch = false;
1991 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1992 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1993 patchesToRemove.removeItemsAt(i);
1994 retainedPatch = true;
1995 break;
1996 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001997 }
Michael Chan6fb34492020-12-08 15:44:49 +11001998 if (retainedPatch) {
1999 it = patchesToCreate.erase(it);
2000 continue;
2001 }
2002 ++it;
2003 }
2004 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2005 return NO_ERROR;
2006 }
2007 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2008 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002009 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 }
Michael Chan6fb34492020-12-08 15:44:49 +11002011 status_t status = NO_ERROR;
2012 for (const auto &p : patchesToCreate) {
2013 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2014 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2015 char message[256];
2016 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2017 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2018 currStatus == NO_ERROR ? "Success" : "Error",
2019 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2020 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2021 if (currStatus == NO_ERROR) {
2022 ALOGD("%s", message);
2023 } else {
2024 ALOGE("%s", message);
2025 if (status == NO_ERROR) {
2026 status = currStatus;
2027 }
2028 }
2029 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002030 return status;
2031}
2032
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002033void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2034 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002035 for (size_t i = 0; i < msdPatches.size(); i++) {
2036 const auto& patch = msdPatches[i];
2037 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2038 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2039 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2040 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2041 releaseAudioPatch(patch->getHandle(), mUidCached);
2042 break;
2043 }
2044 }
2045 }
2046}
2047
Dorin Drimus94d94412022-02-02 09:05:02 +01002048bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002049 DeviceVector devicesToCheck =
2050 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002051 AudioPatchCollection msdPatches = getMsdOutputPatches();
2052 for (size_t i = 0; i < msdPatches.size(); i++) {
2053 const auto& patch = msdPatches[i];
2054 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2055 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2056 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2057 const auto& foundDevice = devicesToCheck.getDevice(
2058 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2059 if (foundDevice != nullptr) {
2060 devicesToCheck.remove(foundDevice);
2061 if (devicesToCheck.isEmpty()) {
2062 return true;
2063 }
2064 }
2065 }
2066 }
2067 }
2068 return false;
2069}
2070
Eric Laurente0720872014-03-11 09:30:41 -07002071audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002072 audio_output_flags_t flags,
2073 audio_format_t format,
2074 audio_channel_mask_t channelMask,
2075 uint32_t samplingRate,
2076 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002077{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2079 "%s called with format %#x", __func__, format);
2080
jiabinebb6af42020-06-09 17:31:17 -07002081 // Return the output that haptic-generating attached to when 1) session id is specified,
2082 // 2) haptic-generating effect exists for given session id and 3) the output that
2083 // haptic-generating effect attached to is in given outputs.
2084 if (sessionId != AUDIO_SESSION_NONE) {
2085 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2086 sessionId, FX_IID_HAPTICGENERATOR);
2087 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2088 return hapticGeneratingOutput;
2089 }
2090 }
2091
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 // Flags disqualifying an output: the match must happen before calling selectOutput()
2093 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2094 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2095
2096 // Flags expressing a functional request: must be honored in priority over
2097 // other criteria
2098 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2099 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002100 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2101 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 // Flags expressing a performance request: have lower priority than serving
2103 // requested sampling rate or channel mask
2104 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2105 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2106 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2107
2108 const audio_output_flags_t functionalFlags =
2109 (audio_output_flags_t)(flags & kFunctionalFlags);
2110 const audio_output_flags_t performanceFlags =
2111 (audio_output_flags_t)(flags & kPerformanceFlags);
2112
2113 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2114
Eric Laurente552edb2014-03-10 17:42:56 -07002115 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002116 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002117 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002118 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002119 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002120 // with tiebreak preferring the minimum number of extra functional flags
2121 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002122 // 3: the output supporting the exact channel mask
2123 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002124 // 5: the output with the highest sampling rate if the requested sample rate is
2125 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 // 6: the output with the highest number of requested performance flags
2127 // 7: the output with the bit depth the closest to the requested one
2128 // 8: the primary output
2129 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002130
Eric Laurent16c66dd2019-05-01 17:54:10 -07002131 // matching criteria values in priority order for best matching output so far
2132 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002134 const bool hasOrphanHaptic =
2135 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002136 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2137 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2138 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002139
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002140 for (audio_io_handle_t output : outputs) {
2141 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002142 // matching criteria values in priority order for current output
2143 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002144
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 if (outputDesc->isDuplicated()) {
2146 continue;
2147 }
2148 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2149 continue;
2150 }
Eric Laurent8838a382014-09-08 16:44:28 -07002151
Eric Laurent16c66dd2019-05-01 17:54:10 -07002152 // If haptic channel is specified, use the haptic output if present.
2153 // When using haptic output, same audio format and sample rate are required.
2154 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002155 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002156 // skip if haptic channel specified but output does not support it, or output support haptic
2157 // but there is no haptic channel requested AND no orphan haptic effect exist
2158 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2159 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002160 continue;
2161 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002162 // In the case of audio-coupled-haptic playback, there is no format conversion and
2163 // resampling in the framework, same format/channel/sampleRate for client and the output
2164 // thread is required. In the case of HapticGenerator effect, do not require format
2165 // matching.
2166 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2167 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002168 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002169 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 }
2171
2172 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002173 const int matchingFunctionalFlags =
2174 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2175 const int totalFunctionalFlags =
2176 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2177 // Prefer matching functional flags, but subtract unnecessary functional flags.
2178 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179
2180 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002181 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2182 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2184 channelCount <= outputChannelCount) {
2185 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002186 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2187 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002189 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 currentMatchCriteria[3] = outputChannelCount;
2191 }
2192
2193 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002194 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002195 int diff; // avoid unsigned integer overflow.
2196 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2197
2198 // prefer the closest output sampling rate greater than or equal to target
2199 // if none exists, prefer the closest output sampling rate less than target.
2200 //
2201 // criteria is offset to make non-negative.
2202 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 }
2204
2205 // performance flags match
2206 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2207
2208 // format match
2209 if (format != AUDIO_FORMAT_INVALID) {
2210 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002211 PolicyAudioPort::kFormatDistanceMax -
2212 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 }
2214
2215 // primary output match
2216 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2217
2218 // compare match criteria by priority then value
2219 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2220 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2221 bestMatchCriteria = currentMatchCriteria;
2222 bestOutput = output;
2223
2224 std::stringstream result;
2225 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2226 std::ostream_iterator<int>(result, " "));
2227 ALOGV("%s new bestOutput %d criteria %s",
2228 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002229 }
2230 }
2231
Eric Laurent16c66dd2019-05-01 17:54:10 -07002232 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002233}
2234
Eric Laurent8fc147b2018-07-22 19:13:55 -07002235status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002236{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002237 ALOGV("%s portId %d", __FUNCTION__, portId);
2238
2239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2240 if (outputDesc == 0) {
2241 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002242 return BAD_VALUE;
2243 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002244 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Eric Laurent8fc147b2018-07-22 19:13:55 -07002246 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002247 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002248
jiabin220eea12024-05-17 17:55:20 +00002249 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2250 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2251 && outputDesc->isBitPerfect()) {
2252 // Usually, APM selects bit-perfect output for high priority use cases only when
2253 // bit-perfect output is the only output that can be routed to the selected device.
2254 // However, here is no need to play high priority use cases such as ringtone and alarm
2255 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2256 // can attach to new output.
2257 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2258 __func__, client->stream());
2259 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2260 return DEAD_OBJECT;
2261 }
2262
Eric Laurent733ce942017-12-07 12:18:25 -08002263 status_t status = outputDesc->start();
2264 if (status != NO_ERROR) {
2265 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002266 }
2267
Eric Laurent97ac8712018-07-27 18:59:02 -07002268 uint32_t delayMs;
2269 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002270
2271 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002272 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002273 if (status == DEAD_OBJECT) {
2274 sp<SwAudioOutputDescriptor> desc =
2275 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2276 if (desc == nullptr) {
2277 // This is not common, it may indicate something wrong with the HAL.
2278 ALOGE("%s unable to open output with default config", __func__);
2279 return status;
2280 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002281 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002282 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002283 }
jiabina84c3d32022-12-02 18:59:55 +00002284
2285 // If the client is the first one active on preferred mixer parameters, reopen the output
2286 // if the current mixer parameters doesn't match the preferred one.
2287 if (outputDesc->devices().size() == 1) {
2288 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2289 outputDesc->devices()[0]->getId(), client->strategy());
2290 if (info != nullptr && info->getUid() == client->uid()) {
2291 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2292 info->getConfigBase(), info->getFlags())) {
2293 stopSource(outputDesc, client);
2294 outputDesc->stop();
2295 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2296 config.channel_mask = info->getConfigBase().channel_mask;
2297 config.sample_rate = info->getConfigBase().sample_rate;
2298 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002299 sp<SwAudioOutputDescriptor> desc =
2300 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2301 if (desc == nullptr) {
2302 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002303 }
jiabin220eea12024-05-17 17:55:20 +00002304 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002305 // Intentionally return error to let the client side resending request for
2306 // creating and starting.
2307 return DEAD_OBJECT;
2308 }
2309 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002310 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002311 // If it is first bit-perfect client, reroute all clients that will be routed to
2312 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2313 PortHandleVector clientsToInvalidate;
2314 for (size_t i = 0; i < mOutputs.size(); i++) {
2315 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002316 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002317 continue;
2318 }
2319 for (const auto& c : mOutputs[i]->getClientIterable()) {
2320 clientsToInvalidate.push_back(c->portId());
2321 }
2322 }
2323 if (!clientsToInvalidate.empty()) {
2324 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2325 __func__);
2326 mpClientInterface->invalidateTracks(clientsToInvalidate);
2327 }
2328 }
jiabina84c3d32022-12-02 18:59:55 +00002329 }
2330 }
2331
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002332 if (client->hasPreferredDevice()) {
2333 // playback activity with preferred device impacts routing occurred, inform upper layers
2334 mpClientInterface->onRoutingUpdated();
2335 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002336 if (delayMs != 0) {
2337 usleep(delayMs * 1000);
2338 }
2339
jiabin220eea12024-05-17 17:55:20 +00002340 if (status == NO_ERROR &&
2341 outputDesc->mPreferredAttrInfo != nullptr &&
2342 outputDesc->isBitPerfect() &&
2343 com::android::media::audioserver::
2344 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2345 // A new client is started on bit-perfect output, update all clients internal mute.
2346 updateClientsInternalMute(outputDesc);
2347 }
2348
Eric Laurentc75307b2015-03-17 15:29:32 -07002349 return status;
2350}
2351
Eric Laurent96d1dda2022-03-14 17:14:19 +01002352bool AudioPolicyManager::isLeUnicastActive() const {
2353 if (isInCall()) {
2354 return true;
2355 }
2356 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2357}
2358
2359bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2360 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2361 return false;
2362 }
2363 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2364 ALOGV("%s active %d", __func__, active);
2365 return active;
2366}
2367
Eric Laurent97ac8712018-07-27 18:59:02 -07002368status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2369 const sp<TrackClientDescriptor>& client,
2370 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002371{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002372 // cannot start playback of STREAM_TTS if any other output is being used
2373 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002374
2375 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002376 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002377 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002378 auto clientStrategy = client->strategy();
2379 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002380 if (stream == AUDIO_STREAM_TTS) {
2381 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002382 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002383 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002384 return INVALID_OPERATION;
2385 } else {
2386 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2387 }
2388 } else {
2389 // some playback other than beacon starts
2390 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2391 }
2392
Eric Laurent77305a62016-07-25 16:39:22 -07002393 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002394 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002395 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002396
François Gaffie11d30102018-11-02 16:09:09 +01002397 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002398 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002399 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002400 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002401 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002402 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002403 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002404 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002405 } else {
2406 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002407 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002408 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2409 AUDIO_FORMAT_DEFAULT);
2410 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2411 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002412 }
2413
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002414 // requiresMuteCheck is false when we can bypass mute strategy.
2415 // It covers a common case when there is no materially active audio
2416 // and muting would result in unnecessary delay and dropped audio.
2417 const uint32_t outputLatencyMs = outputDesc->latency();
2418 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002419 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002420
Eric Laurente552edb2014-03-10 17:42:56 -07002421 // increment usage count for this stream on the requested output:
2422 // NOTE that the usage count is the same for duplicated output and hardware output which is
2423 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002424 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002425
2426 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002427 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002428 // Preferred device may be exclusive, use only if no other active clients on this output
2429 devices = DeviceVector(
2430 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2431 } else {
2432 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2433 }
François Gaffie11d30102018-11-02 16:09:09 +01002434 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002435 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002436 }
2437 }
Eric Laurente552edb2014-03-10 17:42:56 -07002438
François Gaffiec005e562018-11-06 15:04:49 +01002439 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002440 selectOutputForMusicEffects();
2441 }
2442
François Gaffie1c878552018-11-22 16:53:21 +01002443 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002444 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002445 if (devices.isEmpty()) {
2446 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002447 }
François Gaffiec005e562018-11-06 15:04:49 +01002448 bool shouldWait =
2449 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2450 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2451 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002452 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002453 const bool needToCloseBitPerfectOutput =
2454 (com::android::media::audioserver::
2455 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2456 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2457 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002458 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002460 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461 // An output has a shared device if
2462 // - managed by the same hw module
2463 // - supports the currently selected device
2464 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002465 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002466
Eric Laurent77305a62016-07-25 16:39:22 -07002467 // force a device change if any other output is:
2468 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002469 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002470 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002471 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002472 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002473 // change the device currently selected by the other output.
2474 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002475 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002476 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002477 force = true;
2478 }
2479 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002480 // a notification so that audio focus effect can propagate, or that a mute/unmute
2481 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002482 const uint32_t latencyMs = desc->latency();
2483 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2484
2485 if (shouldWait && isActive && (waitMs < latencyMs)) {
2486 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002487 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002488
2489 // Require mute check if another output is on a shared device
2490 // and currently active to have proper drain and avoid pops.
2491 // Note restoring AudioTracks onto this output needs to invoke
2492 // a volume ramp if there is no mute.
2493 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002494
2495 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2496 outputsToReopen.push_back(desc);
2497 }
Eric Laurente552edb2014-03-10 17:42:56 -07002498 }
2499 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002500
jiabin220eea12024-05-17 17:55:20 +00002501 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002502 // If the output is open with preferred mixer attributes, but the routed device is
2503 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2504 // changed.
2505 return DEAD_OBJECT;
2506 }
jiabin220eea12024-05-17 17:55:20 +00002507 for (auto& outputToReopen : outputsToReopen) {
2508 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2509 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002510 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302511 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2512 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002513
Eric Laurente552edb2014-03-10 17:42:56 -07002514 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002515 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002516 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002517 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002518 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002519 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002520 outputDesc->useHwGain() /*force*/)) {
2521 // request AudioService to reinitialize the volume curves asynchronously
2522 ALOGE("checkAndSetVolume failed, requesting volume range init");
2523 mpClientInterface->onVolumeRangeInitRequest();
2524 };
Eric Laurente552edb2014-03-10 17:42:56 -07002525
2526 // update the outputs if starting an output with a stream that can affect notification
2527 // routing
2528 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002529
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002530 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002531 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002532 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002533 }
Eric Laurentdc462862016-07-19 12:29:53 -07002534
2535 if (waitMs > muteWaitMs) {
2536 *delayMs = waitMs - muteWaitMs;
2537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538
2539 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2540 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2541 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2542 // change occurs after the MixerThread starts and causes a stream volume
2543 // glitch.
2544 //
2545 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002546 }
Eric Laurentdc462862016-07-19 12:29:53 -07002547
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002548 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002549 mEngine->getForceUse(
2550 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002551 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002552 }
2553
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 // Automatically enable the remote submix input when output is started on a re routing mix
2555 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002556 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2557 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2559 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2560 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002561 "remote-submix",
2562 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002563 }
2564
Eric Laurent96d1dda2022-03-14 17:14:19 +01002565 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2566
Eric Laurente552edb2014-03-10 17:42:56 -07002567 return NO_ERROR;
2568}
2569
Eric Laurent96d1dda2022-03-14 17:14:19 +01002570void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2571 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2572 bool isUnicastActive = isLeUnicastActive();
2573
2574 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002575 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002576 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2577 for (size_t i = 0; i < mOutputs.size(); i++) {
2578 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2579 if (desc != ignoredOutput && desc->isActive()
2580 && ((isUnicastActive &&
2581 !desc->devices().
2582 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2583 || (wasUnicastActive &&
2584 !desc->devices().getDevicesFromTypes(
2585 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2586 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2587 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002588 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002589 // If the device is using preferred mixer attributes, the output need to reopen
2590 // with default configuration when the new selected devices are different from
2591 // current routing devices.
2592 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2593 continue;
2594 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302595 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002596 // re-apply device specific volume if not done by setOutputDevice()
2597 if (!force) {
2598 applyStreamVolumes(desc, newDevices.types(), delayMs);
2599 }
2600 }
2601 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002602 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002603 }
2604}
2605
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002607{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 ALOGV("%s portId %d", __FUNCTION__, portId);
2609
2610 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2611 if (outputDesc == 0) {
2612 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 return BAD_VALUE;
2614 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002615 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002616
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002617 if (client->hasPreferredDevice(true)) {
2618 // playback activity with preferred device impacts routing occurred, inform upper layers
2619 mpClientInterface->onRoutingUpdated();
2620 }
2621
Eric Laurent97ac8712018-07-27 18:59:02 -07002622 ALOGV("stopOutput() output %d, stream %d, session %d",
2623 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002624
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002626
Eric Laurent733ce942017-12-07 12:18:25 -08002627 if (status == NO_ERROR ) {
2628 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002629 } else {
2630 return status;
2631 }
2632
2633 if (outputDesc->devices().size() == 1) {
2634 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2635 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002636 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002637 if (info != nullptr && info->getUid() == client->uid()) {
2638 info->decreaseActiveClient();
2639 if (info->getActiveClientCount() == 0) {
2640 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002641 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002642 }
2643 }
jiabin220eea12024-05-17 17:55:20 +00002644 if (com::android::media::audioserver::
2645 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2646 !outputReopened && outputDesc->isBitPerfect()) {
2647 // Only need to update the clients' internal mute when the output is bit-perfect and it
2648 // is not reopened.
2649 updateClientsInternalMute(outputDesc);
2650 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002651 }
2652 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002653}
2654
Eric Laurent97ac8712018-07-27 18:59:02 -07002655status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2656 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002657{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002658 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002659 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002660 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002661 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002662
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002663 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2664
François Gaffie1c878552018-11-22 16:53:21 +01002665 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2666 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002667 // Automatically disable the remote submix input when output is stopped on a
2668 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002669 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002670 if (isSingleDeviceType(
2671 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002672 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002673 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2675 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002676 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002677 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002678 }
2679 }
2680 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002681 if (client->hasPreferredDevice(true) &&
2682 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002683 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 forceDeviceUpdate = true;
2685 }
2686
Eric Laurente552edb2014-03-10 17:42:56 -07002687 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002688 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002689
Eric Laurente552edb2014-03-10 17:42:56 -07002690 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002691 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002692 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002693 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002694
2695 // If the routing does not change, if an output is routed on a device using HwGain
2696 // (aka setAudioPortConfig) and there are still active clients following different
2697 // volume group(s), force reapply volume
2698 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2699 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2700
Eric Laurente552edb2014-03-10 17:42:56 -07002701 // delay the device switch by twice the latency because stopOutput() is executed when
2702 // the track stop() command is received and at that time the audio track buffer can
2703 // still contain data that needs to be drained. The latency only covers the audio HAL
2704 // and kernel buffers. Also the latency does not always include additional delay in the
2705 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302706 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002707 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002708
2709 // force restoring the device selection on other active outputs if it differs from the
2710 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002711 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002712 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002713 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002714 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002715 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002716 desc->isActive() &&
2717 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002718 (newDevices != desc->devices())) {
2719 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2720 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002721
jiabin220eea12024-05-17 17:55:20 +00002722 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002723 // If the device is using preferred mixer attributes, the output need to
2724 // reopen with default configuration when the new selected devices are
2725 // different from current routing devices.
2726 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2727 continue;
2728 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302729 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002730
Eric Laurent57de36c2016-09-28 16:59:11 -07002731 // re-apply device specific volume if not done by setOutputDevice()
2732 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002733 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002734 }
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
2736 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002737 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002738 // update the outputs if stopping one with a stream that can affect notification routing
2739 handleNotificationRoutingForStream(stream);
2740 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002741
2742 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2743 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002744 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002745 }
2746
François Gaffiec005e562018-11-06 15:04:49 +01002747 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002748 selectOutputForMusicEffects();
2749 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002750
2751 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2752
Eric Laurente552edb2014-03-10 17:42:56 -07002753 return NO_ERROR;
2754 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002755 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002756 return INVALID_OPERATION;
2757 }
2758}
2759
jiabinbce0c1d2020-10-05 11:20:18 -07002760bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002761{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002762 ALOGV("%s portId %d", __FUNCTION__, portId);
2763
2764 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2765 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002766 // If an output descriptor is closed due to a device routing change,
2767 // then there are race conditions with releaseOutput from tracks
2768 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2769 // destroyed shortly thereafter.
2770 //
2771 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002772 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002773 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002774 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002775
2776 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002777
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302778 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2779 if (outputDesc->isClientActive(client)) {
2780 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2781 stopOutput(portId);
2782 }
2783
Eric Laurent8fc147b2018-07-22 19:13:55 -07002784 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2785 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002786 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002787 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002788 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002790 if (--outputDesc->mDirectOpenCount == 0) {
2791 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002792 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002793 }
2794 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302795
Andy Hung39efb7a2018-09-26 15:39:28 -07002796 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002797 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2798 // The output is pending reopened to query dynamic profiles and
2799 // there is no active clients
2800 closeOutput(outputDesc->mIoHandle);
2801 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2802 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2803 if (newOutputDesc == nullptr) {
2804 ALOGE("%s failed to open output", __func__);
2805 }
2806 return true;
2807 }
2808 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002809}
2810
Eric Laurentcaf7f482014-11-25 17:50:47 -08002811status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2812 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002813 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002814 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002815 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002816 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002817 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002818 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002819 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002820 audio_port_handle_t *portId,
2821 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002822{
François Gaffiec005e562018-11-06 15:04:49 +01002823 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002824 "flags %#x attributes=%s requested device ID %d",
2825 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2826 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002827
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002829 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002830 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002831 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002833 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 sp<RecordClientDescriptor> clientDesc;
2835 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002836 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002838
2839 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2840 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2841 return INVALID_OPERATION;
2842 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002843
Francois Gaffie716e1432019-01-14 16:58:59 +01002844 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2845 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002846 }
2847
Paul McLean466dc8e2015-04-17 13:15:36 -06002848 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002849 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002850 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002851
Eric Laurentad2e7b92017-09-14 20:06:42 -07002852 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2853 // possible
2854 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2855 *input != AUDIO_IO_HANDLE_NONE) {
2856 ssize_t index = mInputs.indexOfKey(*input);
2857 if (index < 0) {
2858 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2859 status = BAD_VALUE;
2860 goto error;
2861 }
2862 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002863 RecordClientVector clients = inputDesc->getClientsForSession(session);
2864 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002865 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2866 status = BAD_VALUE;
2867 goto error;
2868 }
2869 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2870 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002871 // corresponds to a new client and is only permitted from the same UID.
2872 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 if (clients.size() > 1) {
2874 for (const auto& client : clients) {
2875 // The client map is ordered by key values (portId) and portIds are allocated
2876 // incrementaly. So the first client in this list is the one opened by audio flinger
2877 // when the mmap stream is created and should be ignored as it does not correspond
2878 // to an actual client
2879 if (client == *clients.cbegin()) {
2880 continue;
2881 }
2882 if (uid != client->uid() && !client->isSilenced()) {
2883 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2884 uid, client->portId(), client->uid());
2885 status = INVALID_OPERATION;
2886 goto error;
2887 }
Eric Laurent331679c2018-04-16 17:03:16 -07002888 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002889 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002890 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002891 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002892
Eric Laurentfecbceb2021-02-09 14:46:43 +01002893 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 }
2896
2897 *input = AUDIO_IO_HANDLE_NONE;
2898 *inputType = API_INPUT_INVALID;
2899
Francois Gaffie716e1432019-01-14 16:58:59 +01002900 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002901 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002902 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002903 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002904 ALOGW("%s could not find input mix for attr %s",
2905 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002907 }
jiabinc1de2df2019-05-07 14:26:40 -07002908 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2909 String8(attr->tags + strlen("addr=")),
2910 AUDIO_FORMAT_DEFAULT);
2911 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002912 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002913 __func__, attributes.source, attributes.tags);
2914 status = BAD_VALUE;
2915 goto error;
2916 }
2917
Kevin Rocard25f9b052019-02-27 15:08:54 -08002918 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2919 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2920 } else {
2921 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2922 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002923 if (virtualDeviceId) {
2924 *virtualDeviceId = policyMix->mVirtualDeviceId;
2925 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002926 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002927 if (explicitRoutingDevice != nullptr) {
2928 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002929 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002930 // Prevent from storing invalid requested device id in clients
2931 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002932 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002933 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2934 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002935 }
François Gaffie11d30102018-11-02 16:09:09 +01002936 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002937 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002938 status = BAD_VALUE;
2939 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002940 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002941 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2942 *inputType = API_INPUT_MIX_CAPTURE;
2943 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002944 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2945 // there is an external policy, but this input is attached to a mix of recorders,
2946 // meaning it receives audio injected into the framework, so the recorder doesn't
2947 // know about it and is therefore considered "legacy"
2948 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002949
2950 if (virtualDeviceId) {
2951 *virtualDeviceId = policyMix->mVirtualDeviceId;
2952 }
François Gaffie11d30102018-11-02 16:09:09 +01002953 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002954 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002955 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002956 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002957 } else {
2958 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002959 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002960
Eric Laurent599c7582015-12-07 18:05:55 -08002961 }
2962
François Gaffiec005e562018-11-06 15:04:49 +01002963 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002964 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002965 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002966 AudioProfileVector profiles;
2967 status_t ret = getProfilesForDevices(
2968 DeviceVector(device), profiles, flags, true /*isInput*/);
2969 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002970 const auto channels = profiles[0]->getChannels();
2971 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2972 config->channel_mask = *channels.begin();
2973 }
2974 const auto sampleRates = profiles[0]->getSampleRates();
2975 if (!sampleRates.empty() &&
2976 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2977 config->sample_rate = *sampleRates.begin();
2978 }
jiabinf1c73972022-04-14 16:28:52 -07002979 config->format = profiles[0]->getFormat();
2980 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002981 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002982 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002983
Marvin Ramine5a122d2023-12-07 13:57:59 +01002984
2985 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2986 *virtualDeviceId = policyMix->mVirtualDeviceId;
2987 }
2988
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989exit:
2990
François Gaffiec005e562018-11-06 15:04:49 +01002991 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2992 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002993
Francois Gaffie716e1432019-01-14 16:58:59 +01002994 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002995 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002996 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997
Mikhail Naganov2996f672019-04-18 12:29:59 -07002998 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002999 requestedDeviceId, attributes.source, flags,
3000 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003002 // Move (if found) effect for the client session to its input
3003 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003004 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003005
3006 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3007 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003008
Eric Laurent599c7582015-12-07 18:05:55 -08003009 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003010
3011error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003013}
3014
3015
François Gaffie11d30102018-11-02 16:09:09 +01003016audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003017 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003018 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003019 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003020 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003021 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003022{
3023 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003024 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003025 bool isSoundTrigger = false;
3026
François Gaffiec005e562018-11-06 15:04:49 +01003027 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003028 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3029 if (index >= 0) {
3030 input = mSoundTriggerSessions.valueFor(session);
3031 isSoundTrigger = true;
3032 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3033 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3034 } else {
3035 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003036 }
François Gaffiec005e562018-11-06 15:04:49 +01003037 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003038 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003039 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003040 }
3041
Carter Hsua3abb402021-10-26 11:11:20 +08003042 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3043 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3044 }
3045
Eric Laurentfe231122017-11-17 17:48:06 -08003046 // sampling rate and flags may be updated by getInputProfile
3047 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3048 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003049 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003050 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003051 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003052 // find a compatible input profile (not necessarily identical in parameters)
3053 sp<IOProfile> profile = getInputProfile(
3054 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3055 if (profile == nullptr) {
3056 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003057 }
jiabin2fd710d2022-05-02 23:20:22 +00003058
Glenn Kasten05ddca52016-02-11 08:17:12 -08003059 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003060 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003061 if (samplingRate == 0) {
3062 samplingRate = profileSamplingRate;
3063 }
Eric Laurente552edb2014-03-10 17:42:56 -07003064
Eric Laurent322b4d22015-04-03 15:57:54 -07003065 if (profile->getModuleHandle() == 0) {
3066 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003067 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003068 }
3069
Eric Laurentec376dc2021-04-08 20:41:22 +02003070 // Reuse an already opened input if a client with the same session ID already exists
3071 // on that input
3072 for (size_t i = 0; i < mInputs.size(); i++) {
3073 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3074 if (desc->mProfile != profile) {
3075 continue;
3076 }
3077 RecordClientVector clients = desc->clientsList();
3078 for (const auto &client : clients) {
3079 if (session == client->session()) {
3080 return desc->mIoHandle;
3081 }
3082 }
3083 }
3084
Eric Laurent3974e3b2017-12-07 17:58:43 -08003085 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003086 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003087 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003088 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003089 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003090 continue;
3091 }
3092 // if sound trigger, reuse input if used by other sound trigger on same session
3093 // else
3094 // reuse input if active client app is not in IDLE state
3095 //
3096 RecordClientVector clients = desc->clientsList();
3097 bool doClose = false;
3098 for (const auto& client : clients) {
3099 if (isSoundTrigger != client->isSoundTrigger()) {
3100 continue;
3101 }
3102 if (client->isSoundTrigger()) {
3103 if (session == client->session()) {
3104 return desc->mIoHandle;
3105 }
3106 continue;
3107 }
3108 if (client->active() && client->appState() != APP_STATE_IDLE) {
3109 return desc->mIoHandle;
3110 }
3111 doClose = true;
3112 }
3113 if (doClose) {
3114 closeInput(desc->mIoHandle);
3115 } else {
3116 i++;
3117 }
3118 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003119 }
3120
Eric Laurentfe231122017-11-17 17:48:06 -08003121 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003122
Eric Laurentfe231122017-11-17 17:48:06 -08003123 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3124 lConfig.sample_rate = profileSamplingRate;
3125 lConfig.channel_mask = profileChannelMask;
3126 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003127
François Gaffie11d30102018-11-02 16:09:09 +01003128 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003129
3130 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003131 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003132 (profileSamplingRate != lConfig.sample_rate) ||
3133 !audio_formats_match(profileFormat, lConfig.format) ||
3134 (profileChannelMask != lConfig.channel_mask)) {
3135 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003136 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003137 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003138 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003139 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003140 }
Eric Laurent599c7582015-12-07 18:05:55 -08003141 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003142 }
3143
Eric Laurentc722f302014-12-10 11:21:49 -08003144 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003145
Eric Laurent599c7582015-12-07 18:05:55 -08003146 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003147 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003148
Eric Laurent599c7582015-12-07 18:05:55 -08003149 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003150}
3151
Eric Laurent4eb58f12018-12-07 16:41:02 -08003152status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003153{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003154 ALOGV("%s portId %d", __FUNCTION__, portId);
3155
3156 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3157 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003158 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003159 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003160 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003161 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003162 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 if (client->active()) {
3164 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3165 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003166 }
3167
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168 audio_session_t session = client->session();
3169
Eric Laurent4eb58f12018-12-07 16:41:02 -08003170 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003171
Eric Laurent4eb58f12018-12-07 16:41:02 -08003172 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003173
Eric Laurent4eb58f12018-12-07 16:41:02 -08003174 status_t status = inputDesc->start();
3175 if (status != NO_ERROR) {
3176 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003177 }
Eric Laurente552edb2014-03-10 17:42:56 -07003178
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003179 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003180 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003182
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 // indicate active capture to sound trigger service if starting capture from a mic on
3184 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003185 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003186 if (device != nullptr) {
3187 status = setInputDevice(input, device, true /* force */);
3188 } else {
3189 ALOGW("%s no new input device can be found for descriptor %d",
3190 __FUNCTION__, inputDesc->getId());
3191 status = BAD_VALUE;
3192 }
Eric Laurente552edb2014-03-10 17:42:56 -07003193
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003194 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003195 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003197 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003198 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3199 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003200 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003201 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003202
François Gaffie11d30102018-11-02 16:09:09 +01003203 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3204 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003206 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003207 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003208
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 // automatically enable the remote submix output when input is started if not
3210 // used by a policy mix of type MIX_TYPE_RECORDERS
3211 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003212 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003213 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003214 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003215 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003216 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3217 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003218 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003219 if (address != "") {
3220 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3221 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003222 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003223 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003224 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003225 } else if (status != NO_ERROR) {
3226 // Restore client activity state.
3227 inputDesc->setClientActive(client, false);
3228 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003229 }
3230
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003231 ALOGV("%s input %d source = %d status = %d exit",
3232 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003233
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003234 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003235}
3236
Eric Laurent8fc147b2018-07-22 19:13:55 -07003237status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003238{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003239 ALOGV("%s portId %d", __FUNCTION__, portId);
3240
3241 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3242 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003243 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003244 return BAD_VALUE;
3245 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003246 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003247 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003248 if (!client->active()) {
3249 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003250 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003251 }
Carter Hsue6139d52021-07-08 10:30:20 +08003252 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003253 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003254
Eric Laurent8f42ea12018-08-08 09:08:25 -07003255 inputDesc->stop();
3256 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003257 auto current_source = inputDesc->source();
3258 setInputDevice(input, getNewInputDevice(inputDesc),
3259 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003260 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003261 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003263 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003264 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3265 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003266 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003267 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003268
3269 // automatically disable the remote submix output when input is stopped if not
3270 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003271 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003272 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003273 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003274 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003275 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3276 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003277 }
3278 if (address != "") {
3279 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3280 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003281 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003282 }
3283 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 resetInputDevice(input);
3285
3286 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3287 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003288 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3289 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003291 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003292 }
3293 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003295 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003296}
3297
Eric Laurent8fc147b2018-07-22 19:13:55 -07003298void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003299{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003300 ALOGV("%s portId %d", __FUNCTION__, portId);
3301
3302 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3303 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003304 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003305 return;
3306 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003307 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003308 audio_io_handle_t input = inputDesc->mIoHandle;
3309
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003311
Andy Hung39efb7a2018-09-26 15:39:28 -07003312 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003313
3314 // If no more clients are present in this session, park effects to an orphan chain
3315 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3316 if (clientsOnSession.size() == 0) {
3317 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3318 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003319 if (inputDesc->getClientCount() > 0) {
3320 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003321 return;
3322 }
3323
Eric Laurent05b90f82014-08-27 15:32:29 -07003324 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003325 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003327}
3328
Eric Laurent8f42ea12018-08-08 09:08:25 -07003329void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003330{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003332
3333 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003335 }
3336}
3337
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3339{
3340 stopInput(portId);
3341 releaseInput(portId);
3342}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003343
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003344bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3345 if (input->clientsList().size() == 0
3346 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3347 return true;
3348 }
3349 for (const auto& client : input->clientsList()) {
3350 sp<DeviceDescriptor> device =
3351 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3352 client->session());
3353 if (!input->supportedDevices().contains(device)) {
3354 return true;
3355 }
3356 }
3357 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3358 return false;
3359}
3360
Eric Laurent0dd51852019-04-19 18:18:58 -07003361void AudioPolicyManager::checkCloseInputs() {
3362 // After connecting or disconnecting an input device, close input if:
3363 // - it has no client (was just opened to check profile) OR
3364 // - none of its supported devices are connected anymore OR
3365 // - one of its clients cannot be routed to one of its supported
3366 // devices anymore. Otherwise update device selection
3367 std::vector<audio_io_handle_t> inputsToClose;
3368 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003369 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003370 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003371 }
3372 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003373 for (const audio_io_handle_t handle : inputsToClose) {
3374 ALOGV("%s closing input %d", __func__, handle);
3375 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003376 }
Eric Laurentd4692962014-05-05 18:13:44 -07003377}
3378
Vlad Popa87e0e582024-05-20 18:49:20 -07003379status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3380 const char *address __unused,
3381 bool enabled,
3382 audio_stream_type_t streamToDriveAbs)
3383{
3384 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3385 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3386 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3387 toString(streamToDriveAbs).c_str());
3388 return BAD_VALUE;
3389 }
3390
3391 if (enabled) {
3392 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3393 } else {
3394 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3395 }
3396
3397 return NO_ERROR;
3398}
3399
François Gaffie251c7f02018-11-07 10:41:08 +01003400void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003401{
3402 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003403 if (indexMin < 0 || indexMax < 0) {
3404 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3405 return;
3406 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003407 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003408
3409 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003410 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3411 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003412 continue;
3413 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003414 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003415 }
Eric Laurente552edb2014-03-10 17:42:56 -07003416}
3417
Eric Laurente0720872014-03-11 09:30:41 -07003418status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003419 int index,
3420 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003421{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003422 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003423 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3424 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3425 return NO_ERROR;
3426 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003427 ALOGV("%s: stream %s attributes=%s", __func__,
3428 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003429 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003430}
3431
Eric Laurente0720872014-03-11 09:30:41 -07003432status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003433 int *index,
3434 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003435{
François Gaffiec005e562018-11-06 15:04:49 +01003436 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3437 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003438 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003439 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003440 deviceTypes = mEngine->getOutputDevicesForStream(
3441 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003442 }
jiabin9a3361e2019-10-01 09:38:30 -07003443 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003444}
3445
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003446status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003447 int index,
3448 audio_devices_t device)
3449{
3450 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003451 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3452 if (group == VOLUME_GROUP_NONE) {
3453 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003454 return BAD_VALUE;
3455 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003456 ALOGV("%s: group %d matching with %s index %d",
3457 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003458 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003459 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003460 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003461 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3462 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3463 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3464 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003465 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3466
3467 status = setVolumeCurveIndex(index, device, curves);
3468 if (status != NO_ERROR) {
3469 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3470 return status;
3471 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003472
jiabin9a3361e2019-10-01 09:38:30 -07003473 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003474 auto curCurvAttrs = curves.getAttributes();
3475 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3476 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003477 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003478 } else if (!curves.getStreamTypes().empty()) {
3479 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003480 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003481 } else {
3482 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3483 return BAD_VALUE;
3484 }
jiabin9a3361e2019-10-01 09:38:30 -07003485 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3486 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003487
François Gaffiecfe17322018-11-07 13:41:29 +01003488 // update volume on all outputs and streams matching the following:
3489 // - The requested stream (or a stream matching for volume control) is active on the output
3490 // - The device (or devices) selected by the engine for this stream includes
3491 // the requested device
3492 // - For non default requested device, currently selected device on the output is either the
3493 // requested device or one of the devices selected by the engine for this stream
3494 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3495 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003496 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003497 for (size_t i = 0; i < mOutputs.size(); i++) {
3498 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003499 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003500
jiabin9a3361e2019-10-01 09:38:30 -07003501 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3502 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003503 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003504
3505 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003506 continue;
3507 }
3508 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3509 curDevices.find(device) == curDevices.end()) {
3510 continue;
3511 }
3512 bool applyVolume = false;
3513 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3514 curSrcDevices.insert(device);
3515 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003516 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3517 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003518 } else {
3519 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3520 }
3521 if (!applyVolume) {
3522 continue; // next output
3523 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003524 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3525 // If a higher priority strategy is active, and the output is routed to a device with a
3526 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003527 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003528 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003529 // If the volume source is active with higher priority source, ensure at least Sw Muted
3530 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003531 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3532 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3533 false /*preferredDevice*/);
3534 if (activeClients.empty()) {
3535 continue;
3536 }
3537 bool isPreempted = false;
3538 bool isHigherPriority = productStrategy < strategy;
3539 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003540 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003541 ALOGV("%s: Strategy=%d (\nrequester:\n"
3542 " group %d, volumeGroup=%d attributes=%s)\n"
3543 " higher priority source active:\n"
3544 " volumeGroup=%d attributes=%s) \n"
3545 " on output %zu, bailing out", __func__, productStrategy,
3546 group, group, toString(attributes).c_str(),
3547 client->volumeSource(), toString(client->attributes()).c_str(), i);
3548 applyVolume = false;
3549 isPreempted = true;
3550 break;
3551 }
3552 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003553 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003554 applyVolume = true;
3555 }
3556 }
3557 if (isPreempted || applyVolume) {
3558 break;
3559 }
3560 }
3561 if (!applyVolume) {
3562 continue; // next output
3563 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003564 }
François Gaffieed91f582020-01-31 10:35:37 +01003565 //FIXME: workaround for truncated touch sounds
3566 // delayed volume change for system stream to be removed when the problem is
3567 // handled by system UI
3568 status_t volStatus = checkAndSetVolume(
3569 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003570 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003571 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3572 if (volStatus != NO_ERROR) {
3573 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003574 }
3575 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003576
3577 // update voice volume if the an active call route exists
3578 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3579 && (curSrcDevices.find(
3580 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3581 != curSrcDevices.end())) {
3582 bool isVoiceVolSrc;
3583 bool isBtScoVolSrc;
3584 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3585 isVoiceVolSrc, isBtScoVolSrc, __func__)
3586 && (isVoiceVolSrc || isBtScoVolSrc)) {
3587 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3588 }
3589 }
3590
François Gaffiecfe17322018-11-07 13:41:29 +01003591 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3592 return status;
3593}
3594
François Gaffieaaac0fd2018-11-22 17:56:39 +01003595status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003596 audio_devices_t device,
3597 IVolumeCurves &volumeCurves)
3598{
3599 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3600 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003601 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3602 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003603 (index > volumeCurves.getVolumeIndexMax())) {
3604 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3605 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3606 return BAD_VALUE;
3607 }
3608 if (!audio_is_output_device(device)) {
3609 return BAD_VALUE;
3610 }
3611
3612 // Force max volume if stream cannot be muted
3613 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3614
François Gaffieaaac0fd2018-11-22 17:56:39 +01003615 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003616 volumeCurves.addCurrentVolumeIndex(device, index);
3617 return NO_ERROR;
3618}
3619
3620status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3621 int &index,
3622 audio_devices_t device)
3623{
3624 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3625 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003626 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003627 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003628 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003629 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003630 }
jiabin9a3361e2019-10-01 09:38:30 -07003631 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003632}
3633
3634status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3635 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003636 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003637{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003638 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003639 return BAD_VALUE;
3640 }
jiabin9a3361e2019-10-01 09:38:30 -07003641 index = curves.getVolumeIndex(deviceTypes);
3642 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003643 return NO_ERROR;
3644}
3645
3646status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3647 int &index)
3648{
3649 index = getVolumeCurves(attr).getVolumeIndexMin();
3650 return NO_ERROR;
3651}
3652
3653status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3654 int &index)
3655{
3656 index = getVolumeCurves(attr).getVolumeIndexMax();
3657 return NO_ERROR;
3658}
3659
Eric Laurent36829f92017-04-07 19:04:42 -07003660audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003661{
3662 // select one output among several suitable for global effects.
3663 // The priority is as follows:
3664 // 1: An offloaded output. If the effect ends up not being offloadable,
3665 // AudioFlinger will invalidate the track and the offloaded output
3666 // will be closed causing the effect to be moved to a PCM output.
3667 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003668 // 3: The primary output
3669 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003670
François Gaffiec005e562018-11-06 15:04:49 +01003671 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3672 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003673 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003674
Eric Laurent36829f92017-04-07 19:04:42 -07003675 if (outputs.size() == 0) {
3676 return AUDIO_IO_HANDLE_NONE;
3677 }
Eric Laurente552edb2014-03-10 17:42:56 -07003678
Eric Laurent36829f92017-04-07 19:04:42 -07003679 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3680 bool activeOnly = true;
3681
3682 while (output == AUDIO_IO_HANDLE_NONE) {
3683 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3684 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3685 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3686
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003687 for (audio_io_handle_t output : outputs) {
3688 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003689 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003690 continue;
3691 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003692 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3693 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003694 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003695 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003696 }
3697 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003698 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003699 }
3700 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003701 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003702 }
3703 }
3704 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3705 output = outputOffloaded;
3706 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3707 output = outputDeepBuffer;
3708 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3709 output = outputPrimary;
3710 } else {
3711 output = outputs[0];
3712 }
3713 activeOnly = false;
3714 }
3715
3716 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003717 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3718 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003719 mMusicEffectOutput = output;
3720 }
3721
3722 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003723 return output;
3724}
3725
Eric Laurent36829f92017-04-07 19:04:42 -07003726audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3727{
3728 return selectOutputForMusicEffects();
3729}
3730
Eric Laurente0720872014-03-11 09:30:41 -07003731status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003732 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003733 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003734 int session,
3735 int id)
3736{
Shunkai Yao29d10572024-03-19 04:31:47 +00003737 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003738 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003739 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003740 index = mInputs.indexOfKey(io);
3741 if (index < 0) {
3742 ALOGW("registerEffect() unknown io %d", io);
3743 return INVALID_OPERATION;
3744 }
Eric Laurente552edb2014-03-10 17:42:56 -07003745 }
3746 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003747 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3748 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3749 || strategy == PRODUCT_STRATEGY_NONE));
3750 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003751}
3752
Eric Laurentc241b0d2018-11-28 09:08:49 -08003753status_t AudioPolicyManager::unregisterEffect(int id)
3754{
3755 if (mEffects.getEffect(id) == nullptr) {
3756 return INVALID_OPERATION;
3757 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003758 if (mEffects.isEffectEnabled(id)) {
3759 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3760 setEffectEnabled(id, false);
3761 }
3762 return mEffects.unregisterEffect(id);
3763}
3764
3765status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3766{
3767 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3768 if (effect == nullptr) {
3769 return INVALID_OPERATION;
3770 }
3771
3772 status_t status = mEffects.setEffectEnabled(id, enabled);
3773 if (status == NO_ERROR) {
3774 mInputs.trackEffectEnabled(effect, enabled);
3775 }
3776 return status;
3777}
3778
Eric Laurent6c796322019-04-09 14:13:17 -07003779
3780status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3781{
3782 mEffects.moveEffects(ids, io);
3783 return NO_ERROR;
3784}
3785
Eric Laurentc75307b2015-03-17 15:29:32 -07003786bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3787{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003788 auto vs = toVolumeSource(stream, false);
3789 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003790}
3791
3792bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3793{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003794 auto vs = toVolumeSource(stream, false);
3795 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003796}
3797
Eric Laurente0720872014-03-11 09:30:41 -07003798bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003799{
3800 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003801 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003802 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003803 return true;
3804 }
3805 }
3806 return false;
3807}
3808
Eric Laurent275e8e92014-11-30 15:14:47 -08003809// Register a list of custom mixes with their attributes and format.
3810// When a mix is registered, corresponding input and output profiles are
3811// added to the remote submix hw module. The profile contains only the
3812// parameters (sampling rate, format...) specified by the mix.
3813// The corresponding input remote submix device is also connected.
3814//
3815// When a remote submix device is connected, the address is checked to select the
3816// appropriate profile and the corresponding input or output stream is opened.
3817//
3818// When capture starts, getInputForAttr() will:
3819// - 1 look for a mix matching the address passed in attribtutes tags if any
3820// - 2 if none found, getDeviceForInputSource() will:
3821// - 2.1 look for a mix matching the attributes source
3822// - 2.2 if none found, default to device selection by policy rules
3823// At this time, the corresponding output remote submix device is also connected
3824// and active playback use cases can be transferred to this mix if needed when reconnecting
3825// after AudioTracks are invalidated
3826//
3827// When playback starts, getOutputForAttr() will:
3828// - 1 look for a mix matching the address passed in attribtutes tags if any
3829// - 2 if none found, look for a mix matching the attributes usage
3830// - 3 if none found, default to device and output selection by policy rules.
3831
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003832status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003833{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003834 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3835 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003836 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003837 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003838 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003839 // examine each mix's route type
3840 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003841 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003842 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3843 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3844 ALOGE("Unsupported Policy Mix %zu of %zu: "
3845 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3846 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003847 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003848 break;
3849 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003850 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3851 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003852 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003853 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3854 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003855 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003856 rSubmixModule = mHwModules.getModuleFromName(
3857 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3858 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003859 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003860 i);
3861 res = INVALID_OPERATION;
3862 break;
3863 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003864 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003865
Eric Laurent97ac8712018-07-27 18:59:02 -07003866 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003867 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003868 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003869 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003870 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3871 } else {
3872 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3873 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003874 }
François Gaffie036e1e92015-03-19 10:16:24 +01003875
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003876 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003877 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003878 res = INVALID_OPERATION;
3879 break;
3880 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003881 audio_config_t outputConfig = mix.mFormat;
3882 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003883 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3884 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003885 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3886 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003887 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003888 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3889 audio_is_linear_pcm(outputConfig.format)
3890 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003891 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003892 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3893 audio_is_linear_pcm(inputConfig.format)
3894 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003895
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003896 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003897 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003898 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003899 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003900 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003901 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003902 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003903 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3904 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003905 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003906 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003907 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003908
3909 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3910 mix.mDeviceType, mix.mDeviceAddress,
3911 String8(), AUDIO_FORMAT_DEFAULT);
3912 if (device == nullptr) {
3913 res = INVALID_OPERATION;
3914 break;
3915 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003916
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003917 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003918 // First try to find an already opened output supporting the device
3919 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003920 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003921
Eric Laurentc529cf62020-04-17 18:19:10 -07003922 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003923 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003924 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003925 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003926 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003927 } else {
3928 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003929 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003930 }
3931 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003932 // If no output found, try to find a direct output profile supporting the device
3933 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3934 sp<HwModule> module = mHwModules[i];
3935 for (size_t j = 0;
3936 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3937 j++) {
3938 sp<IOProfile> profile = module->getOutputProfiles()[j];
3939 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3940 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3941 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003942 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003943 res = INVALID_OPERATION;
3944 } else {
3945 foundOutput = true;
3946 }
3947 }
3948 }
3949 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003950 if (res != NO_ERROR) {
3951 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003952 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003953 res = INVALID_OPERATION;
3954 break;
3955 } else if (!foundOutput) {
3956 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003957 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003958 res = INVALID_OPERATION;
3959 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003960 } else {
3961 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003962 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003963 }
Eric Laurentc722f302014-12-10 11:21:49 -08003964 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003965 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003966 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003967 if (audio_flags::audio_mix_ownership()) {
3968 // Only unregister mixes that were actually registered to not accidentally unregister
3969 // mixes that already existed previously.
3970 unregisterPolicyMixes(registeredMixes);
3971 registeredMixes.clear();
3972 } else {
3973 unregisterPolicyMixes(mixes);
3974 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003975 } else if (checkOutputs) {
3976 checkForDeviceAndOutputChanges();
3977 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003978 }
3979 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003980}
3981
3982status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3983{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003984 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003985 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003986 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003987 sp<HwModule> rSubmixModule;
3988 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003989 for (const auto& mix : mixes) {
3990 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003991
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003992 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003993 rSubmixModule = mHwModules.getModuleFromName(
3994 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3995 if (rSubmixModule == 0) {
3996 res = INVALID_OPERATION;
3997 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003998 }
3999 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004000
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004001 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004002
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004003 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004004 res = INVALID_OPERATION;
4005 continue;
4006 }
4007
Marvin Ramin0783e202024-03-05 12:45:50 +01004008 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004009 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004010 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4011 status_t currentRes =
4012 setDeviceConnectionStateInt(device,
4013 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4014 address.c_str(),
4015 "remote-submix",
4016 AUDIO_FORMAT_DEFAULT);
4017 if (!audio_flags::audio_mix_ownership()) {
4018 res = currentRes;
4019 }
4020 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004021 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004022 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004023 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004024 }
4025 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004026 }
jiabin5740f082019-08-19 15:08:30 -07004027 rSubmixModule->removeOutputProfile(address.c_str());
4028 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004029
Kevin Rocard153f92d2018-12-18 18:33:28 -08004030 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004031 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004032 res = INVALID_OPERATION;
4033 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004034 } else {
4035 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004036 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004037 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004038 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004039
4040 if (res == NO_ERROR && checkOutputs) {
4041 checkForDeviceAndOutputChanges();
4042 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004043 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004044 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004045}
4046
Marvin Raminbdefaf02023-11-01 09:10:32 +01004047status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4048 if (!audio_flags::audio_mix_test_api()) {
4049 return INVALID_OPERATION;
4050 }
4051
4052 _aidl_return.clear();
4053 _aidl_return.reserve(mPolicyMixes.size());
4054 for (const auto &policyMix: mPolicyMixes) {
4055 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4056 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4057 policyMix->mCbFlags);
4058 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004059 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004060 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004061 }
4062
Vlad Popaa5d73f32024-03-08 16:05:38 -08004063 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004064 return OK;
4065}
4066
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004067status_t AudioPolicyManager::updatePolicyMix(
4068 const AudioMix& mix,
4069 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4070 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4071 if (res == NO_ERROR) {
4072 checkForDeviceAndOutputChanges();
4073 updateCallAndOutputRouting();
4074 }
4075 return res;
4076}
4077
Mikhail Naganov100f0122018-11-29 11:22:16 -08004078void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4079{
4080 size_t i = 0;
4081 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4082 for (const auto& fmt : mManualSurroundFormats) {
4083 if (i++ != 0) dst->append(", ");
4084 std::string sfmt;
4085 FormatConverter::toString(fmt, sfmt);
4086 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4087 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4088 }
4089}
4090
Eric Laurentc529cf62020-04-17 18:19:10 -07004091// Returns true if all devices types match the predicate and are supported by one HW module
4092bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004093 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004094 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004095 const char *context,
4096 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004097 for (size_t i = 0; i < devices.size(); i++) {
4098 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004099 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004100 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004101 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004102 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004103 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004104 return false;
4105 }
4106 }
4107 return true;
4108}
4109
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004110void AudioPolicyManager::changeOutputDevicesMuteState(
4111 const AudioDeviceTypeAddrVector& devices) {
4112 ALOGVV("%s() num devices %zu", __func__, devices.size());
4113
4114 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4115 getSoftwareOutputsForDevices(devices);
4116
4117 for (size_t i = 0; i < outputs.size(); i++) {
4118 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4119 DeviceVector prevDevices = outputDesc->devices();
4120 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4121 }
4122}
4123
4124std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4125 const AudioDeviceTypeAddrVector& devices) const
4126{
4127 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4128 DeviceVector deviceDescriptors;
4129 for (size_t j = 0; j < devices.size(); j++) {
4130 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4131 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4132 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4133 ALOGE("%s: device type %#x address %s not supported or not an output device",
4134 __func__, devices[j].mType, devices[j].getAddress());
4135 continue;
4136 }
4137 deviceDescriptors.add(desc);
4138 }
4139 for (size_t i = 0; i < mOutputs.size(); i++) {
4140 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4141 continue;
4142 }
4143 outputs.push_back(mOutputs.valueAt(i));
4144 }
4145 return outputs;
4146}
4147
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004148status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004149 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004150 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004151 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4152 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004153 }
4154 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004155 if (res != NO_ERROR) {
4156 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4157 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004158 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004159
4160 checkForDeviceAndOutputChanges();
4161 updateCallAndOutputRouting();
4162
4163 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004164}
4165
4166status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4167 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004168 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4169 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004170 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004171 __FUNCTION__, uid);
4172 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004173 }
4174
Eric Laurentc529cf62020-04-17 18:19:10 -07004175 checkForDeviceAndOutputChanges();
4176 updateCallAndOutputRouting();
4177
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004178 return res;
4179}
4180
Eric Laurent2517af32020-11-25 15:31:27 +01004181
jiabin0a488932020-08-07 17:32:40 -07004182status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4183 device_role_t role,
4184 const AudioDeviceTypeAddrVector &devices) {
4185 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4186 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004187
Eric Laurentc529cf62020-04-17 18:19:10 -07004188 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004189 return BAD_VALUE;
4190 }
jiabin0a488932020-08-07 17:32:40 -07004191 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004192 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004193 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4194 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004195 return status;
4196 }
4197
4198 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004199
4200 bool forceVolumeReeval = false;
4201 // FIXME: workaround for truncated touch sounds
4202 // to be removed when the problem is handled by system UI
4203 uint32_t delayMs = 0;
4204 if (strategy == mCommunnicationStrategy) {
4205 forceVolumeReeval = true;
4206 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4207 updateInputRouting();
4208 }
4209 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004210
4211 return NO_ERROR;
4212}
4213
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004214void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4215 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004216{
4217 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004218 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004219 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004220 // Only apply special touch sound delay once
4221 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004222 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004223 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004224 for (size_t i = 0; i < mOutputs.size(); i++) {
4225 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4226 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004227 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4228 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004229 // As done in setDeviceConnectionState, we could also fix default device issue by
4230 // preventing the force re-routing in case of default dev that distinguishes on address.
4231 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004232 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004233 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004234 // If the device is using preferred mixer attributes, the output need to reopen
4235 // with default configuration when the new selected devices are different from
4236 // current routing devices.
4237 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4238 continue;
4239 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304240
4241 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4242 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004243 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004244 // Only apply special touch sound delay once
4245 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004246 }
4247 if (forceVolumeReeval && !newDevices.isEmpty()) {
4248 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4249 }
4250 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004251 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004252 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004253}
4254
Eric Laurent2517af32020-11-25 15:31:27 +01004255void AudioPolicyManager::updateInputRouting() {
4256 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304257 // Skip for hotword recording as the input device switch
4258 // is handled within sound trigger HAL
4259 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4260 continue;
4261 }
Eric Laurent2517af32020-11-25 15:31:27 +01004262 auto newDevice = getNewInputDevice(activeDesc);
4263 // Force new input selection if the new device can not be reached via current input
4264 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4265 setInputDevice(activeDesc->mIoHandle, newDevice);
4266 } else {
4267 closeInput(activeDesc->mIoHandle);
4268 }
4269 }
4270}
4271
Paul Wang5d7cdb52022-11-22 09:45:06 +00004272status_t
4273AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4274 device_role_t role,
4275 const AudioDeviceTypeAddrVector &devices) {
4276 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4277 dumpAudioDeviceTypeAddrVector(devices).c_str());
4278
Eric Laurent78fedbf2023-03-09 14:40:44 +01004279 if (!areAllDevicesSupported(
4280 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004281 return BAD_VALUE;
4282 }
4283 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4284 if (status != NO_ERROR) {
4285 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4286 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4287 return status;
4288 }
4289
4290 checkForDeviceAndOutputChanges();
4291
4292 bool forceVolumeReeval = false;
4293 // TODO(b/263479999): workaround for truncated touch sounds
4294 // to be removed when the problem is handled by system UI
4295 uint32_t delayMs = 0;
4296 if (strategy == mCommunnicationStrategy) {
4297 forceVolumeReeval = true;
4298 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4299 updateInputRouting();
4300 }
4301 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4302
4303 return NO_ERROR;
4304}
4305
4306status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4307 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004308{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004309 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004310
Paul Wang5d7cdb52022-11-22 09:45:06 +00004311 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004312 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004313 ALOGW_IF(status != NAME_NOT_FOUND,
4314 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004315 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004316 return status;
4317 }
4318
4319 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004320
4321 bool forceVolumeReeval = false;
4322 // FIXME: workaround for truncated touch sounds
4323 // to be removed when the problem is handled by system UI
4324 uint32_t delayMs = 0;
4325 if (strategy == mCommunnicationStrategy) {
4326 forceVolumeReeval = true;
4327 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4328 updateInputRouting();
4329 }
4330 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004331
4332 return NO_ERROR;
4333}
4334
jiabin0a488932020-08-07 17:32:40 -07004335status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4336 device_role_t role,
4337 AudioDeviceTypeAddrVector &devices) {
4338 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004339}
4340
Jiabin Huang3b98d322020-09-03 17:54:16 +00004341status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4342 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4343 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4344 dumpAudioDeviceTypeAddrVector(devices).c_str());
4345
Mikhail Naganov55773032020-10-01 15:08:13 -07004346 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004347 return BAD_VALUE;
4348 }
4349 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4350 ALOGW_IF(status != NO_ERROR,
4351 "Engine could not set preferred devices %s for audio source %d role %d",
4352 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4353
4354 return status;
4355}
4356
4357status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4358 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4359 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4360 dumpAudioDeviceTypeAddrVector(devices).c_str());
4361
Mikhail Naganov55773032020-10-01 15:08:13 -07004362 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004363 return BAD_VALUE;
4364 }
4365 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4366 ALOGW_IF(status != NO_ERROR,
4367 "Engine could not add preferred devices %s for audio source %d role %d",
4368 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4369
Eric Laurent2517af32020-11-25 15:31:27 +01004370 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004371 return status;
4372}
4373
4374status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4375 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4376{
4377 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4378 dumpAudioDeviceTypeAddrVector(devices).c_str());
4379
Eric Laurent78fedbf2023-03-09 14:40:44 +01004380 if (!areAllDevicesSupported(
4381 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004382 return BAD_VALUE;
4383 }
4384
4385 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4386 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004387 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004388 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004389 if (status == NO_ERROR) {
4390 updateInputRouting();
4391 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004392 return status;
4393}
4394
4395status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4396 device_role_t role) {
4397 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4398
4399 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004400 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004401 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004402 if (status == NO_ERROR) {
4403 updateInputRouting();
4404 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004405 return status;
4406}
4407
4408status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4409 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4410 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4411}
4412
Oscar Azucena90e77632019-11-27 17:12:28 -08004413status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004414 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004415 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004416 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4417 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004418 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004419 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4420 if (status != NO_ERROR) {
4421 ALOGE("%s() could not set device affinity for userId %d",
4422 __FUNCTION__, userId);
4423 return status;
4424 }
4425
4426 // reevaluate outputs for all devices
4427 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004428 changeOutputDevicesMuteState(devices);
4429 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4430 true /* skipDelays */);
4431 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004432
4433 return NO_ERROR;
4434}
4435
4436status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004437 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004438 AudioDeviceTypeAddrVector devices;
4439 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004440 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4441 if (status != NO_ERROR) {
4442 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4443 __FUNCTION__, userId);
4444 return status;
4445 }
4446
4447 // reevaluate outputs for all devices
4448 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004449 changeOutputDevicesMuteState(devices);
4450 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4451 true /* skipDelays */);
4452 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004453
4454 return NO_ERROR;
4455}
4456
Andy Hungc29d82b2018-10-05 12:23:17 -07004457void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004458{
Andy Hungc29d82b2018-10-05 12:23:17 -07004459 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004460 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004461 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004462 std::string stateLiteral;
4463 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004464 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004465 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4466 "communications", "media", "record", "dock", "system",
4467 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4468 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4469 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004470 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4471 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4472 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4473 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4474 dst->append(" (MANUAL: ");
4475 dumpManualSurroundFormats(dst);
4476 dst->append(")");
4477 }
4478 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004479 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004480 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4481 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004482 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004483 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004484
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004485 dst->append("\n");
4486 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4487 dst->append("\n");
4488 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004489 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004490 mOutputs.dump(dst);
4491 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004492 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004493 mAudioPatches.dump(dst);
4494 mPolicyMixes.dump(dst);
4495 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004496
Kevin Rocardb99cc752019-03-21 20:52:24 -07004497 dst->appendFormat(" AllowedCapturePolicies:\n");
4498 for (auto& policy : mAllowedCapturePolicies) {
4499 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4500 }
4501
jiabina84c3d32022-12-02 18:59:55 +00004502 dst->appendFormat(" Preferred mixer audio configuration:\n");
4503 for (const auto it : mPreferredMixerAttrInfos) {
4504 dst->appendFormat(" - device port id: %d\n", it.first);
4505 for (const auto preferredMixerInfoIt : it.second) {
4506 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4507 preferredMixerInfoIt.second->dump(dst);
4508 }
4509 }
4510
François Gaffiec005e562018-11-06 15:04:49 +01004511 dst->appendFormat("\nPolicy Engine dump:\n");
4512 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004513
4514 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4515 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4516 dst->appendFormat(" - device type: %s, driving stream %d\n",
4517 dumpDeviceTypes({it.first}).c_str(),
4518 mEngine->getVolumeGroupForAttributes(it.second));
4519 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004520}
4521
4522status_t AudioPolicyManager::dump(int fd)
4523{
4524 String8 result;
4525 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004526 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004527 return NO_ERROR;
4528}
4529
Kevin Rocardb99cc752019-03-21 20:52:24 -07004530status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4531{
4532 mAllowedCapturePolicies[uid] = capturePolicy;
4533 return NO_ERROR;
4534}
4535
Eric Laurente552edb2014-03-10 17:42:56 -07004536// This function checks for the parameters which can be offloaded.
4537// This can be enhanced depending on the capability of the DSP and policy
4538// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004539audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004540{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004541 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004542 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004543 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004544 offloadInfo.format,
4545 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4546 offloadInfo.has_video);
4547
jiabin2b9d5a12021-12-10 01:06:29 +00004548 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004549 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004550 }
4551
4552 // See if there is a profile to support this.
4553 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004554 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004555 offloadInfo.sample_rate,
4556 offloadInfo.format,
4557 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004558 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4559 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004560 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4561 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4562 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004563 if (profile == nullptr) {
4564 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4565 }
4566 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4567 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4568 }
4569 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004570}
4571
Michael Chana94fbb22018-04-24 14:31:19 +10004572bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4573 const audio_attributes_t& attributes) {
4574 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004575 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004576 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4577 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004578 config.sample_rate,
4579 config.format,
4580 config.channel_mask,
4581 output_flags,
4582 true /* directOnly */);
4583 ALOGV("%s() profile %sfound with name: %s, "
4584 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4585 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004586 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004587 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004588
4589 // also try the MSD module if compatible profile not found
4590 if (profile == nullptr) {
4591 profile = getMsdProfileForOutput(outputDevices,
4592 config.sample_rate,
4593 config.format,
4594 config.channel_mask,
4595 output_flags,
4596 true /* directOnly */);
4597 ALOGV("%s() MSD profile %sfound with name: %s, "
4598 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4599 __FUNCTION__, profile != 0 ? "" : "NOT ",
4600 (profile != 0 ? profile->getTagName().c_str() : "null"),
4601 config.sample_rate, config.format, config.channel_mask, output_flags);
4602 }
4603 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004604}
4605
jiabin2b9d5a12021-12-10 01:06:29 +00004606bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4607 bool durationIgnored) {
4608 if (mMasterMono) {
4609 return false; // no offloading if mono is set.
4610 }
4611
4612 // Check if offload has been disabled
4613 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4614 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4615 return false;
4616 }
4617
4618 // Check if stream type is music, then only allow offload as of now.
4619 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4620 {
4621 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4622 return false;
4623 }
4624
4625 //TODO: enable audio offloading with video when ready
4626 const bool allowOffloadWithVideo =
4627 property_get_bool("audio.offload.video", false /* default_value */);
4628 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4629 ALOGV("%s: has_video == true, returning false", __func__);
4630 return false;
4631 }
4632
4633 //If duration is less than minimum value defined in property, return false
4634 const int min_duration_secs = property_get_int32(
4635 "audio.offload.min.duration.secs", -1 /* default_value */);
4636 if (!durationIgnored) {
4637 if (min_duration_secs >= 0) {
4638 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4639 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4640 __func__, min_duration_secs);
4641 return false;
4642 }
4643 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4644 ALOGV("%s: Offload denied by duration < default min(=%u)",
4645 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4646 return false;
4647 }
4648 }
4649
4650 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4651 // creating an offloaded track and tearing it down immediately after start when audioflinger
4652 // detects there is an active non offloadable effect.
4653 // FIXME: We should check the audio session here but we do not have it in this context.
4654 // This may prevent offloading in rare situations where effects are left active by apps
4655 // in the background.
4656 if (mEffects.isNonOffloadableEffectEnabled()) {
4657 return false;
4658 }
4659
4660 return true;
4661}
4662
4663audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4664 const audio_config_t *config) {
4665 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4666 offloadInfo.format = config->format;
4667 offloadInfo.sample_rate = config->sample_rate;
4668 offloadInfo.channel_mask = config->channel_mask;
4669 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4670 offloadInfo.has_video = false;
4671 offloadInfo.is_streaming = false;
4672 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4673
4674 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4675 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4676 audio_flags_to_audio_output_flags(attr->flags, &flags);
4677 // only retain flags that will drive compressed offload or passthrough
4678 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4679 if (offloadPossible) {
4680 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4681 }
4682 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4683
Dorin Drimusfae3c642022-03-17 18:36:30 +01004684 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004685 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004686 DeviceVector outputDevices = engineOutputDevices;
4687 // the MSD module checks for different conditions and output devices
4688 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4689 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4690 continue;
4691 }
4692 outputDevices = getMsdAudioOutDevices();
4693 }
jiabin2b9d5a12021-12-10 01:06:29 +00004694 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004695 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004696 config->sample_rate, nullptr /*updatedSamplingRate*/,
4697 config->format, nullptr /*updatedFormat*/,
4698 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004699 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004700 continue;
4701 }
4702 // reject profiles not corresponding to a device currently available
4703 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4704 continue;
4705 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004706 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4707 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004708 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004709 != AUDIO_DIRECT_NOT_SUPPORTED) {
4710 // Already reports offload gapless supported. No need to report offload support.
4711 continue;
4712 }
4713 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4714 != AUDIO_OUTPUT_FLAG_NONE) {
4715 // If offload gapless is reported, no need to report offload support.
4716 directMode = (audio_direct_mode_t) ((directMode &
4717 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4718 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4719 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004720 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004721 }
4722 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004723 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004724 }
4725 }
4726 }
4727 return directMode;
4728}
4729
Dorin Drimusf2196d82022-01-03 12:11:18 +01004730status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4731 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004732 if (mEffects.isNonOffloadableEffectEnabled()) {
4733 return OK;
4734 }
jiabinf1c73972022-04-14 16:28:52 -07004735 DeviceVector devices;
4736 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004737 if (status != OK) {
4738 return status;
4739 }
4740 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4741 if (devices.empty()) {
4742 return OK; // no output devices for the attributes
4743 }
jiabinf1c73972022-04-14 16:28:52 -07004744 return getProfilesForDevices(devices, audioProfilesVector,
4745 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004746}
4747
jiabina84c3d32022-12-02 18:59:55 +00004748status_t AudioPolicyManager::getSupportedMixerAttributes(
4749 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4750 ALOGV("%s, portId=%d", __func__, portId);
4751 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4752 if (deviceDescriptor == nullptr) {
4753 ALOGE("%s the requested device is currently unavailable", __func__);
4754 return BAD_VALUE;
4755 }
jiabin96daffc2023-05-11 17:51:55 +00004756 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4757 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4758 deviceDescriptor->type());
4759 return BAD_VALUE;
4760 }
jiabina84c3d32022-12-02 18:59:55 +00004761 for (const auto& hwModule : mHwModules) {
4762 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4763 if (curProfile->supportsDevice(deviceDescriptor)) {
4764 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4765 }
4766 }
4767 }
4768 return NO_ERROR;
4769}
4770
4771status_t AudioPolicyManager::setPreferredMixerAttributes(
4772 const audio_attributes_t *attr,
4773 audio_port_handle_t portId,
4774 uid_t uid,
4775 const audio_mixer_attributes_t *mixerAttributes) {
4776 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4777 "mixerBehavior=%d}, uid=%d, portId=%u",
4778 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4779 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4780 mixerAttributes->mixer_behavior, uid, portId);
4781 if (attr->usage != AUDIO_USAGE_MEDIA) {
4782 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4783 return BAD_VALUE;
4784 }
4785 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4786 if (deviceDescriptor == nullptr) {
4787 ALOGE("%s the requested device is currently unavailable", __func__);
4788 return BAD_VALUE;
4789 }
4790 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4791 ALOGE("%s(%d), type=%d, is not a usb output device",
4792 __func__, portId, deviceDescriptor->type());
4793 return BAD_VALUE;
4794 }
4795
4796 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4797 audio_flags_to_audio_output_flags(attr->flags, &flags);
4798 flags = (audio_output_flags_t) (flags |
4799 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4800 sp<IOProfile> profile = nullptr;
4801 DeviceVector devices(deviceDescriptor);
4802 for (const auto& hwModule : mHwModules) {
4803 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4804 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004805 && curProfile->getCompatibilityScore(
4806 devices,
4807 mixerAttributes->config.sample_rate,
4808 nullptr /*updatedSamplingRate*/,
4809 mixerAttributes->config.format,
4810 nullptr /*updatedFormat*/,
4811 mixerAttributes->config.channel_mask,
4812 nullptr /*updatedChannelMask*/,
4813 flags,
4814 false /*exactMatchRequiredForInputFlags*/)
4815 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004816 profile = curProfile;
4817 break;
4818 }
4819 }
4820 }
4821 if (profile == nullptr) {
4822 ALOGE("%s, there is no compatible profile found", __func__);
4823 return BAD_VALUE;
4824 }
4825
4826 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4827 sp<PreferredMixerAttributesInfo>::make(
4828 uid, portId, profile, flags, *mixerAttributes);
4829 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4830 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4831
4832 // If 1) there is any client from the preferred mixer configuration owner that is currently
4833 // active and matches the strategy and 2) current output is on the preferred device and the
4834 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4835 // configuration.
4836 std::vector<audio_io_handle_t> outputsToReopen;
4837 for (size_t i = 0; i < mOutputs.size(); i++) {
4838 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004839 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4840 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004841 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004842 } else {
4843 for (const auto &client: output->getActiveClients()) {
4844 if (client->uid() == uid && client->strategy() == strategy) {
4845 client->setIsInvalid();
4846 outputsToReopen.push_back(output->mIoHandle);
4847 }
jiabina84c3d32022-12-02 18:59:55 +00004848 }
4849 }
4850 }
4851 }
4852 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4853 config.sample_rate = mixerAttributes->config.sample_rate;
4854 config.channel_mask = mixerAttributes->config.channel_mask;
4855 config.format = mixerAttributes->config.format;
4856 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004857 sp<SwAudioOutputDescriptor> desc =
4858 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4859 if (desc == nullptr) {
4860 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4861 continue;
4862 }
jiabin220eea12024-05-17 17:55:20 +00004863 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004864 }
4865
4866 return NO_ERROR;
4867}
4868
4869sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004870 audio_port_handle_t devicePortId,
4871 product_strategy_t strategy,
4872 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004873 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4874 if (it == mPreferredMixerAttrInfos.end()) {
4875 return nullptr;
4876 }
jiabind9a58d32023-06-01 17:57:30 +00004877 if (activeBitPerfectPreferred) {
4878 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004879 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004880 return info;
4881 }
4882 }
jiabina84c3d32022-12-02 18:59:55 +00004883 }
jiabind9a58d32023-06-01 17:57:30 +00004884 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4885 return strategyMatchedMixerAttrInfoIt == it->second.end()
4886 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004887}
4888
4889status_t AudioPolicyManager::getPreferredMixerAttributes(
4890 const audio_attributes_t *attr,
4891 audio_port_handle_t portId,
4892 audio_mixer_attributes_t* mixerAttributes) {
4893 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4894 portId, mEngine->getProductStrategyForAttributes(*attr));
4895 if (info == nullptr) {
4896 return NAME_NOT_FOUND;
4897 }
4898 *mixerAttributes = info->getMixerAttributes();
4899 return NO_ERROR;
4900}
4901
4902status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4903 audio_port_handle_t portId,
4904 uid_t uid) {
4905 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4906 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4907 if (preferredMixerAttrInfo == nullptr) {
4908 return NAME_NOT_FOUND;
4909 }
4910 if (preferredMixerAttrInfo->getUid() != uid) {
4911 ALOGE("%s, requested uid=%d, owned uid=%d",
4912 __func__, uid, preferredMixerAttrInfo->getUid());
4913 return PERMISSION_DENIED;
4914 }
4915 mPreferredMixerAttrInfos[portId].erase(strategy);
4916 if (mPreferredMixerAttrInfos[portId].empty()) {
4917 mPreferredMixerAttrInfos.erase(portId);
4918 }
4919
4920 // Reconfig existing output
4921 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4922 for (size_t i = 0; i < mOutputs.size(); i++) {
4923 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4924 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4925 }
4926 }
4927 for (const auto output : potentialOutputsToReopen) {
4928 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4929 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4930 preferredMixerAttrInfo->getFlags())) {
4931 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4932 }
4933 }
4934 return NO_ERROR;
4935}
4936
Eric Laurent6a94d692014-05-20 11:18:06 -07004937status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4938 audio_port_type_t type,
4939 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004940 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004941 unsigned int *generation)
4942{
jiabin19cdba52020-11-24 11:28:58 -08004943 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4944 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 return BAD_VALUE;
4946 }
4947 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004948 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 *num_ports = 0;
4950 }
4951
4952 size_t portsWritten = 0;
4953 size_t portsMax = *num_ports;
4954 *num_ports = 0;
4955 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004956 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4957 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004959 for (const auto& dev : mAvailableOutputDevices) {
4960 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004961 continue;
4962 }
4963 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004964 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004965 }
4966 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004968 }
4969 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004970 for (const auto& dev : mAvailableInputDevices) {
4971 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004972 continue;
4973 }
4974 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004975 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004976 }
4977 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 }
4980 }
4981 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4982 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4983 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4984 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4985 }
4986 *num_ports += mInputs.size();
4987 }
4988 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004989 size_t numOutputs = 0;
4990 for (size_t i = 0; i < mOutputs.size(); i++) {
4991 if (!mOutputs[i]->isDuplicated()) {
4992 numOutputs++;
4993 if (portsWritten < portsMax) {
4994 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4995 }
4996 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 }
Eric Laurent84c70242014-06-23 08:46:27 -07004998 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 }
5000 }
jiabina84c3d32022-12-02 18:59:55 +00005001
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005003 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 return NO_ERROR;
5005}
5006
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005007status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5008 std::vector<media::AudioPortFw>* _aidl_return) {
5009 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5010 audio_port_v7 port;
5011 dev->toAudioPort(&port);
5012 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5013 _aidl_return->push_back(std::move(aidlPort));
5014 return OK;
5015 };
5016
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005017 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005018 for (const auto& dev : module->getDeclaredDevices()) {
5019 if (role == media::AudioPortRole::NONE ||
5020 ((role == media::AudioPortRole::SOURCE)
5021 == audio_is_input_device(dev->type()))) {
5022 RETURN_STATUS_IF_ERROR(pushPort(dev));
5023 }
5024 }
5025 }
5026 return OK;
5027}
5028
jiabin19cdba52020-11-24 11:28:58 -08005029status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005030{
Eric Laurent99fcae42018-05-17 16:59:18 -07005031 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5032 return BAD_VALUE;
5033 }
5034 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5035 if (dev != 0) {
5036 dev->toAudioPort(port);
5037 return NO_ERROR;
5038 }
5039 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5040 if (dev != 0) {
5041 dev->toAudioPort(port);
5042 return NO_ERROR;
5043 }
5044 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5045 if (out != 0) {
5046 out->toAudioPort(port);
5047 return NO_ERROR;
5048 }
5049 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5050 if (in != 0) {
5051 in->toAudioPort(port);
5052 return NO_ERROR;
5053 }
5054 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005055}
5056
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005057status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5058 audio_patch_handle_t *handle,
5059 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005060{
François Gaffieafd4cea2019-11-18 15:50:22 +01005061 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 if (handle == NULL || patch == NULL) {
5063 return BAD_VALUE;
5064 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005066 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005067 return BAD_VALUE;
5068 }
5069 // only one source per audio patch supported for now
5070 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005071 return INVALID_OPERATION;
5072 }
Eric Laurent874c42872014-08-08 15:13:39 -07005073 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 return INVALID_OPERATION;
5075 }
Eric Laurent874c42872014-08-08 15:13:39 -07005076 for (size_t i = 0; i < patch->num_sinks; i++) {
5077 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5078 return INVALID_OPERATION;
5079 }
5080 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005081
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005082 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5083 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5084 if (srcDevice == nullptr || sinkDevice == nullptr) {
5085 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5086 return BAD_VALUE;
5087 }
5088 ALOGV("%s between source %s and sink %s", __func__,
5089 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5090 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5091 // Default attributes, default volume priority, not to infer with non raw audio patches.
5092 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5093 const struct audio_port_config *source = &patch->sources[0];
5094 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005095 new SourceClientDescriptor(
5096 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5097 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5098 true);
5099 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005100
5101 status_t status =
5102 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5103
5104 if (status != NO_ERROR) {
5105 return INVALID_OPERATION;
5106 }
5107 mAudioSources.add(portId, sourceDesc);
5108 return NO_ERROR;
5109}
5110
5111status_t AudioPolicyManager::connectAudioSourceToSink(
5112 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5113 const struct audio_patch *patch,
5114 audio_patch_handle_t &handle,
5115 uid_t uid, uint32_t delayMs)
5116{
5117 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5118 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5119 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5120 return INVALID_OPERATION;
5121 }
5122 sourceDesc->connect(handle, sinkDevice);
5123 if (isMsdPatch(handle)) {
5124 return NO_ERROR;
5125 }
5126 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5127 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5128 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5129 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5130 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5131 goto FailurePatchAdded;
5132 }
5133 status = swOutput->start();
5134 if (status != NO_ERROR) {
5135 goto FailureSourceAdded;
5136 }
5137 swOutput->addClient(sourceDesc);
5138 status = startSource(swOutput, sourceDesc, &delayMs);
5139 if (status != NO_ERROR) {
5140 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5141 goto FailureSourceActive;
5142 }
5143 if (delayMs != 0) {
5144 usleep(delayMs * 1000);
5145 }
5146 return NO_ERROR;
5147
5148FailureSourceActive:
5149 swOutput->stop();
5150 releaseOutput(sourceDesc->portId());
5151FailureSourceAdded:
5152 sourceDesc->setSwOutput(nullptr);
5153FailurePatchAdded:
5154 releaseAudioPatchInternal(handle);
5155 return INVALID_OPERATION;
5156}
5157
5158status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5159 audio_patch_handle_t *handle,
5160 uid_t uid, uint32_t delayMs,
5161 const sp<SourceClientDescriptor>& sourceDesc)
5162{
5163 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005164 sp<AudioPatch> patchDesc;
5165 ssize_t index = mAudioPatches.indexOfKey(*handle);
5166
François Gaffieafd4cea2019-11-18 15:50:22 +01005167 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5168 patch->sources[0].role,
5169 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005170#if LOG_NDEBUG == 0
5171 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005172 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5173 patch->sinks[i].role,
5174 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005175 }
5176#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005177
5178 if (index >= 0) {
5179 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005180 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5181 __func__, mUidCached, patchDesc->getUid(), uid);
5182 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 return INVALID_OPERATION;
5184 }
5185 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005186 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 }
5188
5189 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005190 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005192 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005193 return BAD_VALUE;
5194 }
Eric Laurent84c70242014-06-23 08:46:27 -07005195 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5196 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 if (patchDesc != 0) {
5198 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005199 ALOGV("%s source id differs for patch current id %d new id %d",
5200 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005201 return BAD_VALUE;
5202 }
5203 }
Eric Laurent874c42872014-08-08 15:13:39 -07005204 DeviceVector devices;
5205 for (size_t i = 0; i < patch->num_sinks; i++) {
5206 // Only support mix to devices connection
5207 // TODO add support for mix to mix connection
5208 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005209 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005210 return INVALID_OPERATION;
5211 }
5212 sp<DeviceDescriptor> devDesc =
5213 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5214 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005216 return BAD_VALUE;
5217 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005218
jiabin66acc432024-02-06 00:57:36 +00005219 if (outputDesc->mProfile->getCompatibilityScore(
5220 DeviceVector(devDesc),
5221 patch->sources[0].sample_rate,
5222 nullptr, // updatedSamplingRate
5223 patch->sources[0].format,
5224 nullptr, // updatedFormat
5225 patch->sources[0].channel_mask,
5226 nullptr, // updatedChannelMask
5227 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005228 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005229 return INVALID_OPERATION;
5230 }
5231 devices.add(devDesc);
5232 }
5233 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 return INVALID_OPERATION;
5235 }
Eric Laurent874c42872014-08-08 15:13:39 -07005236
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005238 ALOGV("%s setting device %s on output %d",
5239 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305240 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005241 index = mAudioPatches.indexOfKey(*handle);
5242 if (index >= 0) {
5243 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005244 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 }
5246 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005247 patchDesc->setUid(uid);
5248 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005250 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 return INVALID_OPERATION;
5252 }
5253 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5254 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5255 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005256 // only one sink supported when connecting an input device to a mix
5257 if (patch->num_sinks > 1) {
5258 return INVALID_OPERATION;
5259 }
François Gaffie53615e22015-03-19 09:24:12 +01005260 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 if (inputDesc == NULL) {
5262 return BAD_VALUE;
5263 }
5264 if (patchDesc != 0) {
5265 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5266 return BAD_VALUE;
5267 }
5268 }
François Gaffie11d30102018-11-02 16:09:09 +01005269 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005270 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005271 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 return BAD_VALUE;
5273 }
5274
jiabin66acc432024-02-06 00:57:36 +00005275 if (inputDesc->mProfile->getCompatibilityScore(
5276 DeviceVector(device),
5277 patch->sinks[0].sample_rate,
5278 nullptr, /*updatedSampleRate*/
5279 patch->sinks[0].format,
5280 nullptr, /*updatedFormat*/
5281 patch->sinks[0].channel_mask,
5282 nullptr, /*updatedChannelMask*/
5283 // FIXME for the parameter type,
5284 // and the NONE
5285 (audio_output_flags_t)
5286 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 return INVALID_OPERATION;
5288 }
5289 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005291 device->toString().c_str(), inputDesc->mIoHandle);
5292 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 index = mAudioPatches.indexOfKey(*handle);
5294 if (index >= 0) {
5295 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005296 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 }
5298 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005299 patchDesc->setUid(uid);
5300 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005302 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 return INVALID_OPERATION;
5304 }
5305 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5306 // device to device connection
5307 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005308 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 return BAD_VALUE;
5310 }
5311 }
François Gaffie11d30102018-11-02 16:09:09 +01005312 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005314 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005315 return BAD_VALUE;
5316 }
Eric Laurent874c42872014-08-08 15:13:39 -07005317
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 //update source and sink with our own data as the data passed in the patch may
5319 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005320 PatchBuilder patchBuilder;
5321 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005322
5323 // if first sink is to MSD, establish single MSD patch
5324 if (getMsdAudioOutDevices().contains(
5325 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5326 ALOGV("%s patching to MSD", __FUNCTION__);
5327 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5328 goto installPatch;
5329 }
5330
François Gaffieafd4cea2019-11-18 15:50:22 +01005331 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5332 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333
Eric Laurent874c42872014-08-08 15:13:39 -07005334 for (size_t i = 0; i < patch->num_sinks; i++) {
5335 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005336 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005337 return INVALID_OPERATION;
5338 }
François Gaffie11d30102018-11-02 16:09:09 +01005339 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005340 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005341 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005342 return BAD_VALUE;
5343 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 audio_port_config sinkPortConfig = {};
5345 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5346 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005347
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005348 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5349 // volume management purpose (tracking activity)
5350 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5351 // in config XML to reach the sink so that is can be declared as available.
5352 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005353 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005354 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005355 // take care of dynamic routing for SwOutput selection,
5356 audio_attributes_t attributes = sourceDesc->attributes();
5357 audio_stream_type_t stream = sourceDesc->stream();
5358 audio_attributes_t resultAttr;
5359 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5360 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005361 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5362 config.channel_mask =
5363 (audio_channel_mask_get_representation(sourceMask)
5364 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5365 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005366 config.format = sourceDesc->config().format;
5367 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5368 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5369 bool isRequestedDeviceForExclusiveUse = false;
5370 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005371 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005372 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005373 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5374 &stream, sourceDesc->uid(), &config, &flags,
5375 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005376 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005377 if (output == AUDIO_IO_HANDLE_NONE) {
5378 ALOGV("%s no output for device %s",
5379 __FUNCTION__, sinkDevice->toString().c_str());
5380 return INVALID_OPERATION;
5381 }
5382 outputDesc = mOutputs.valueFor(output);
5383 if (outputDesc->isDuplicated()) {
5384 ALOGE("%s output is duplicated", __func__);
5385 return INVALID_OPERATION;
5386 }
François Gaffie7e39df22022-04-26 12:48:49 +02005387 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5388 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005389 } else {
5390 // Same for "raw patches" aka created from createAudioPatch API
5391 SortedVector<audio_io_handle_t> outputs =
5392 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5393 // if the sink device is reachable via an opened output stream, request to
5394 // go via this output stream by adding a second source to the patch
5395 // description
5396 output = selectOutput(outputs);
5397 if (output == AUDIO_IO_HANDLE_NONE) {
5398 ALOGE("%s no output available for internal patch sink", __func__);
5399 return INVALID_OPERATION;
5400 }
5401 outputDesc = mOutputs.valueFor(output);
5402 if (outputDesc->isDuplicated()) {
5403 ALOGV("%s output for device %s is duplicated",
5404 __func__, sinkDevice->toString().c_str());
5405 return INVALID_OPERATION;
5406 }
François Gaffie7e39df22022-04-26 12:48:49 +02005407 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005408 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005409 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005410 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005411 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005412 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005413 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5414 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005415 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5416 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005417 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005418 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005419 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005420 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005421 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005422 return INVALID_OPERATION;
5423 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005424 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005425 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005426 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005427 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005428 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005429 srcMixPortConfig.ext.mix.usecase.stream =
5430 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005431 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5432 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005433 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005434 }
Eric Laurent83b88082014-06-20 18:31:16 -07005435 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005436 }
5437 // TODO: check from routing capabilities in config file and other conflicting patches
5438
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005439installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005440 status_t status = installPatch(
5441 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005442 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005443 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 return INVALID_OPERATION;
5445 }
5446 } else {
5447 return BAD_VALUE;
5448 }
5449 } else {
5450 return BAD_VALUE;
5451 }
5452 return NO_ERROR;
5453}
5454
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005455status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005456{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005457 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005458 ssize_t index = mAudioPatches.indexOfKey(handle);
5459
5460 if (index < 0) {
5461 return BAD_VALUE;
5462 }
5463 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5465 __func__, mUidCached, patchDesc->getUid(), uid);
5466 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 return INVALID_OPERATION;
5468 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005469 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5470 for (size_t i = 0; i < mAudioSources.size(); i++) {
5471 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5472 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5473 portId = sourceDesc->portId();
5474 break;
5475 }
5476 }
5477 return portId != AUDIO_PORT_HANDLE_NONE ?
5478 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005479}
Eric Laurent6a94d692014-05-20 11:18:06 -07005480
François Gaffieafd4cea2019-11-18 15:50:22 +01005481status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005482 uint32_t delayMs,
5483 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005484{
5485 ALOGV("%s patch %d", __func__, handle);
5486 if (mAudioPatches.indexOfKey(handle) < 0) {
5487 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5488 return BAD_VALUE;
5489 }
5490 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005492 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005493 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005494 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005495 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005496 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005497 return BAD_VALUE;
5498 }
5499
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305500 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005501 getNewOutputDevices(outputDesc, true /*fromCache*/),
5502 true,
5503 0,
5504 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005505 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5506 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005507 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005508 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005509 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 return BAD_VALUE;
5511 }
5512 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005513 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005514 true,
5515 NULL);
5516 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005517 status_t status =
5518 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5519 ALOGV("%s patch panel returned %d patchHandle %d",
5520 __func__, status, patchDesc->getAfHandle());
5521 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005522 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005523 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005524 // SW or HW Bridge
5525 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5526 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005527 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005528 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5529 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5530 outputDesc = sourceDesc->swOutput().promote();
5531 }
5532 if (outputDesc == nullptr) {
5533 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5534 // releaseOutput has already called closeOutput in case of direct output
5535 return NO_ERROR;
5536 }
François Gaffie7e39df22022-04-26 12:48:49 +02005537 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005538 // While using a HwBridge, force reconsidering device only if not reusing an existing
5539 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005540 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005541 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5542 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5543 // Reconsider device only for cases:
5544 // 1 / Active Output
5545 // 2 / Inactive Output previously hosting HwBridge
5546 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5547 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5548 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305549 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005550 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5551 outputDesc->devices(),
5552 force,
5553 0,
5554 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005555 } else {
5556 return BAD_VALUE;
5557 }
5558 } else {
5559 return BAD_VALUE;
5560 }
5561 return NO_ERROR;
5562}
5563
5564status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5565 struct audio_patch *patches,
5566 unsigned int *generation)
5567{
François Gaffie53615e22015-03-19 09:24:12 +01005568 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005569 return BAD_VALUE;
5570 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005571 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005572 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005573}
5574
Eric Laurente1715a42014-05-20 11:30:42 -07005575status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005576{
Eric Laurente1715a42014-05-20 11:30:42 -07005577 ALOGV("setAudioPortConfig()");
5578
5579 if (config == NULL) {
5580 return BAD_VALUE;
5581 }
5582 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5583 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005584 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5585 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005586 }
5587
Eric Laurenta121f902014-06-03 13:32:54 -07005588 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005589 if (config->type == AUDIO_PORT_TYPE_MIX) {
5590 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005591 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005592 if (outputDesc == NULL) {
5593 return BAD_VALUE;
5594 }
Eric Laurent84c70242014-06-23 08:46:27 -07005595 ALOG_ASSERT(!outputDesc->isDuplicated(),
5596 "setAudioPortConfig() called on duplicated output %d",
5597 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005598 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005599 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005600 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005601 if (inputDesc == NULL) {
5602 return BAD_VALUE;
5603 }
Eric Laurenta121f902014-06-03 13:32:54 -07005604 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005605 } else {
5606 return BAD_VALUE;
5607 }
5608 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5609 sp<DeviceDescriptor> deviceDesc;
5610 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5611 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5612 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5613 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5614 } else {
5615 return BAD_VALUE;
5616 }
5617 if (deviceDesc == NULL) {
5618 return BAD_VALUE;
5619 }
Eric Laurenta121f902014-06-03 13:32:54 -07005620 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005621 } else {
5622 return BAD_VALUE;
5623 }
5624
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005625 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005626 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5627 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005628 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005629 audioPortConfig->toAudioPortConfig(&newConfig, config);
5630 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005631 }
Eric Laurenta121f902014-06-03 13:32:54 -07005632 if (status != NO_ERROR) {
5633 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005634 }
Eric Laurente1715a42014-05-20 11:30:42 -07005635
5636 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005637}
5638
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005639void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5640{
Eric Laurentd60560a2015-04-10 11:31:20 -07005641 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005642 clearAudioPatches(uid);
5643 clearSessionRoutes(uid);
5644}
5645
Eric Laurent6a94d692014-05-20 11:18:06 -07005646void AudioPolicyManager::clearAudioPatches(uid_t uid)
5647{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005648 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005649 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005650 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005651 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005652 }
5653 }
5654}
5655
François Gaffiec005e562018-11-06 15:04:49 +01005656void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005657{
François Gaffiec005e562018-11-06 15:04:49 +01005658 // Take the first attributes following the product strategy as it is used to retrieve the routed
5659 // device. All attributes wihin a strategy follows the same "routing strategy"
5660 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5661 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005662 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005663 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005664 for (size_t j = 0; j < mOutputs.size(); j++) {
5665 if (mOutputs.keyAt(j) == ouptutToSkip) {
5666 continue;
5667 }
5668 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005669 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005670 continue;
5671 }
5672 // If the default device for this strategy is on another output mix,
5673 // invalidate all tracks in this strategy to force re connection.
5674 // Otherwise select new device on the output mix.
5675 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005676 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005677 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005678 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005679 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005680 // If the device is using preferred mixer attributes, the output need to reopen
5681 // with default configuration when the new selected devices are different from
5682 // current routing devices.
5683 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5684 continue;
5685 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305686 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005687 }
5688 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005689 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005690}
5691
5692void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5693{
5694 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005695 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005696 for (size_t i = 0; i < mOutputs.size(); i++) {
5697 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005698 for (const auto& client : outputDesc->getClientIterable()) {
5699 if (client->hasPreferredDevice() && client->uid() == uid) {
5700 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005701 auto clientStrategy = client->strategy();
5702 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5703 end(affectedStrategies)) {
5704 continue;
5705 }
5706 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005707 }
5708 }
5709 }
5710 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005711 for (const auto& strategy : affectedStrategies) {
5712 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005713 }
5714
5715 // remove input routes associated with this uid
5716 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005717 for (size_t i = 0; i < mInputs.size(); i++) {
5718 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005719 for (const auto& client : inputDesc->getClientIterable()) {
5720 if (client->hasPreferredDevice() && client->uid() == uid) {
5721 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5722 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005723 }
5724 }
5725 }
5726 // reroute inputs if necessary
5727 SortedVector<audio_io_handle_t> inputsToClose;
5728 for (size_t i = 0; i < mInputs.size(); i++) {
5729 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005730 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005731 inputsToClose.add(inputDesc->mIoHandle);
5732 }
5733 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005734 for (const auto& input : inputsToClose) {
5735 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005736 }
5737}
5738
Eric Laurentd60560a2015-04-10 11:31:20 -07005739void AudioPolicyManager::clearAudioSources(uid_t uid)
5740{
5741 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005742 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5743 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005744 stopAudioSource(mAudioSources.keyAt(i));
5745 }
5746 }
5747}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005748
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005749status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5750 audio_io_handle_t *ioHandle,
5751 audio_devices_t *device)
5752{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005753 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5754 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005755 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005756 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5757 if (deviceDesc == nullptr) {
5758 return INVALID_OPERATION;
5759 }
5760 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005761
François Gaffiedf372692015-03-19 10:43:27 +01005762 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005763}
5764
Eric Laurentd60560a2015-04-10 11:31:20 -07005765status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005766 const audio_attributes_t *attributes,
5767 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005768 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005769{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005770 ALOGV("%s", __FUNCTION__);
5771 *portId = AUDIO_PORT_HANDLE_NONE;
5772
5773 if (source == NULL || attributes == NULL || portId == NULL) {
5774 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5775 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005776 return BAD_VALUE;
5777 }
5778
Eric Laurentd60560a2015-04-10 11:31:20 -07005779 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5780 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005781 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5782 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005783 return INVALID_OPERATION;
5784 }
5785
François Gaffie11d30102018-11-02 16:09:09 +01005786 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005787 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005788 String8(source->ext.device.address),
5789 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005790 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005791 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005792 return BAD_VALUE;
5793 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005794
jiabin4ef93452019-09-10 14:29:54 -07005795 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005796
François Gaffieaaac0fd2018-11-22 17:56:39 +01005797 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005798 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005799 mEngine->getStreamTypeForAttributes(*attributes),
5800 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005801 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005802
5803 status_t status = connectAudioSource(sourceDesc);
5804 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005805 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005806 }
5807 return status;
5808}
5809
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005810status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005811{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005812 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005813
5814 // make sure we only have one patch per source.
5815 disconnectAudioSource(sourceDesc);
5816
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005817 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005818 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5819 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5820 sourceDesc->srcDevice()->type(),
5821 String8(sourceDesc->srcDevice()->address().c_str()),
5822 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005823 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005824 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005825 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005826 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005827 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5828 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5829 return INVALID_OPERATION;
5830 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005831 PatchBuilder patchBuilder;
5832 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5833 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005834
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005835 return connectAudioSourceToSink(
5836 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005837}
5838
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005839status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005840{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005841 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5842 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005843 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005844 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005845 return BAD_VALUE;
5846 }
5847 status_t status = disconnectAudioSource(sourceDesc);
5848
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005849 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005850 return status;
5851}
5852
Andy Hung2ddee192015-12-18 17:34:44 -08005853status_t AudioPolicyManager::setMasterMono(bool mono)
5854{
5855 if (mMasterMono == mono) {
5856 return NO_ERROR;
5857 }
5858 mMasterMono = mono;
5859 // if enabling mono we close all offloaded devices, which will invalidate the
5860 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5861 // for recreating the new AudioTrack as non-offloaded PCM.
5862 //
5863 // If disabling mono, we leave all tracks as is: we don't know which clients
5864 // and tracks are able to be recreated as offloaded. The next "song" should
5865 // play back offloaded.
5866 if (mMasterMono) {
5867 Vector<audio_io_handle_t> offloaded;
5868 for (size_t i = 0; i < mOutputs.size(); ++i) {
5869 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5870 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5871 offloaded.push(desc->mIoHandle);
5872 }
5873 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005874 for (const auto& handle : offloaded) {
5875 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005876 }
5877 }
5878 // update master mono for all remaining outputs
5879 for (size_t i = 0; i < mOutputs.size(); ++i) {
5880 updateMono(mOutputs.keyAt(i));
5881 }
5882 return NO_ERROR;
5883}
5884
5885status_t AudioPolicyManager::getMasterMono(bool *mono)
5886{
5887 *mono = mMasterMono;
5888 return NO_ERROR;
5889}
5890
Eric Laurentac9cef52017-06-09 15:46:26 -07005891float AudioPolicyManager::getStreamVolumeDB(
5892 audio_stream_type_t stream, int index, audio_devices_t device)
5893{
jiabin9a3361e2019-10-01 09:38:30 -07005894 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005895}
5896
jiabin81772902018-04-02 17:52:27 -07005897status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5898 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005899 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005900{
Kriti Dang6537def2021-03-02 13:46:59 +01005901 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5902 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005903 return BAD_VALUE;
5904 }
Kriti Dang6537def2021-03-02 13:46:59 +01005905 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5906 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005907
5908 size_t formatsWritten = 0;
5909 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005910
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005911 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005912 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5913 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005914 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005915 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005916 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005917 bool formatEnabled = true;
5918 switch (forceUse) {
5919 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005920 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005921 break;
5922 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5923 formatEnabled = false;
5924 break;
5925 default: // AUTO or ALWAYS => true
5926 break;
jiabin81772902018-04-02 17:52:27 -07005927 }
5928 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5929 }
jiabin81772902018-04-02 17:52:27 -07005930 }
5931 return NO_ERROR;
5932}
5933
Kriti Dang6537def2021-03-02 13:46:59 +01005934status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5935 audio_format_t *surroundFormats) {
5936 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5937 return BAD_VALUE;
5938 }
5939 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5940 __func__, *numSurroundFormats, surroundFormats);
5941
5942 size_t formatsWritten = 0;
5943 size_t formatsMax = *numSurroundFormats;
5944 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5945
5946 // Return formats from all device profiles that have already been resolved by
5947 // checkOutputsForDevice().
5948 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5949 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5950 audio_devices_t deviceType = device->type();
5951 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5952 // returns formats reported by HDMI devices.
5953 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5954 continue;
5955 }
5956 // Formats reported by sink devices
5957 std::unordered_set<audio_format_t> formatset;
5958 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5959 formatset.insert(it->second.begin(), it->second.end());
5960 }
5961
5962 // Formats hard-coded in the in policy configuration file (if any).
5963 FormatVector encodedFormats = device->encodedFormats();
5964 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5965 // Filter the formats which are supported by the vendor hardware.
5966 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005967 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005968 formats.insert(*it);
5969 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005970 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005971 if (pair.second.count(*it) != 0) {
5972 formats.insert(pair.first);
5973 break;
5974 }
5975 }
5976 }
5977 }
5978 }
5979 *numSurroundFormats = formats.size();
5980 for (const auto& format: formats) {
5981 if (formatsWritten < formatsMax) {
5982 surroundFormats[formatsWritten++] = format;
5983 }
5984 }
5985 return NO_ERROR;
5986}
5987
jiabin81772902018-04-02 17:52:27 -07005988status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5989{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005990 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005991 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5992 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005993 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005994 return BAD_VALUE;
5995 }
5996
Mikhail Naganov100f0122018-11-29 11:22:16 -08005997 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5998 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005999 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006000 return INVALID_OPERATION;
6001 }
6002
Mikhail Naganov100f0122018-11-29 11:22:16 -08006003 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006004 return NO_ERROR;
6005 }
6006
Mikhail Naganov100f0122018-11-29 11:22:16 -08006007 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006008 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006009 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006010 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006011 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006012 }
6013 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006014 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006015 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006016 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006017 }
6018 }
6019
6020 sp<SwAudioOutputDescriptor> outputDesc;
6021 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006022 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6023 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006024 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6025 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006026 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006027 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006028 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6029 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6030 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006031 name.c_str(),
6032 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006033 if (status != NO_ERROR) {
6034 continue;
6035 }
6036 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6037 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6038 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006039 name.c_str(),
6040 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006041 profileUpdated |= (status == NO_ERROR);
6042 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006043 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006044 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006045 AUDIO_DEVICE_IN_HDMI);
6046 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6047 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006048 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006049 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006050 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6051 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6052 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006053 name.c_str(),
6054 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006055 if (status != NO_ERROR) {
6056 continue;
6057 }
6058 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6059 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6060 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006061 name.c_str(),
6062 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006063 profileUpdated |= (status == NO_ERROR);
6064 }
6065
jiabin81772902018-04-02 17:52:27 -07006066 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006067 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006068 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006069 }
6070
6071 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6072}
6073
Eric Laurent5ada82e2019-08-29 17:53:54 -07006074void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006075{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006076 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006077 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006078 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006079 }
6080}
6081
jiabin6012f912018-11-02 17:06:30 -07006082bool AudioPolicyManager::isHapticPlaybackSupported()
6083{
6084 for (const auto& hwModule : mHwModules) {
6085 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6086 for (const auto &outProfile : outputProfiles) {
6087 struct audio_port audioPort;
6088 outProfile->toAudioPort(&audioPort);
6089 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6090 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6091 return true;
6092 }
6093 }
6094 }
6095 }
6096 return false;
6097}
6098
Carter Hsu325a8eb2022-01-19 19:56:51 +08006099bool AudioPolicyManager::isUltrasoundSupported()
6100{
6101 bool hasUltrasoundOutput = false;
6102 bool hasUltrasoundInput = false;
6103 for (const auto& hwModule : mHwModules) {
6104 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6105 if (!hasUltrasoundOutput) {
6106 for (const auto &outProfile : outputProfiles) {
6107 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6108 hasUltrasoundOutput = true;
6109 break;
6110 }
6111 }
6112 }
6113
6114 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6115 if (!hasUltrasoundInput) {
6116 for (const auto &inputProfile : inputProfiles) {
6117 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6118 hasUltrasoundInput = true;
6119 break;
6120 }
6121 }
6122 }
6123
6124 if (hasUltrasoundOutput && hasUltrasoundInput)
6125 return true;
6126 }
6127 return false;
6128}
6129
Atneya Nair698f5ef2022-12-15 16:15:09 -08006130bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6131{
6132 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6133 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6134 for (const auto& hwModule : mHwModules) {
6135 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6136 for (const auto &inputProfile : inputProfiles) {
6137 if ((inputProfile->getFlags() & mask) == mask) {
6138 return true;
6139 }
6140 }
6141 }
6142 return false;
6143}
6144
Eric Laurent8340e672019-11-06 11:01:08 -08006145bool AudioPolicyManager::isCallScreenModeSupported()
6146{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006147 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006148}
6149
6150
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006151status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006152{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006153 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006154 if (!sourceDesc->isConnected()) {
6155 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6156 return NO_ERROR;
6157 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006158 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6159 if (swOutput != 0) {
6160 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006161 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006162 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006163 }
jiabinbce0c1d2020-10-05 11:20:18 -07006164 if (releaseOutput(sourceDesc->portId())) {
6165 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6166 // no need to release audio patch here but just return NO_ERROR.
6167 return NO_ERROR;
6168 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006169 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006170 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006171 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006172 // close Hwoutput and remove from mHwOutputs
6173 } else {
6174 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6175 }
6176 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006177 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006178 sourceDesc->disconnect();
6179 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006180}
6181
François Gaffiec005e562018-11-06 15:04:49 +01006182sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6183 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006184{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006185 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006186 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006187 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006188 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006189 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6190 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006191 source = sourceDesc;
6192 break;
6193 }
6194 }
6195 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006196}
6197
Eric Laurentb4f42a92022-01-17 17:37:31 +01006198bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006199 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006200 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006201{
6202 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6203 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006204 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006205 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006206 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6207 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6208 return false;
6209 }
6210 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6211 return false;
6212 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006213 }
6214
Eric Laurentd332bc82023-08-04 11:45:23 +02006215 // The caller can have the audio config criteria ignored by either passing a null ptr or
6216 // the AUDIO_CONFIG_INITIALIZER value.
6217 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006218 // some positional channel masks and PCM format and for stereo if low latency performance
6219 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006220
6221 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006222 static const bool stereo_spatialization_enabled =
6223 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006224 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006225 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006226 ? audio_channel_mask_contains_stereo(config->channel_mask)
6227 : audio_is_channel_mask_spatialized(config->channel_mask);
6228 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006229 return false;
6230 }
6231 if (!audio_is_linear_pcm(config->format)) {
6232 return false;
6233 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006234 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6235 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6236 return false;
6237 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006238 }
6239
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006240 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006241 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006242 if (profile == nullptr) {
6243 return false;
6244 }
6245
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006246 return true;
6247}
6248
Shunkai Yao4c3af932024-04-26 04:12:21 +00006249// The Spatializer output is compatible with Haptic use cases if:
6250// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6251// with client if client haptic channel bits were set, or
6252// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6253// including the haptic bits or creating the HapticGenerator effect for same session.
6254bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6255 const audio_config_t* config, audio_session_t sessionId) const {
6256 const auto clientHapticChannel =
6257 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6258 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6259 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6260
6261 if (threadOutputHapticChannel) {
6262 // check format and sampleRate match if client haptic channel mask exist
6263 if (clientHapticChannel) {
6264 return mSpatializerOutput->getFormat() == config->format &&
6265 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6266 }
6267 return true;
6268 } else {
6269 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6270 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6271 // HapticGenerator effect for this session) are not supported.
6272 return clientHapticChannel == 0 &&
6273 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6274 }
6275}
6276
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006277void AudioPolicyManager::checkVirtualizerClientRoutes() {
6278 std::set<audio_stream_type_t> streamsToInvalidate;
6279 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006280 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6281 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006282 audio_attributes_t attr = client->attributes();
6283 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6284 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6285 audio_config_base_t clientConfig = client->config();
6286 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006287 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006288 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006289 streamsToInvalidate.insert(client->stream());
6290 }
6291 }
6292 }
6293
jiabinc44b3462022-12-08 12:52:31 -08006294 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006295}
6296
Eric Laurente191d1b2022-04-15 11:59:25 +02006297
6298bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6299 const sp<SwAudioOutputDescriptor>& outputDesc) {
6300 if (outputDesc->isDuplicated()) {
6301 return false;
6302 }
6303 DeviceVector devices = outputDesc->supportedDevices();
6304 for (size_t i = 0; i < mOutputs.size(); i++) {
6305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6306 if (desc == outputDesc || desc->isDuplicated()) {
6307 continue;
6308 }
6309 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6310 if (!sharedDevices.isEmpty()
6311 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6312 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6313 return false;
6314 }
6315 }
6316 return true;
6317}
6318
6319
Eric Laurentfa0f6742021-08-17 18:39:44 +02006320status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006321 const audio_attributes_t *attr,
6322 audio_io_handle_t *output) {
6323 *output = AUDIO_IO_HANDLE_NONE;
6324
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006325 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6326 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6327 audio_config_t *configPtr = nullptr;
6328 audio_config_t config;
6329 if (mixerConfig != nullptr) {
6330 config = audio_config_initializer(mixerConfig);
6331 configPtr = &config;
6332 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006333 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006334 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006335 return BAD_VALUE;
6336 }
6337
6338 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006339 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006340 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006341 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006342 return BAD_VALUE;
6343 }
6344
Eric Laurente191d1b2022-04-15 11:59:25 +02006345 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006346 for (size_t i = 0; i < mOutputs.size(); i++) {
6347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006348 if (!desc->isDuplicated()
6349 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6350 spatializerOutputs.push_back(desc);
6351 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006352 }
6353 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006354 mSpatializerOutput.clear();
6355 bool outputsChanged = false;
6356 for (const auto& desc : spatializerOutputs) {
6357 if (desc->mProfile == profile
6358 && (configPtr == nullptr
6359 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6360 mSpatializerOutput = desc;
6361 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6362 } else {
6363 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6364 " and devices %s", __func__, desc->mIoHandle,
6365 configPtr != nullptr ? configPtr->channel_mask : 0,
6366 devices.toString().c_str());
6367 closeOutput(desc->mIoHandle);
6368 outputsChanged = true;
6369 }
Eric Laurent39095982021-08-24 18:29:27 +02006370 }
6371
Eric Laurente191d1b2022-04-15 11:59:25 +02006372 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006373 sp<SwAudioOutputDescriptor> desc =
6374 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006375 if (desc != nullptr) {
6376 mSpatializerOutput = desc;
6377 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006378 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006379 }
6380
6381 checkVirtualizerClientRoutes();
6382
Eric Laurente191d1b2022-04-15 11:59:25 +02006383 if (outputsChanged) {
6384 mPreviousOutputs = mOutputs;
6385 mpClientInterface->onAudioPortListUpdate();
6386 }
6387
6388 if (mSpatializerOutput == nullptr) {
6389 ALOGV("%s could not open spatializer output with requested config", __func__);
6390 return BAD_VALUE;
6391 }
Eric Laurent39095982021-08-24 18:29:27 +02006392 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006393 ALOGV("%s returning new spatializer output %d", __func__, *output);
6394 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006395}
6396
Eric Laurentfa0f6742021-08-17 18:39:44 +02006397status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6398 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006399 return INVALID_OPERATION;
6400 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006401 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006402 return BAD_VALUE;
6403 }
Eric Laurent39095982021-08-24 18:29:27 +02006404
Eric Laurente191d1b2022-04-15 11:59:25 +02006405 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6406 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6407 closeOutput(mSpatializerOutput->mIoHandle);
6408 //from now on mSpatializerOutput is null
6409 checkVirtualizerClientRoutes();
6410 }
Eric Laurent39095982021-08-24 18:29:27 +02006411
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006412 return NO_ERROR;
6413}
6414
Eric Laurente552edb2014-03-10 17:42:56 -07006415// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006416// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006417// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006418uint32_t AudioPolicyManager::nextAudioPortGeneration()
6419{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006420 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006421}
6422
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006423AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006424 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006425 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006426 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006427 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006428 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006429 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006430 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006431 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006432 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006433 mAudioPortGeneration(1),
6434 mBeaconMuteRefCount(0),
6435 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006436 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006437 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006438 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006439 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006440{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006441}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006442
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006443status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006444 if (mEngine == nullptr) {
6445 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006446 }
6447 mEngine->setObserver(this);
6448 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006449 if (status != NO_ERROR) {
6450 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6451 return status;
6452 }
François Gaffie2110e042015-03-24 08:41:51 +01006453
jiabin29230182023-04-04 21:02:36 +00006454 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6455 // at the end of this function.
6456 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006457 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6458 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6459
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006460 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006461 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006462 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006463
Eric Laurent3a4311c2014-03-17 12:00:47 -07006464 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006465 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6466 defaultOutputDevice == nullptr ||
6467 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6468 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6469 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006470 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006471 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006472 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006473
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006474 // Silence ALOGV statements
6475 property_set("log.tag." LOG_TAG, "D");
6476
Eric Laurente552edb2014-03-10 17:42:56 -07006477 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006478 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006479}
6480
Eric Laurente0720872014-03-11 09:30:41 -07006481AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006482{
Eric Laurente552edb2014-03-10 17:42:56 -07006483 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006484 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006485 }
6486 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006487 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006488 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006489 mAvailableOutputDevices.clear();
6490 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006491 mOutputs.clear();
6492 mInputs.clear();
6493 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006494 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006495 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006496}
6497
Eric Laurente0720872014-03-11 09:30:41 -07006498status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006499{
Eric Laurent87ffa392015-05-22 10:32:38 -07006500 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006501}
6502
Eric Laurente552edb2014-03-10 17:42:56 -07006503// ---
6504
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006505void AudioPolicyManager::onNewAudioModulesAvailable()
6506{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006507 DeviceVector newDevices;
6508 onNewAudioModulesAvailableInt(&newDevices);
6509 if (!newDevices.empty()) {
6510 nextAudioPortGeneration();
6511 mpClientInterface->onAudioPortListUpdate();
6512 }
6513}
6514
6515void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6516{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006517 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006518 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6519 continue;
6520 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006521 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006522 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6523 handle != AUDIO_MODULE_HANDLE_NONE) {
6524 hwModule->setHandle(handle);
6525 } else {
6526 ALOGW("could not load HW module %s", hwModule->getName());
6527 continue;
6528 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006529 }
6530 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006531 // open all output streams needed to access attached devices.
6532 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006533 // This also validates mAvailableOutputDevices list
6534 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6535 if (!outProfile->canOpenNewIo()) {
6536 ALOGE("Invalid Output profile max open count %u for profile %s",
6537 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6538 continue;
6539 }
6540 if (!outProfile->hasSupportedDevices()) {
6541 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6542 continue;
6543 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006544 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6545 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006546 mTtsOutputAvailable = true;
6547 }
6548
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006549 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006550 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006551 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006552 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6553 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006554 } else {
6555 // choose first device present in profile's SupportedDevices also part of
6556 // mAvailableOutputDevices.
6557 if (availProfileDevices.isEmpty()) {
6558 continue;
6559 }
6560 supportedDevice = availProfileDevices.itemAt(0);
6561 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006562 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006563 continue;
6564 }
6565 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6566 mpClientInterface);
6567 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006568 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6569 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006570 AUDIO_STREAM_DEFAULT,
6571 AUDIO_OUTPUT_FLAG_NONE, &output);
6572 if (status != NO_ERROR) {
6573 ALOGW("Cannot open output stream for devices %s on hw module %s",
6574 supportedDevice->toString().c_str(), hwModule->getName());
6575 continue;
6576 }
6577 for (const auto &device : availProfileDevices) {
6578 // give a valid ID to an attached device once confirmed it is reachable
6579 if (!device->isAttached()) {
6580 device->attach(hwModule);
6581 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006582 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006583 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006584 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6585 }
6586 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006587 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006588 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6589 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006590 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006591 }
Eric Laurent39095982021-08-24 18:29:27 +02006592 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006593 outputDesc->close();
6594 } else {
6595 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306596 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006597 DeviceVector(supportedDevice),
6598 true,
6599 0,
6600 NULL);
6601 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006602 }
6603 // open input streams needed to access attached devices to validate
6604 // mAvailableInputDevices list
6605 for (const auto& inProfile : hwModule->getInputProfiles()) {
6606 if (!inProfile->canOpenNewIo()) {
6607 ALOGE("Invalid Input profile max open count %u for profile %s",
6608 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6609 continue;
6610 }
6611 if (!inProfile->hasSupportedDevices()) {
6612 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6613 continue;
6614 }
6615 // chose first device present in profile's SupportedDevices also part of
6616 // available input devices
6617 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006618 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006619 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006620 ALOGV("%s: Input device list is empty! for profile %s",
6621 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006622 continue;
6623 }
6624 sp<AudioInputDescriptor> inputDesc =
6625 new AudioInputDescriptor(inProfile, mpClientInterface);
6626
6627 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6628 status_t status = inputDesc->open(nullptr,
6629 availProfileDevices.itemAt(0),
6630 AUDIO_SOURCE_MIC,
6631 AUDIO_INPUT_FLAG_NONE,
6632 &input);
6633 if (status != NO_ERROR) {
6634 ALOGW("Cannot open input stream for device %s on hw module %s",
6635 availProfileDevices.toString().c_str(),
6636 hwModule->getName());
6637 continue;
6638 }
6639 for (const auto &device : availProfileDevices) {
6640 // give a valid ID to an attached device once confirmed it is reachable
6641 if (!device->isAttached()) {
6642 device->attach(hwModule);
6643 device->importAudioPortAndPickAudioProfile(inProfile, true);
6644 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006645 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006646 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6647 }
6648 }
6649 inputDesc->close();
6650 }
6651 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006652
6653 // Check if spatializer outputs can be closed until used.
6654 // mOutputs vector never contains duplicated outputs at this point.
6655 std::vector<audio_io_handle_t> outputsClosed;
6656 for (size_t i = 0; i < mOutputs.size(); i++) {
6657 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6658 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6659 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6660 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006661 nextAudioPortGeneration();
6662 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6663 if (index >= 0) {
6664 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6665 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6666 patchDesc->getAfHandle(), 0);
6667 mAudioPatches.removeItemsAt(index);
6668 mpClientInterface->onAudioPatchListUpdate();
6669 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006670 desc->close();
6671 }
6672 }
6673 for (auto output : outputsClosed) {
6674 removeOutput(output);
6675 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006676}
6677
Eric Laurent98e38192018-02-15 18:31:53 -08006678void AudioPolicyManager::addOutput(audio_io_handle_t output,
6679 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006680{
Eric Laurent1c333e22014-05-20 10:48:17 -07006681 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006682 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006683 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006684 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006685 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006686}
6687
François Gaffie53615e22015-03-19 09:24:12 +01006688void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6689{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006690 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6691 ALOGV("%s: removing primary output", __func__);
6692 mPrimaryOutput = nullptr;
6693 }
François Gaffie53615e22015-03-19 09:24:12 +01006694 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006695 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006696}
6697
Eric Laurent98e38192018-02-15 18:31:53 -08006698void AudioPolicyManager::addInput(audio_io_handle_t input,
6699 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006700{
Eric Laurent1c333e22014-05-20 10:48:17 -07006701 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006702 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006703}
Eric Laurente552edb2014-03-10 17:42:56 -07006704
François Gaffie11d30102018-11-02 16:09:09 +01006705status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006706 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006707 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006708{
François Gaffie11d30102018-11-02 16:09:09 +01006709 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006710 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006711 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006712
François Gaffie11d30102018-11-02 16:09:09 +01006713 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006714 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006715 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006716 }
Eric Laurente552edb2014-03-10 17:42:56 -07006717
Eric Laurent3b73df72014-03-11 09:06:29 -07006718 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006719 // first call getAudioPort to get the supported attributes from the HAL
6720 struct audio_port_v7 port = {};
6721 device->toAudioPort(&port);
6722 status_t status = mpClientInterface->getAudioPort(&port);
6723 if (status == NO_ERROR) {
6724 device->importAudioPort(port);
6725 }
6726
6727 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006728 for (size_t i = 0; i < mOutputs.size(); i++) {
6729 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006730 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006731 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006732 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6733 mOutputs.keyAt(i), device->toString().c_str());
6734 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006735 }
6736 }
6737 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006738 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006739 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006740 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6741 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006742 if (profile->supportsDevice(device)) {
6743 profiles.add(profile);
6744 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6745 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006746 }
6747 }
6748 }
6749
Eric Laurent7b279bb2015-12-14 10:18:23 -08006750 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006751
Eric Laurente552edb2014-03-10 17:42:56 -07006752 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006753 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006754 return BAD_VALUE;
6755 }
6756
6757 // open outputs for matching profiles if needed. Direct outputs are also opened to
6758 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6759 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006760 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006761
6762 // nothing to do if one output is already opened for this profile
6763 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006764 for (j = 0; j < outputs.size(); j++) {
6765 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006766 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006767 // matching profile: save the sample rates, format and channel masks supported
6768 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006769 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006770 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006771 }
Eric Laurente552edb2014-03-10 17:42:56 -07006772 break;
6773 }
6774 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006775 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006776 continue;
6777 }
6778
Eric Laurent3974e3b2017-12-07 17:58:43 -08006779 if (!profile->canOpenNewIo()) {
6780 ALOGW("Max Output number %u already opened for this profile %s",
6781 profile->maxOpenCount, profile->getTagName().c_str());
6782 continue;
6783 }
6784
Eric Laurent83efe1c2017-07-09 16:51:08 -07006785 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006786 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006787 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6788 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006789 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006790 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006791 profiles.removeAt(profile_index);
6792 profile_index--;
6793 } else {
6794 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006795 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006796 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006797 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6798 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006799 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006800 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006801
François Gaffie11d30102018-11-02 16:09:09 +01006802 if (device_distinguishes_on_address(deviceType)) {
6803 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6804 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306805 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6806 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006807 }
Eric Laurente552edb2014-03-10 17:42:56 -07006808 ALOGV("checkOutputsForDevice(): adding output %d", output);
6809 }
6810 }
6811
6812 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006813 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006814 return BAD_VALUE;
6815 }
Eric Laurentd4692962014-05-05 18:13:44 -07006816 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006817 // check if one opened output is not needed any more after disconnecting one device
6818 for (size_t i = 0; i < mOutputs.size(); i++) {
6819 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006820 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006821 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006822 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006823 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006824 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006825 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006826 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6827 mOutputs.keyAt(i));
6828 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006829 }
Eric Laurente552edb2014-03-10 17:42:56 -07006830 }
6831 }
Eric Laurentd4692962014-05-05 18:13:44 -07006832 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006833 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006834 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6835 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006836 if (!profile->supportsDevice(device)) {
6837 continue;
6838 }
6839 ALOGV("checkOutputsForDevice(): "
6840 "clearing direct output profile %zu on module %s",
6841 j, hwModule->getName());
6842 profile->clearAudioProfiles();
6843 if (!profile->hasDynamicAudioProfile()) {
6844 continue;
6845 }
6846 // When a device is disconnected, if there is an IOProfile that contains dynamic
6847 // profiles and supports the disconnected device, call getAudioPort to repopulate
6848 // the capabilities of the devices that is supported by the IOProfile.
6849 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6850 if (supportedDevice == device ||
6851 !mAvailableOutputDevices.contains(supportedDevice)) {
6852 continue;
6853 }
6854 struct audio_port_v7 port;
6855 supportedDevice->toAudioPort(&port);
6856 status_t status = mpClientInterface->getAudioPort(&port);
6857 if (status == NO_ERROR) {
6858 supportedDevice->importAudioPort(port);
6859 }
Eric Laurente552edb2014-03-10 17:42:56 -07006860 }
6861 }
6862 }
6863 }
6864 return NO_ERROR;
6865}
6866
François Gaffie11d30102018-11-02 16:09:09 +01006867status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006868 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006869{
François Gaffie11d30102018-11-02 16:09:09 +01006870 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006871 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006872 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006873 }
6874
Eric Laurentd4692962014-05-05 18:13:44 -07006875 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006876 sp<AudioInputDescriptor> desc;
6877
jiabinbf5f4262023-04-12 21:48:34 +00006878 // first call getAudioPort to get the supported attributes from the HAL
6879 struct audio_port_v7 port = {};
6880 device->toAudioPort(&port);
6881 status_t status = mpClientInterface->getAudioPort(&port);
6882 if (status == NO_ERROR) {
6883 device->importAudioPort(port);
6884 }
6885
Eric Laurent0dd51852019-04-19 18:18:58 -07006886 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006887 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006888 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006889 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006890 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006891 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006892 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006893
François Gaffie11d30102018-11-02 16:09:09 +01006894 if (profile->supportsDevice(device)) {
6895 profiles.add(profile);
6896 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6897 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006898 }
6899 }
6900 }
6901
Eric Laurent0dd51852019-04-19 18:18:58 -07006902 if (profiles.isEmpty()) {
6903 ALOGW("%s: No input profile available for device %s",
6904 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006905 return BAD_VALUE;
6906 }
6907
6908 // open inputs for matching profiles if needed. Direct inputs are also opened to
6909 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6910 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6911
Eric Laurent1c333e22014-05-20 10:48:17 -07006912 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006913
Eric Laurentd4692962014-05-05 18:13:44 -07006914 // nothing to do if one input is already opened for this profile
6915 size_t input_index;
6916 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6917 desc = mInputs.valueAt(input_index);
6918 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006919 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006920 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006921 }
Eric Laurentd4692962014-05-05 18:13:44 -07006922 break;
6923 }
6924 }
6925 if (input_index != mInputs.size()) {
6926 continue;
6927 }
6928
Eric Laurent3974e3b2017-12-07 17:58:43 -08006929 if (!profile->canOpenNewIo()) {
6930 ALOGW("Max Input number %u already opened for this profile %s",
6931 profile->maxOpenCount, profile->getTagName().c_str());
6932 continue;
6933 }
6934
Eric Laurentfe231122017-11-17 17:48:06 -08006935 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006936 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006937 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006938
Eric Laurentcf2c0212014-07-25 16:20:43 -07006939 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006940 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006941 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006942 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006943 mpClientInterface->setParameters(input, String8(param));
6944 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006945 }
jiabin12537fc2023-10-12 17:56:08 +00006946 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006947 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006948 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006949 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006950 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006951 }
6952
Eric Laurent0dd51852019-04-19 18:18:58 -07006953 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006954 addInput(input, desc);
6955 }
6956 } // endif input != 0
6957
Eric Laurentcf2c0212014-07-25 16:20:43 -07006958 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006959 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006960 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006961 profiles.removeAt(profile_index);
6962 profile_index--;
6963 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006964 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006965 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006966 }
Eric Laurentd4692962014-05-05 18:13:44 -07006967 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006968
6969 if (checkCloseInput(desc)) {
6970 ALOGV("%s closing input %d", __func__, input);
6971 closeInput(input);
6972 }
Eric Laurentd4692962014-05-05 18:13:44 -07006973 }
6974 } // end scan profiles
6975
6976 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006977 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006978 return BAD_VALUE;
6979 }
6980 } else {
6981 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006982 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006983 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006984 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006985 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006986 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006987 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006988 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006989 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6990 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006991 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006992 }
6993 }
6994 }
6995 } // end disconnect
6996
6997 return NO_ERROR;
6998}
6999
7000
Eric Laurente0720872014-03-11 09:30:41 -07007001void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007002{
7003 ALOGV("closeOutput(%d)", output);
7004
François Gaffie1c878552018-11-22 16:53:21 +01007005 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7006 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007007 ALOGW("closeOutput() unknown output %d", output);
7008 return;
7009 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007010 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007011 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007012
Eric Laurente552edb2014-03-10 17:42:56 -07007013 // look for duplicated outputs connected to the output being removed.
7014 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007015 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7016 if (dupOutput->isDuplicated() &&
7017 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7018 sp<SwAudioOutputDescriptor> remainingOutput =
7019 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007020 // As all active tracks on duplicated output will be deleted,
7021 // and as they were also referenced on the other output, the reference
7022 // count for their stream type must be adjusted accordingly on
7023 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007024 const bool wasActive = remainingOutput->isActive();
7025 // Note: no-op on the closing output where all clients has already been set inactive
7026 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007027 // stop() will be a no op if the output is still active but is needed in case all
7028 // active streams refcounts where cleared above
7029 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007030 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007031 }
Eric Laurente552edb2014-03-10 17:42:56 -07007032 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7033 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7034
7035 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007036 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007037 }
7038 }
7039
Eric Laurent05b90f82014-08-27 15:32:29 -07007040 nextAudioPortGeneration();
7041
François Gaffie1c878552018-11-22 16:53:21 +01007042 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007043 if (index >= 0) {
7044 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007045 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7046 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007047 mAudioPatches.removeItemsAt(index);
7048 mpClientInterface->onAudioPatchListUpdate();
7049 }
7050
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007051 if (closingOutputWasActive) {
7052 closingOutput->stop();
7053 }
François Gaffie1c878552018-11-22 16:53:21 +01007054 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007055 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007056 for (const auto device : closingOutput->devices()) {
7057 device->setPreferredConfig(nullptr);
7058 }
7059 }
Eric Laurente552edb2014-03-10 17:42:56 -07007060
François Gaffie53615e22015-03-19 09:24:12 +01007061 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007062 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007063 if (closingOutput == mSpatializerOutput) {
7064 mSpatializerOutput.clear();
7065 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007066
7067 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7068 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007069 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007070 bool directOutputOpen = false;
7071 for (size_t i = 0; i < mOutputs.size(); i++) {
7072 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7073 directOutputOpen = true;
7074 break;
7075 }
7076 }
7077 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007078 ALOGV("no direct outputs open, reset MSD patches");
7079 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7080 // how output devices for patching are resolved. Avoid by caching and reusing the
7081 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7082 // devices to patch to. This may be complicated by the fact that devices may become
7083 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007084 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007085 }
7086 }
jiabin220eea12024-05-17 17:55:20 +00007087
7088 if (closingOutput->mPreferredAttrInfo != nullptr) {
7089 closingOutput->mPreferredAttrInfo->resetActiveClient();
7090 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007091}
7092
7093void AudioPolicyManager::closeInput(audio_io_handle_t input)
7094{
7095 ALOGV("closeInput(%d)", input);
7096
7097 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7098 if (inputDesc == NULL) {
7099 ALOGW("closeInput() unknown input %d", input);
7100 return;
7101 }
7102
Eric Laurent6a94d692014-05-20 11:18:06 -07007103 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007104
François Gaffie11d30102018-11-02 16:09:09 +01007105 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007106 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007107 if (index >= 0) {
7108 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007109 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7110 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007111 mAudioPatches.removeItemsAt(index);
7112 mpClientInterface->onAudioPatchListUpdate();
7113 }
7114
François Gaffie6ebbce02023-07-19 13:27:53 +02007115 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007116 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007117 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007118
François Gaffie11d30102018-11-02 16:09:09 +01007119 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7120 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007121 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007122 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007123 }
Eric Laurente552edb2014-03-10 17:42:56 -07007124}
7125
François Gaffie11d30102018-11-02 16:09:09 +01007126SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7127 const DeviceVector &devices,
7128 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007129{
7130 SortedVector<audio_io_handle_t> outputs;
7131
François Gaffie11d30102018-11-02 16:09:09 +01007132 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007133 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007134 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007135 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007136 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007137 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007138 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007139 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007140 outputs.add(openOutputs.keyAt(i));
7141 }
7142 }
7143 return outputs;
7144}
7145
Mikhail Naganov37977152018-07-11 15:54:44 -07007146void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7147{
7148 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7149 // output is suspended before any tracks are moved to it
7150 checkA2dpSuspend();
7151 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007152 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007153 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007154 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007155 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007156 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7157 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7158 // configuration changes will ultimately be rerouted correctly. We can still avoid
7159 // unnecessary rerouting by caching and reusing the arguments to
7160 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7161 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007162 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007163 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007164 // an event that changed routing likely occurred, inform upper layers
7165 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007166}
7167
François Gaffiec005e562018-11-06 15:04:49 +01007168bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7169 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007170{
François Gaffiec005e562018-11-06 15:04:49 +01007171 return mEngine->getProductStrategyForAttributes(lAttr) ==
7172 mEngine->getProductStrategyForAttributes(rAttr);
7173}
7174
Francois Gaffieff1eb522020-05-06 18:37:04 +02007175void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7176{
7177 for (size_t i = 0; i < mAudioSources.size(); i++) {
7178 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7179 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007180 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007181 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007182 connectAudioSource(sourceDesc);
7183 }
7184 }
7185}
7186
7187void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7188{
7189 for (size_t i = 0; i < mAudioSources.size(); i++) {
7190 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7191 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7192 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7193 disconnectAudioSource(sourceDesc);
7194 }
7195 }
7196}
7197
François Gaffiec005e562018-11-06 15:04:49 +01007198void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7199{
7200 auto psId = mEngine->getProductStrategyForAttributes(attr);
7201
7202 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7203 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007204
François Gaffie11d30102018-11-02 16:09:09 +01007205 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7206 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007207
Eric Laurentc209fe42020-06-05 18:11:23 -07007208 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007209 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007210 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007211 // take into account dynamic audio policies related changes: if a client is now associated
7212 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007213 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007214 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7215 if (desc->isDuplicated()) {
7216 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007217 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007218 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7219 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7220 continue;
7221 }
7222 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007223 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007224 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7225 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7226 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007227 if (status != OK) {
7228 continue;
7229 }
yucliuf4de36d2020-09-14 14:57:56 -07007230 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007231 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007232 maxLatency = desc->latency();
7233 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007234 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007235 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007236 }
7237 }
7238
Eric Laurent56ed8842022-11-15 16:04:41 +01007239 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007240 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7241 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007242 for (audio_io_handle_t srcOut : srcOutputs) {
7243 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007244 if (desc == nullptr) continue;
7245
7246 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007247 maxLatency = desc->latency();
7248 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007249
Eric Laurent56ed8842022-11-15 16:04:41 +01007250 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007251 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007252 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007253 // a client on a non direct outputs has necessarily a linear PCM format
7254 // so we can call selectOutput() safely
7255 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7256 client->flags(),
7257 client->config().format,
7258 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007259 client->config().sample_rate,
7260 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007261 if (newOutput != srcOut) {
7262 invalidate = true;
7263 break;
7264 }
7265 } else {
7266 sp<IOProfile> profile = getProfileForOutput(newDevices,
7267 client->config().sample_rate,
7268 client->config().format,
7269 client->config().channel_mask,
7270 client->flags(),
7271 true /* directOnly */);
7272 if (profile != desc->mProfile) {
7273 invalidate = true;
7274 break;
7275 }
7276 }
7277 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007278 // mute strategy while moving tracks from one output to another
7279 if (invalidate) {
7280 invalidatedOutputs.push_back(desc);
7281 if (desc->isStrategyActive(psId)) {
7282 setStrategyMute(psId, true, desc);
7283 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7284 newDevices.types());
7285 }
Eric Laurente552edb2014-03-10 17:42:56 -07007286 }
François Gaffiec005e562018-11-06 15:04:49 +01007287 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007288 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007289 connectAudioSource(source);
7290 }
Eric Laurente552edb2014-03-10 17:42:56 -07007291 }
7292
Eric Laurent56ed8842022-11-15 16:04:41 +01007293 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7294 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7295 std::to_string(srcOutputs[0]).c_str(),
7296 std::to_string(dstOutputs[0]).c_str());
7297
François Gaffiec005e562018-11-06 15:04:49 +01007298 // Move effects associated to this stream from previous output to new output
7299 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007300 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007301 }
François Gaffiec005e562018-11-06 15:04:49 +01007302 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007303 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007304 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007305 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007306 desc->setTracksInvalidatedStatusByStrategy(psId);
7307 }
Eric Laurente552edb2014-03-10 17:42:56 -07007308 }
7309 }
7310}
7311
Eric Laurente0720872014-03-11 09:30:41 -07007312void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007313{
François Gaffiec005e562018-11-06 15:04:49 +01007314 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7315 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7316 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007317 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007318 }
Eric Laurente552edb2014-03-10 17:42:56 -07007319}
7320
Kevin Rocard153f92d2018-12-18 18:33:28 -08007321void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007322 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007323 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007324 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007325 for (size_t i = 0; i < mOutputs.size(); i++) {
7326 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7327 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007328 sp<AudioPolicyMix> primaryMix;
7329 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007330 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007331 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7332 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7333 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007334 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7335 for (auto &secondaryMix : secondaryMixes) {
7336 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7337 if (outputDesc != nullptr &&
7338 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7339 secondaryDescs.push_back(outputDesc);
7340 }
7341 }
7342
jiabinc44b3462022-12-08 12:52:31 -08007343 if (status != OK &&
7344 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7345 // When it failed to query secondary output, only invalidate the client that is not
7346 // MMAP. The reason is that MMAP stream will not support secondary output.
7347 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007348 } else if (!std::equal(
7349 client->getSecondaryOutputs().begin(),
7350 client->getSecondaryOutputs().end(),
7351 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007352 if (!audio_is_linear_pcm(client->config().format)) {
7353 // If the format is not PCM, the tracks should be invalidated to get correct
7354 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007355 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007356 } else {
7357 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7358 std::vector<audio_io_handle_t> secondaryOutputIds;
7359 for (const auto &secondaryDesc: secondaryDescs) {
7360 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7361 weakSecondaryDescs.push_back(secondaryDesc);
7362 }
7363 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7364 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007365 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007366 }
7367 }
7368 }
jiabin10a03f12021-05-07 23:46:28 +00007369 if (!trackSecondaryOutputs.empty()) {
7370 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7371 }
jiabinc44b3462022-12-08 12:52:31 -08007372 if (!clientsToInvalidate.empty()) {
7373 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7374 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007375 }
7376}
7377
Eric Laurent2517af32020-11-25 15:31:27 +01007378bool AudioPolicyManager::isScoRequestedForComm() const {
7379 AudioDeviceTypeAddrVector devices;
7380 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7381 for (const auto &device : devices) {
7382 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7383 return true;
7384 }
7385 }
7386 return false;
7387}
7388
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007389bool AudioPolicyManager::isHearingAidUsedForComm() const {
7390 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7391 true /*fromCache*/);
7392 for (const auto &device : devices) {
7393 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7394 return true;
7395 }
7396 }
7397 return false;
7398}
7399
7400
Eric Laurente0720872014-03-11 09:30:41 -07007401void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007402{
François Gaffie53615e22015-03-19 09:24:12 +01007403 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007404 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007405 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007406 return;
7407 }
7408
Eric Laurent3a4311c2014-03-17 12:00:47 -07007409 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007410 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7411 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007412 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007413
7414 // if suspended, restore A2DP output if:
7415 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007416 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007417 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007418 //
Eric Laurentf732e072016-08-03 19:30:28 -07007419 // if not suspended, suspend A2DP output if:
7420 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007421 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007422 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007423 //
7424 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007425 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007426 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007427 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007428 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007429
7430 mpClientInterface->restoreOutput(a2dpOutput);
7431 mA2dpSuspended = false;
7432 }
7433 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007434 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007435 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007436 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007437 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007438
7439 mpClientInterface->suspendOutput(a2dpOutput);
7440 mA2dpSuspended = true;
7441 }
7442 }
7443}
7444
François Gaffie11d30102018-11-02 16:09:09 +01007445DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7446 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007447{
François Gaffiedb1755b2023-09-01 11:50:35 +02007448 if (outputDesc == nullptr) {
7449 return DeviceVector{};
7450 }
François Gaffie11d30102018-11-02 16:09:09 +01007451
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007452 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007453 if (index >= 0) {
7454 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007455 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007456 ALOGV("%s device %s forced by patch %d", __func__,
7457 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7458 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007459 }
7460 }
7461
Dean Wheatley514b4312020-06-17 21:45:00 +10007462 // Do not retrieve engine device for outputs through MSD
7463 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7464 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7465 return outputDesc->devices();
7466 }
7467
Eric Laurent97ac8712018-07-27 18:59:02 -07007468 // Honor explicit routing requests only if no client using default routing is active on this
7469 // input: a specific app can not force routing for other apps by setting a preferred device.
7470 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007471 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007472 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007473 if (device != nullptr) {
7474 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007475 }
7476
François Gaffiea807ef92018-11-05 10:44:33 +01007477 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7478 // of setForceUse / Default Bus device here
7479 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7480 if (device != nullptr) {
7481 return DeviceVector(device);
7482 }
7483
François Gaffiedb1755b2023-09-01 11:50:35 +02007484 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007485 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7486 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307487 auto hasStreamActive = [&](auto stream) {
7488 return hasStream(streams, stream) && isStreamActive(stream, 0);
7489 };
Eric Laurent484e9272018-06-07 17:29:23 -07007490
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307491 auto doGetOutputDevicesForVoice = [&]() {
7492 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007493 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307494 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007495 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7496 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307497 };
7498
7499 // With low-latency playing on speaker, music on WFD, when the first low-latency
7500 // output is stopped, getNewOutputDevices checks for a product strategy
7501 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007502 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307503 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7504 // stream is associated to the output descriptor.
7505 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7506 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7507 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7508 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007509 // Retrieval of devices for voice DL is done on primary output profile, cannot
7510 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007511 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007512 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7513 break;
7514 }
Eric Laurente552edb2014-03-10 17:42:56 -07007515 }
François Gaffiec005e562018-11-06 15:04:49 +01007516 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007517 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007518}
7519
François Gaffie11d30102018-11-02 16:09:09 +01007520sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7521 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007522{
François Gaffie11d30102018-11-02 16:09:09 +01007523 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007524
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007525 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007526 if (index >= 0) {
7527 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007528 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007529 ALOGV("getNewInputDevice() device %s forced by patch %d",
7530 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7531 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007532 }
7533 }
7534
Eric Laurent97ac8712018-07-27 18:59:02 -07007535 // Honor explicit routing requests only if no client using default routing is active on this
7536 // input: a specific app can not force routing for other apps by setting a preferred device.
7537 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007538 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7539 if (device != nullptr) {
7540 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007541 }
7542
Eric Laurentdc95a252018-04-12 12:46:56 -07007543 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007544 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007545 audio_attributes_t attributes;
7546 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007547 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007548 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7549 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007550 attributes = topClient->attributes();
7551 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007552 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007553 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007554 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7555 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007556 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007557 }
7558
Francois Gaffie716e1432019-01-14 16:58:59 +01007559 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7560 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007561 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007562 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007563 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007564 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007565
Eric Laurente552edb2014-03-10 17:42:56 -07007566 return device;
7567}
7568
Eric Laurent794fde22016-03-11 09:50:45 -08007569bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7570 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007571 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007572}
7573
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007574status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007575 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007576 if (devices == nullptr) {
7577 return BAD_VALUE;
7578 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007579
Andy Hung6d23c0f2022-02-16 09:37:15 -08007580 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007581 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7582 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007583 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007584 for (const auto& device : curDevices) {
7585 devices->push_back(device->getDeviceTypeAddr());
7586 }
7587 return NO_ERROR;
7588}
7589
Eric Laurente0720872014-03-11 09:30:41 -07007590void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007591 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007592 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007593 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007594 updateDevicesAndOutputs();
7595 break;
7596 default:
7597 break;
7598 }
7599}
7600
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007601uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007602
7603 // skip beacon mute management if a dedicated TTS output is available
7604 if (mTtsOutputAvailable) {
7605 return 0;
7606 }
7607
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007608 switch(event) {
7609 case STARTING_OUTPUT:
7610 mBeaconMuteRefCount++;
7611 break;
7612 case STOPPING_OUTPUT:
7613 if (mBeaconMuteRefCount > 0) {
7614 mBeaconMuteRefCount--;
7615 }
7616 break;
7617 case STARTING_BEACON:
7618 mBeaconPlayingRefCount++;
7619 break;
7620 case STOPPING_BEACON:
7621 if (mBeaconPlayingRefCount > 0) {
7622 mBeaconPlayingRefCount--;
7623 }
7624 break;
7625 }
7626
7627 if (mBeaconMuteRefCount > 0) {
7628 // any playback causes beacon to be muted
7629 return setBeaconMute(true);
7630 } else {
7631 // no other playback: unmute when beacon starts playing, mute when it stops
7632 return setBeaconMute(mBeaconPlayingRefCount == 0);
7633 }
7634}
7635
7636uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7637 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7638 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7639 // keep track of muted state to avoid repeating mute/unmute operations
7640 if (mBeaconMuted != mute) {
7641 // mute/unmute AUDIO_STREAM_TTS on all outputs
7642 ALOGV("\t muting %d", mute);
7643 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007644 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7645 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7646 ALOGV("\t no tts volume source available");
7647 return 0;
7648 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007649 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007650 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007651 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007652 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007653 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007654 maxLatency = latency;
7655 }
7656 }
7657 mBeaconMuted = mute;
7658 return maxLatency;
7659 }
7660 return 0;
7661}
7662
Eric Laurente0720872014-03-11 09:30:41 -07007663void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007664{
François Gaffiec005e562018-11-06 15:04:49 +01007665 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007666 mPreviousOutputs = mOutputs;
7667}
7668
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007669uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007670 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007671 uint32_t delayMs)
7672{
7673 // mute/unmute strategies using an incompatible device combination
7674 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7675 // if unmuting, unmute only after the specified delay
7676 if (outputDesc->isDuplicated()) {
7677 return 0;
7678 }
7679
7680 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007681 DeviceVector devices = outputDesc->devices();
7682 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007683
François Gaffiec005e562018-11-06 15:04:49 +01007684 auto productStrategies = mEngine->getOrderedProductStrategies();
7685 for (const auto &productStrategy : productStrategies) {
7686 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7687 DeviceVector curDevices =
7688 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7689 curDevices = curDevices.filter(outputDesc->supportedDevices());
7690 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007691 bool doMute = false;
7692
François Gaffiec005e562018-11-06 15:04:49 +01007693 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007694 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007695 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7696 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007697 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007698 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007699 }
Eric Laurent99401132014-05-07 19:48:15 -07007700 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007701 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007702 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007703 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007704 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007705 continue;
7706 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307707 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007708 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7709 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7710 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007711 if (mute) {
7712 // FIXME: should not need to double latency if volume could be applied
7713 // immediately by the audioflinger mixer. We must account for the delay
7714 // between now and the next time the audioflinger thread for this output
7715 // will process a buffer (which corresponds to one buffer size,
7716 // usually 1/2 or 1/4 of the latency).
7717 if (muteWaitMs < desc->latency() * 2) {
7718 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007719 }
7720 }
7721 }
7722 }
7723 }
7724 }
7725
Eric Laurent99401132014-05-07 19:48:15 -07007726 // temporary mute output if device selection changes to avoid volume bursts due to
7727 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007728 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007729 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007730
Eric Laurentdc462862016-07-19 12:29:53 -07007731 if (muteWaitMs < tempMuteWaitMs) {
7732 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007733 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007734
7735 // If recommended duration is defined, replace temporary mute duration to avoid
7736 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7737 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7738 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7739 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7740 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7741
François Gaffieaaac0fd2018-11-22 17:56:39 +01007742 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7743 // make sure that we do not start the temporary mute period too early in case of
7744 // delayed device change
7745 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7746 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007747 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007748 }
7749 }
7750
Eric Laurente552edb2014-03-10 17:42:56 -07007751 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7752 if (muteWaitMs > delayMs) {
7753 muteWaitMs -= delayMs;
7754 usleep(muteWaitMs * 1000);
7755 return muteWaitMs;
7756 }
7757 return 0;
7758}
7759
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307760uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7761 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007762 const DeviceVector &devices,
7763 bool force,
7764 int delayMs,
7765 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007766 bool requiresMuteCheck, bool requiresVolumeCheck,
7767 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007768{
jiabin3ff8d7d2022-12-13 06:27:44 +00007769 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307770 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7771 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7772 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007773 uint32_t muteWaitMs;
7774
7775 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307776 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007777 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307778 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007779 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007780 return muteWaitMs;
7781 }
Eric Laurente552edb2014-03-10 17:42:56 -07007782
7783 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007784 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007785 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007786 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007787
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307788 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7789 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007790
7791 if (!filteredDevices.isEmpty()) {
7792 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007793 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007794
7795 // if the outputs are not materially active, there is no need to mute.
7796 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007797 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007798 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307799 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7800 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007801 muteWaitMs = 0;
7802 }
Eric Laurente552edb2014-03-10 17:42:56 -07007803
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007804 bool outputRouted = outputDesc->isRouted();
7805
Eric Laurent79ea9582020-06-11 18:49:24 -07007806 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7807 // output profile or if new device is not supported AND previous device(s) is(are) still
7808 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007809 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307810 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7811 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007812 // restore previous device after evaluating strategy mute state
7813 outputDesc->setDevices(prevDevices);
7814 return muteWaitMs;
7815 }
7816
Eric Laurente552edb2014-03-10 17:42:56 -07007817 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007818 // the requested device is AUDIO_DEVICE_NONE
7819 // OR the requested device is the same as current device
7820 // AND force is not specified
7821 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007822 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007823 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307824 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7825 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7826 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007827 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307828 ALOGV("%s %s setting same device on routed output, force apply volumes",
7829 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007830 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7831 }
Eric Laurente552edb2014-03-10 17:42:56 -07007832 return muteWaitMs;
7833 }
7834
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307835 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7836 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007837
Eric Laurente552edb2014-03-10 17:42:56 -07007838 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007839 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007840 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007841 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007842 PatchBuilder patchBuilder;
7843 patchBuilder.addSource(outputDesc);
7844 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7845 for (const auto &filteredDevice : filteredDevices) {
7846 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007847 }
7848
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007849 // Add half reported latency to delayMs when muteWaitMs is null in order
7850 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007851 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7852 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7853 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007854 }
Eric Laurente552edb2014-03-10 17:42:56 -07007855
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007856 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7857 if (!skipMuteDelay) {
7858 // update stream volumes according to new device
7859 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7860 }
Eric Laurente552edb2014-03-10 17:42:56 -07007861
7862 return muteWaitMs;
7863}
7864
Eric Laurentc75307b2015-03-17 15:29:32 -07007865status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007866 int delayMs,
7867 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007868{
Eric Laurent6a94d692014-05-20 11:18:06 -07007869 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007870 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7871 return INVALID_OPERATION;
7872 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007873 if (patchHandle) {
7874 index = mAudioPatches.indexOfKey(*patchHandle);
7875 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007876 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007877 }
7878 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007879 return INVALID_OPERATION;
7880 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007881 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007882 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007883 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007884 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007885 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007886 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007887 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007888 return status;
7889}
7890
7891status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007892 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007893 bool force,
7894 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007895{
7896 status_t status = NO_ERROR;
7897
Eric Laurent1f2f2232014-06-02 12:01:23 -07007898 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007899 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7900 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007901
François Gaffie11d30102018-11-02 16:09:09 +01007902 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007903 PatchBuilder patchBuilder;
7904 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007905 // AUDIO_SOURCE_HOTWORD is for internal use only:
7906 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007907 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7908 auto result = usecase;
7909 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7910 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7911 }
7912 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007913 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007914 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007915 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007916 }
7917 }
7918 return status;
7919}
7920
Eric Laurent6a94d692014-05-20 11:18:06 -07007921status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7922 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007923{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007924 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007925 ssize_t index;
7926 if (patchHandle) {
7927 index = mAudioPatches.indexOfKey(*patchHandle);
7928 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007929 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007930 }
7931 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007932 return INVALID_OPERATION;
7933 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007934 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007935 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007936 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007937 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007938 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007939 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007940 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007941 return status;
7942}
7943
François Gaffie11d30102018-11-02 16:09:09 +01007944sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007945 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007946 audio_format_t& format,
7947 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007948 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007949{
7950 // Choose an input profile based on the requested capture parameters: select the first available
7951 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007952 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007953
Atneya Nair0f0a8032022-12-12 16:20:12 -08007954 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7955 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7956 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7957
7958 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007959
jiabin2fd710d2022-05-02 23:20:22 +00007960 for (;;) {
7961 sp<IOProfile> firstInexact = nullptr;
7962 uint32_t updatedSamplingRate = 0;
7963 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7964 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7965 for (const auto& hwModule : mHwModules) {
7966 for (const auto& profile : hwModule->getInputProfiles()) {
7967 // profile->log();
7968 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007969 if (profile->getCompatibilityScore(
7970 DeviceVector(device),
7971 samplingRate,
7972 &updatedSamplingRate,
7973 format,
7974 &updatedFormat,
7975 channelMask,
7976 &updatedChannelMask,
7977 // FIXME ugly cast
7978 (audio_output_flags_t) flags,
7979 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7980 samplingRate = updatedSamplingRate;
7981 format = updatedFormat;
7982 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007983 return profile;
7984 }
jiabin66acc432024-02-06 00:57:36 +00007985 if (firstInexact == nullptr
7986 && profile->getCompatibilityScore(
7987 DeviceVector(device),
7988 samplingRate,
7989 &updatedSamplingRate,
7990 format,
7991 &updatedFormat,
7992 channelMask,
7993 &updatedChannelMask,
7994 // FIXME ugly cast
7995 (audio_output_flags_t) flags,
7996 false /*exactMatchRequiredForInputFlags*/)
7997 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007998 firstInexact = profile;
7999 }
8000 }
8001 }
8002
8003 if (firstInexact != nullptr) {
8004 samplingRate = updatedSamplingRate;
8005 format = updatedFormat;
8006 channelMask = updatedChannelMask;
8007 return firstInexact;
8008 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8009 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8010 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8011 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8012 flags = AUDIO_INPUT_FLAG_NONE;
8013 } else { // fail
8014 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8015 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8016 samplingRate, format, channelMask, oriFlags);
8017 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008018 }
8019 }
jiabin2fd710d2022-05-02 23:20:22 +00008020
8021 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008022}
8023
Vlad Popa87e0e582024-05-20 18:49:20 -07008024float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8025 VolumeSource volumeSource,
8026 int index,
8027 const DeviceTypeSet &deviceTypes)
8028{
8029 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8030 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8031 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8032
8033 if (com_android_media_audio_abs_volume_index_fix()) {
8034 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8035 mAbsoluteVolumeDrivingStreams.end()) {
8036 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8037 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8038 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8039 ALOGD("%s: no group matching with %s", __FUNCTION__,
8040 toString(attributesToDriveAbs).c_str());
8041 return volumeDb;
8042 }
8043
8044 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8045 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8046 if (vsToDriveAbs == volumeSource) {
8047 // attenuation is applied by the abs volume controller
8048 return volumeDbMax;
8049 } else {
8050 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8051 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8052 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8053 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8054 curvesAbs.getVolumeIndexMax());
8055 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8056 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8057 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8058 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8059 return newVolumeDb;
8060 }
8061 }
8062 return volumeDb;
8063 } else {
8064 return volumeDb;
8065 }
8066}
8067
François Gaffieaaac0fd2018-11-22 17:56:39 +01008068float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8069 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008070 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008071 const DeviceTypeSet& deviceTypes,
8072 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008073{
Vlad Popa87e0e582024-05-20 18:49:20 -07008074 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008075 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8076 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8077
8078 if (!computeInternalInteraction) {
8079 return volumeDb;
8080 }
8081
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008082 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8083 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8084 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8085 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008086 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8087 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8088 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8089 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8090 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008091 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008092 mOutputs.isActive(ringVolumeSrc, 0)) {
8093 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008094 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8095 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008096 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008097 }
8098
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008099 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008100 if ((volumeSource != callVolumeSrc && (isInCall() ||
8101 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008102 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008103 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8104 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008105 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8106 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8107 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008108 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008109 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008110 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008111 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008112 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8113 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008114 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008115 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8116 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8117 // programmatically muted.
8118 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8119 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8120 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008121 bool exemptFromCapping =
8122 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8123 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008124 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8125 volumeSource, volumeDb);
8126 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008127 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8128 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8129 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008130 }
8131 }
Eric Laurente552edb2014-03-10 17:42:56 -07008132 // if a headset is connected, apply the following rules to ring tones and notifications
8133 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008134 // - always attenuate notifications volume by 6dB
8135 // - attenuate ring tones volume by 6dB unless music is not playing and
8136 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008137 // - if music is playing, always limit the volume to current music volume,
8138 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008139 if (!Intersection(deviceTypes,
8140 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8141 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008142 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8143 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008144 ((volumeSource == alarmVolumeSrc ||
8145 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008146 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8147 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8148 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008149 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8150 curves.canBeMuted()) {
8151
Eric Laurente552edb2014-03-10 17:42:56 -07008152 // when the phone is ringing we must consider that music could have been paused just before
8153 // by the music application and behave as if music was active if the last music track was
8154 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008155 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8156 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008157 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008158 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008159 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8160 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008161 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008162 float musicVolDb = computeVolume(musicCurves,
8163 musicVolumeSrc,
8164 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008165 musicDevice,
8166 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008167 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8168 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8169 if (volumeDb > minVolDb) {
8170 volumeDb = minVolDb;
8171 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008172 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008173 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8174 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008175 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8176 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8177 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8178 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008179 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008180 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008181 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8182 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008183 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8184 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008185 }
8186 }
jiabin9a3361e2019-10-01 09:38:30 -07008187 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008188 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008189 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008190 }
8191 }
8192
François Gaffie43c73442018-11-08 08:21:55 +01008193 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008194}
8195
Eric Laurent3839bc02018-07-10 18:33:34 -07008196int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008197 VolumeSource fromVolumeSource,
8198 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008199{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008200 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008201 return srcIndex;
8202 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008203 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8204 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008205 float minSrc = (float)srcCurves.getVolumeIndexMin();
8206 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8207 float minDst = (float)dstCurves.getVolumeIndexMin();
8208 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008209
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008210 // preserve mute request or correct range
8211 if (srcIndex < minSrc) {
8212 if (srcIndex == 0) {
8213 return 0;
8214 }
8215 srcIndex = minSrc;
8216 } else if (srcIndex > maxSrc) {
8217 srcIndex = maxSrc;
8218 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008219 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8220}
8221
François Gaffieaaac0fd2018-11-22 17:56:39 +01008222status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8223 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008224 int index,
8225 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008226 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008227 int delayMs,
8228 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008229{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008230 // do not change actual attributes volume if the attributes is muted
8231 if (outputDesc->isMuted(volumeSource)) {
8232 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8233 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008234 return NO_ERROR;
8235 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008236
Eric Laurentae6e88c2024-01-10 14:42:57 +01008237 bool isVoiceVolSrc;
8238 bool isBtScoVolSrc;
8239 if (!isVolumeConsistentForCalls(
8240 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008241 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008242 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008243 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008244 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008245
jiabin9a3361e2019-10-01 09:38:30 -07008246 if (deviceTypes.empty()) {
8247 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008248 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008249 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008250 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008251 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008252
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008253 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8254 ALOGE("invalid volume index range");
8255 return BAD_VALUE;
8256 }
8257
jiabin9a3361e2019-10-01 09:38:30 -07008258 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8259 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008260 // Force VoIP volume to max for bluetooth SCO device except if muted
8261 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008262 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008263 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008264 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008265 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008266 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8267 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008268
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008269 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008270 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008271 }
Eric Laurente552edb2014-03-10 17:42:56 -07008272 return NO_ERROR;
8273}
8274
Eric Laurentae6e88c2024-01-10 14:42:57 +01008275void AudioPolicyManager::setVoiceVolume(
8276 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8277 float voiceVolume;
8278 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8279 // by the headset
8280 if (isVoiceVolSrc) {
8281 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8282 } else {
8283 voiceVolume = index == 0 ? 0.0 : 1.0;
8284 }
8285 if (voiceVolume != mLastVoiceVolume) {
8286 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8287 mLastVoiceVolume = voiceVolume;
8288 }
8289}
8290
8291bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8292 const DeviceTypeSet& deviceTypes,
8293 bool& isVoiceVolSrc,
8294 bool& isBtScoVolSrc,
8295 const char* caller) {
8296 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8297 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8298 const bool isScoRequested = isScoRequestedForComm();
8299 const bool isHAUsed = isHearingAidUsedForComm();
8300
8301 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8302 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8303
8304 if ((callVolSrc != btScoVolSrc) &&
8305 ((isVoiceVolSrc && isScoRequested) ||
8306 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8307 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8308 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8309 volumeSource, isScoRequested ? " " : " not ");
8310 return false;
8311 }
8312 return true;
8313}
8314
Eric Laurentc75307b2015-03-17 15:29:32 -07008315void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008316 const DeviceTypeSet& deviceTypes,
8317 int delayMs,
8318 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008319{
jiabincd510522020-01-22 09:40:55 -08008320 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008321 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8322 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8323 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008324 curves.getVolumeIndex(deviceTypes),
8325 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008326 }
8327}
8328
François Gaffiec005e562018-11-06 15:04:49 +01008329void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8330 bool on,
8331 const sp<AudioOutputDescriptor>& outputDesc,
8332 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008333 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008334{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008335 std::vector<VolumeSource> sourcesToMute;
8336 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8337 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8338 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008339 VolumeSource source = toVolumeSource(attributes, false);
8340 if ((source != VOLUME_SOURCE_NONE) &&
8341 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8342 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008343 sourcesToMute.push_back(source);
8344 }
Eric Laurente552edb2014-03-10 17:42:56 -07008345 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008346 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008347 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008348 }
8349
Eric Laurente552edb2014-03-10 17:42:56 -07008350}
8351
François Gaffieaaac0fd2018-11-22 17:56:39 +01008352void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8353 bool on,
8354 const sp<AudioOutputDescriptor>& outputDesc,
8355 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008356 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008357{
jiabin9a3361e2019-10-01 09:38:30 -07008358 if (deviceTypes.empty()) {
8359 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008360 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008361 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008362 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008363 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008364 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008365 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008366 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8367 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008368 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008369 }
8370 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008371 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8372 // ignored
8373 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008374 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008375 if (!outputDesc->isMuted(volumeSource)) {
8376 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008377 return;
8378 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008379 if (outputDesc->decMuteCount(volumeSource) == 0) {
8380 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008381 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008382 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008383 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008384 delayMs);
8385 }
8386 }
8387}
8388
François Gaffie53615e22015-03-19 09:24:12 +01008389bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8390{
François Gaffiec005e562018-11-06 15:04:49 +01008391 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008392 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8393 return true;
8394 }
8395
8396 // has known usage?
8397 switch (paa->usage) {
8398 case AUDIO_USAGE_UNKNOWN:
8399 case AUDIO_USAGE_MEDIA:
8400 case AUDIO_USAGE_VOICE_COMMUNICATION:
8401 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8402 case AUDIO_USAGE_ALARM:
8403 case AUDIO_USAGE_NOTIFICATION:
8404 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8405 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8406 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8407 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8408 case AUDIO_USAGE_NOTIFICATION_EVENT:
8409 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8410 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8411 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8412 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008413 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008414 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008415 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008416 case AUDIO_USAGE_EMERGENCY:
8417 case AUDIO_USAGE_SAFETY:
8418 case AUDIO_USAGE_VEHICLE_STATUS:
8419 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008420 break;
8421 default:
8422 return false;
8423 }
8424 return true;
8425}
8426
François Gaffie2110e042015-03-24 08:41:51 +01008427audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8428{
8429 return mEngine->getForceUse(usage);
8430}
8431
Eric Laurent96d1dda2022-03-14 17:14:19 +01008432bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008433 return isStateInCall(mEngine->getPhoneState());
8434}
8435
Eric Laurent96d1dda2022-03-14 17:14:19 +01008436bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008437 return is_state_in_call(state);
8438}
8439
Eric Laurentf9cccec2022-11-16 19:12:00 +01008440bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008441 audio_mode_t mode = mEngine->getPhoneState();
8442 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008443 || (mode == AUDIO_MODE_CALL_SCREEN)
8444 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008445}
8446
Eric Laurentf9cccec2022-11-16 19:12:00 +01008447bool AudioPolicyManager::isInCallOrScreening() const {
8448 audio_mode_t mode = mEngine->getPhoneState();
8449 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8450}
8451
Eric Laurentd60560a2015-04-10 11:31:20 -07008452void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8453{
8454 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008455 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008456 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008457 sourceDesc->sinkDevice()->equals(deviceDesc))
8458 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008459 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008460 }
8461 }
8462
8463 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8464 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8465 bool release = false;
8466 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8467 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8468 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8469 source->ext.device.type == deviceDesc->type()) {
8470 release = true;
8471 }
8472 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008473 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008474 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8475 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8476 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008477 sink->ext.device.type == deviceDesc->type() &&
8478 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8479 || strncmp(sink->ext.device.address, address,
8480 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008481 release = true;
8482 }
8483 }
8484 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008485 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8486 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008487 }
8488 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008489
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008490 mInputs.clearSessionRoutesForDevice(deviceDesc);
8491
Francois Gaffie716e1432019-01-14 16:58:59 +01008492 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008493}
8494
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008495void AudioPolicyManager::modifySurroundFormats(
8496 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008497 std::unordered_set<audio_format_t> enforcedSurround(
8498 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008499 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008500 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008501 allSurround.insert(pair.first);
8502 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8503 }
Phil Burk09bc4612016-02-24 15:58:15 -08008504
8505 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8506 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008507 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008508 // This is the resulting set of formats depending on the surround mode:
8509 // 'all surround' = allSurround
8510 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8511 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8512 // 'manual surround' = mManualSurroundFormats
8513 // AUTO: formats v 'enforced surround'
8514 // ALWAYS: formats v 'all surround' v 'enforced surround'
8515 // NEVER: formats ^ 'non-surround'
8516 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008517
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008518 std::unordered_set<audio_format_t> formatSet;
8519 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8520 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008521 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008522 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008523 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008524 formatSet.insert(*formatIter);
8525 }
8526 }
8527 } else {
8528 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8529 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008530 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008531
jiabin81772902018-04-02 17:52:27 -07008532 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008533 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008534 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8535 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8536 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008537 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008538 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8539 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8540 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008541 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008542 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008543 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008544 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008545 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008546 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008547}
8548
jiabin06e4bab2019-07-29 10:13:34 -07008549void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8550 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008551 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8552 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8553
8554 // If NEVER, then remove support for channelMasks > stereo.
8555 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008556 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8557 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008558 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008559 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008560 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008561 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008562 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008563 }
8564 }
jiabin81772902018-04-02 17:52:27 -07008565 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8566 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8567 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008568 bool supports5dot1 = false;
8569 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008570 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008571 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8572 supports5dot1 = true;
8573 break;
8574 }
8575 }
8576 // If not then add 5.1 support.
8577 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008578 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008579 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008580 }
Phil Burk09bc4612016-02-24 15:58:15 -08008581 }
8582}
8583
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008584void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008585 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008586 const sp<IOProfile>& profile) {
8587 if (!profile->hasDynamicAudioProfile()) {
8588 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008589 }
François Gaffie112b0af2015-11-19 16:13:25 +01008590
jiabin12537fc2023-10-12 17:56:08 +00008591 audio_port_v7 devicePort;
8592 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008593
jiabin12537fc2023-10-12 17:56:08 +00008594 audio_port_v7 mixPort;
8595 profile->toAudioPort(&mixPort);
8596 mixPort.ext.mix.handle = ioHandle;
8597
8598 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8599 if (status != NO_ERROR) {
8600 ALOGE("%s failed to query the attributes of the mix port", __func__);
8601 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008602 }
jiabin12537fc2023-10-12 17:56:08 +00008603
8604 std::set<audio_format_t> supportedFormats;
8605 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8606 supportedFormats.insert(mixPort.audio_profiles[i].format);
8607 }
8608 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8609 mReportedFormatsMap[devDesc] = formats;
8610
8611 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8612 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8613 modifySurroundFormats(devDesc, &formats);
8614 size_t modifiedNumProfiles = 0;
8615 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8616 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8617 formats.end()) {
8618 // Skip the format that is not present after modifying surround formats.
8619 continue;
8620 }
8621 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8622 sizeof(struct audio_profile));
8623 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8624 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8625 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8626 modifySurroundChannelMasks(&channels);
8627 std::copy(channels.begin(), channels.end(),
8628 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8629 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8630 }
8631 mixPort.num_audio_profiles = modifiedNumProfiles;
8632 }
8633 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008634}
Eric Laurentd60560a2015-04-10 11:31:20 -07008635
Mikhail Naganovdc769682018-05-04 15:34:08 -07008636status_t AudioPolicyManager::installPatch(const char *caller,
8637 audio_patch_handle_t *patchHandle,
8638 AudioIODescriptorInterface *ioDescriptor,
8639 const struct audio_patch *patch,
8640 int delayMs)
8641{
8642 ssize_t index = mAudioPatches.indexOfKey(
8643 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8644 *patchHandle : ioDescriptor->getPatchHandle());
8645 sp<AudioPatch> patchDesc;
8646 status_t status = installPatch(
8647 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8648 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008649 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008650 }
8651 return status;
8652}
8653
8654status_t AudioPolicyManager::installPatch(const char *caller,
8655 ssize_t index,
8656 audio_patch_handle_t *patchHandle,
8657 const struct audio_patch *patch,
8658 int delayMs,
8659 uid_t uid,
8660 sp<AudioPatch> *patchDescPtr)
8661{
8662 sp<AudioPatch> patchDesc;
8663 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8664 if (index >= 0) {
8665 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008666 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008667 }
8668
8669 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8670 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8671 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8672 if (status == NO_ERROR) {
8673 if (index < 0) {
8674 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008675 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008676 } else {
8677 patchDesc->mPatch = *patch;
8678 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008679 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008680 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008681 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008682 }
8683 nextAudioPortGeneration();
8684 mpClientInterface->onAudioPatchListUpdate();
8685 }
8686 if (patchDescPtr) *patchDescPtr = patchDesc;
8687 return status;
8688}
8689
jiabinbce0c1d2020-10-05 11:20:18 -07008690bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8691{
8692 const TrackClientVector activeClients = output->getActiveClients();
8693 if (activeClients.empty()) {
8694 return true;
8695 }
8696 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8697 if (index < 0) {
8698 ALOGE("%s, no audio patch found while there are active clients on output %d",
8699 __func__, output->getId());
8700 return false;
8701 }
8702 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8703 DeviceVector routedDevices;
8704 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8705 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8706 patchDesc->mPatch.sinks[i].id);
8707 if (device == nullptr) {
8708 ALOGE("%s, no audio device found with id(%d)",
8709 __func__, patchDesc->mPatch.sinks[i].id);
8710 return false;
8711 }
8712 routedDevices.add(device);
8713 }
8714 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008715 if (client->isInvalid()) {
8716 // No need to take care about invalidated clients.
8717 continue;
8718 }
jiabinbce0c1d2020-10-05 11:20:18 -07008719 sp<DeviceDescriptor> preferredDevice =
8720 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8721 if (mEngine->getOutputDevicesForAttributes(
8722 client->attributes(), preferredDevice, false) == routedDevices) {
8723 return false;
8724 }
8725 }
8726 return true;
8727}
8728
8729sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008730 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008731 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8732 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008733{
8734 for (const auto& device : devices) {
8735 // TODO: This should be checking if the profile supports the device combo.
8736 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008737 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8738 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008739 return nullptr;
8740 }
8741 }
8742 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8743 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008744 status_t status = desc->open(halConfig, mixerConfig, devices,
8745 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008746 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008747 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008748 return nullptr;
8749 }
jiabin14b50cc2023-12-13 19:01:52 +00008750 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8751 auto portConfig = desc->getConfig();
8752 for (const auto& device : devices) {
8753 device->setPreferredConfig(&portConfig);
8754 }
8755 }
jiabinbce0c1d2020-10-05 11:20:18 -07008756
8757 // Here is where the out_set_parameters() for card & device gets called
8758 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8759 const audio_devices_t deviceType = device->type();
8760 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008761 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008762 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8763 mpClientInterface->setParameters(output, String8(param));
8764 free(param);
8765 }
jiabin12537fc2023-10-12 17:56:08 +00008766 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008767 if (!profile->hasValidAudioProfile()) {
8768 ALOGW("%s() missing param", __func__);
8769 desc->close();
8770 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008771 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8772 // Reopen the output with the best audio profile picked by APM when the profile supports
8773 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008774 desc->close();
8775 output = AUDIO_IO_HANDLE_NONE;
8776 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8777 profile->pickAudioProfile(
8778 config.sample_rate, config.channel_mask, config.format);
8779 config.offload_info.sample_rate = config.sample_rate;
8780 config.offload_info.channel_mask = config.channel_mask;
8781 config.offload_info.format = config.format;
8782
jiabina84c3d32022-12-02 18:59:55 +00008783 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008784 if (status != NO_ERROR) {
8785 return nullptr;
8786 }
8787 }
8788
8789 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008790 setOutputDevices(__func__, desc,
8791 devices,
8792 true,
8793 0,
8794 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008795 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8796 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8797
jiabinbce0c1d2020-10-05 11:20:18 -07008798 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8799 sp<AudioPolicyMix> policyMix;
8800 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8801 policyMix->setOutput(desc);
8802 desc->mPolicyMix = policyMix;
8803 } else {
8804 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008805 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008806 }
8807
baek.kim -61c20122022-07-27 10:05:32 +00008808 } else if (hasPrimaryOutput() && speaker != nullptr
8809 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008810 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8811 // no duplicated output for:
8812 // - direct outputs
8813 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008814 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008815 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8816
8817 //TODO: configure audio effect output stage here
8818
8819 // open a duplicating output thread for the new output and the primary output
8820 sp<SwAudioOutputDescriptor> dupOutputDesc =
8821 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8822 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8823 if (status == NO_ERROR) {
8824 // add duplicated output descriptor
8825 addOutput(duplicatedOutput, dupOutputDesc);
8826 } else {
8827 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8828 mPrimaryOutput->mIoHandle, output);
8829 desc->close();
8830 removeOutput(output);
8831 nextAudioPortGeneration();
8832 return nullptr;
8833 }
8834 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008835 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8836 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8837 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008838 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008839 }
jiabinbce0c1d2020-10-05 11:20:18 -07008840 return desc;
8841}
8842
jiabinf1c73972022-04-14 16:28:52 -07008843status_t AudioPolicyManager::getDevicesForAttributes(
8844 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8845 // Devices are determined in the following precedence:
8846 //
8847 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8848 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8849 //
8850 // If no such dynamic policy then
8851 // 2) Devices containing an active client using setPreferredDevice
8852 // with same strategy as the attributes.
8853 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8854 //
8855 // If no corresponding active client with setPreferredDevice then
8856 // 3) Devices associated with the strategy determined by the attributes
8857 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8858 //
8859 // See related getOutputForAttrInt().
8860
8861 // check dynamic policies but only for primary descriptors (secondary not used for audible
8862 // audio routing, only used for duplication for playback capture)
8863 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008864 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008865 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008866 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8867 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8868 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008869 if (status != OK) {
8870 return status;
8871 }
8872
8873 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8874 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8875 // as they are unaffected by device/stream volume
8876 // (per SwAudioOutputDescriptor::isFixedVolume()).
8877 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8878 ) {
8879 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8880 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8881 devices.add(deviceDesc);
8882 } else {
8883 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8884 // which selects setPreferredDevice if active. This means forVolume call
8885 // will take an active setPreferredDevice, if such exists.
8886
8887 devices = mEngine->getOutputDevicesForAttributes(
8888 attr, nullptr /* preferredDevice */, false /* fromCache */);
8889 }
8890
8891 if (forVolume) {
8892 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8893 // for single volume control in AudioService (such relationship should exist if
8894 // SPEAKER_SAFE is present).
8895 //
8896 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8897 DeviceVector speakerSafeDevices =
8898 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8899 if (!speakerSafeDevices.isEmpty()) {
8900 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8901 devices.remove(speakerSafeDevices);
8902 }
8903 }
8904
8905 return NO_ERROR;
8906}
8907
8908status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8909 AudioProfileVector& audioProfiles,
8910 uint32_t flags,
8911 bool isInput) {
8912 for (const auto& hwModule : mHwModules) {
8913 // the MSD module checks for different conditions
8914 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8915 continue;
8916 }
8917 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8918 : hwModule->getOutputProfiles();
8919 for (const auto& profile : ioProfiles) {
8920 if (!profile->areAllDevicesSupported(devices) ||
8921 !profile->isCompatibleProfileForFlags(
8922 flags, false /*exactMatchRequiredForInputFlags*/)) {
8923 continue;
8924 }
8925 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8926 }
8927 }
8928
8929 if (!isInput) {
8930 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8931 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8932 if (msdModule != nullptr) {
8933 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8934 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8935 for (const auto &profile: msdModule->getOutputProfiles()) {
8936 if (!profile->asAudioPort()->isDirectOutput()) {
8937 continue;
8938 }
8939 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8940 }
8941 } else {
8942 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8943 }
8944 }
8945 }
8946
8947 return NO_ERROR;
8948}
8949
jiabin3ff8d7d2022-12-13 06:27:44 +00008950sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8951 const audio_config_t *config,
8952 audio_output_flags_t flags,
8953 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008954 closeOutput(outputDesc->mIoHandle);
8955 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8956 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8957 if (preferredOutput == nullptr) {
8958 ALOGE("%s failed to reopen output device=%d, caller=%s",
8959 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008960 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008961 return preferredOutput;
8962}
8963
8964void AudioPolicyManager::reopenOutputsWithDevices(
8965 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8966 for (const auto& [output, devices] : outputsToReopen) {
8967 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8968 closeOutput(output);
8969 openOutputWithProfileAndDevice(desc->mProfile, devices);
8970 }
jiabina84c3d32022-12-02 18:59:55 +00008971}
8972
jiabinc44b3462022-12-08 12:52:31 -08008973PortHandleVector AudioPolicyManager::getClientsForStream(
8974 audio_stream_type_t streamType) const {
8975 PortHandleVector clients;
8976 for (size_t i = 0; i < mOutputs.size(); ++i) {
8977 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8978 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8979 }
8980 return clients;
8981}
8982
8983void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8984 PortHandleVector clients;
8985 for (auto stream : streams) {
8986 PortHandleVector clientsForStream = getClientsForStream(stream);
8987 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8988 }
8989 mpClientInterface->invalidateTracks(clients);
8990}
8991
jiabin220eea12024-05-17 17:55:20 +00008992void AudioPolicyManager::updateClientsInternalMute(
8993 const sp<android::SwAudioOutputDescriptor> &desc) {
8994 if (!desc->isBitPerfect() ||
8995 !com::android::media::audioserver::
8996 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
8997 // This is only used for bit perfect output now.
8998 return;
8999 }
9000 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9001 bool bitPerfectClientInternalMute = false;
9002 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9003 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9004 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9005 bitPerfectClient = client;
9006 continue;
9007 }
9008 bool muted = false;
9009 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9010 // System sound is muted.
9011 muted = true;
9012 } else {
9013 bitPerfectClientInternalMute = true;
9014 }
9015 if (client->setInternalMute(muted)) {
9016 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9017 if (!result.ok()) {
9018 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9019 continue;
9020 }
9021 media::TrackInternalMuteInfo info;
9022 info.portId = result.value();
9023 info.muted = client->getInternalMute();
9024 clientsInternalMute.push_back(std::move(info));
9025 }
9026 }
9027 if (bitPerfectClient != nullptr &&
9028 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9029 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9030 if (result.ok()) {
9031 media::TrackInternalMuteInfo info;
9032 info.portId = result.value();
9033 info.muted = bitPerfectClient->getInternalMute();
9034 clientsInternalMute.push_back(std::move(info));
9035 } else {
9036 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9037 __func__, bitPerfectClient->portId());
9038 }
9039 }
9040 if (!clientsInternalMute.empty()) {
9041 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9042 status != NO_ERROR) {
9043 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9044 }
9045 }
9046}
9047
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009048} // namespace android