blob: 7f4be79e256156b50864af28189828ddcc6d6345 [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));
jiabin3ff8d7d2022-12-13 06:27:44 +0000341 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
342 // 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);
François Gaffie44481e72016-04-20 07:49:57 +0200399
Eric Laurent0dd51852019-04-19 18:18:58 -0700400 if (checkInputsForDevice(device, state) != NO_ERROR) {
401 mAvailableInputDevices.remove(device);
402
jiabinc0048632023-04-27 22:04:31 +0000403 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100404
405 mHwModules.cleanUpForDevice(device);
406
Eric Laurentd4692962014-05-05 18:13:44 -0700407 return INVALID_OPERATION;
408 }
409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700414 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return INVALID_OPERATION;
417 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
jiabinc0048632023-04-27 22:04:31 +0000421 // Notify the HAL to prepare to disconnect device
422 broadcastDeviceConnectionState(
423 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
François Gaffie11d30102018-11-02 16:09:09 +0100425 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700426
427 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428
jiabinc0048632023-04-27 22:04:31 +0000429 // Set Disconnect to HALs
430 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
431
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432 // remove device from mReportedFormatsMap cache
433 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700435
436 default:
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return BAD_VALUE;
439 }
440
Eric Laurent736a1022019-03-27 18:28:46 -0700441 // Propagate device availability to Engine
442 setEngineDeviceConnectionState(device, state);
443
Eric Laurent0dd51852019-04-19 18:18:58 -0700444 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700445 // As the input device list can impact the output device selection, update
446 // getDeviceForStrategy() cache
447 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700448
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100449 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200450 // Reconnect Audio Source
451 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
452 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
453 checkAudioSourceForAttributes(attributes);
454 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100456 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700457 }
458
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700461 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700462
François Gaffie11d30102018-11-02 16:09:09 +0100463 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return BAD_VALUE;
465}
466
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
468 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800469 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700470 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
471 devDescr->setName(device_name);
472 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100473}
474
Eric Laurent736a1022019-03-27 18:28:46 -0700475void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
476 audio_policy_dev_state_t state) {
477
478 // the Engine does not have to know about remote submix devices used by dynamic audio policies
479 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
480 return;
481 }
482 mEngine->setDeviceConnectionState(device, state);
483}
484
485
Eric Laurente0720872014-03-11 09:30:41 -0700486audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100487 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700488{
Eric Laurent634b7142016-04-20 13:48:02 -0700489 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
491 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700492 (strlen(device_address) != 0)/*matchAddress*/);
493
494 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100495 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700496 device, device_address);
497 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
498 }
François Gaffie53615e22015-03-19 09:24:12 +0100499
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 DeviceVector *deviceVector;
501
Eric Laurente552edb2014-03-10 17:42:56 -0700502 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 deviceVector = &mAvailableInputDevices;
506 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100507 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 }
Eric Laurent634b7142016-04-20 13:48:02 -0700510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 return (deviceVector->getDevice(
512 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800514}
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
517 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 const char *device_name,
519 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
522 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800524 // connect/disconnect only 1 device at a time
525 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
526
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700528 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530 // Nothing to do: device is not connected
531 return NO_ERROR;
532 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700535 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800536 // configure codecs.
537 // Handle two specific cases by sending a set parameter to
538 // configure A2DP codecs. No need to toggle device state.
539 // Case 1: A2DP active device switches from primary to primary
540 // module
541 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700543 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
545 if (availablePrimaryOutputDevices().contains(devDesc) &&
546 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 bool isA2dp = audio_is_a2dp_out_device(device);
548 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
549 : String8(AudioParameter::keyReconfigLeSupported);
550 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 int isReconfigSupported;
553 repliedParameters.getInt(supportKey, isReconfigSupported);
554 if (isReconfigSupported) {
555 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
556 : String8(AudioParameter::keyReconfigLe);
557 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 param.add(key, String8("true"));
559 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
560 devDesc->setEncodedFormat(encodedFormat);
561 return NO_ERROR;
562 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700563 }
564 }
cnx421bd2dcc42020-07-11 14:58:44 +0800565 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
566 for (size_t i = 0; i < mOutputs.size(); i++) {
567 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
568 // mute media strategies and delay device switch by the largest
569 // This avoid sending the music tail into the earpiece or headset.
570 setStrategyMute(musicStrategy, true, desc);
571 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
572 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
573 nullptr, true /*fromCache*/).types());
574 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 // Toggle the device state: UNAVAILABLE -> AVAILABLE
576 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100577 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800578 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 device_address, device_name,
580 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800581 if (status != NO_ERROR) {
582 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
583 status);
584 return status;
585 }
586
587 status = setDeviceConnectionState(device,
588 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800589 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800590 if (status != NO_ERROR) {
591 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
592 status);
593 return status;
594 }
595
596 return NO_ERROR;
597}
598
Pattydd807582021-11-04 21:01:03 +0800599status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
600 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800601{
Pattydd807582021-11-04 21:01:03 +0800602 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800603 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800604 std::unordered_set<audio_format_t> formatSet;
605 sp<HwModule> primaryModule =
606 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700607 if (primaryModule == nullptr) {
608 ALOGE("%s() unable to get primary module", __func__);
609 return NO_INIT;
610 }
Pattydd807582021-11-04 21:01:03 +0800611
612 DeviceTypeSet audioDeviceSet;
613
614 switch(device) {
615 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
616 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
617 break;
618 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800619 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
620 break;
621 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
622 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800623 break;
624 default:
625 ALOGE("%s() device type 0x%08x not supported", __func__, device);
626 return BAD_VALUE;
627 }
628
jiabin9a3361e2019-10-01 09:38:30 -0700629 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800630 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800631 for (const auto& device : declaredDevices) {
632 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800633 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800634 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800635 return status;
636}
637
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100638DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
639{
640 DeviceVector rxSinkdevices{};
641 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
642 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
643 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
644 auto rxSinkDevice = rxSinkdevices.itemAt(0);
645 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
646 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
647 // retrieve Rx Source device descriptor
648 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
649 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
650
651 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
652 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
653 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
654 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
655 return DeviceVector(rxSinkDevice);
656 }
657 }
658 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
659 // the device returned is not necessarily reachable via this output
660 // (filter later by setOutputDevices())
661 return getNewOutputDevices(mPrimaryOutput, fromCache);
662}
663
664status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
665{
François Gaffiedb1755b2023-09-01 11:50:35 +0200666 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
668 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
669 }
670 return INVALID_OPERATION;
671}
672
673status_t AudioPolicyManager::updateCallRoutingInternal(
674 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675{
676 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100677 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700678 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200679 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700680 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 }
François Gaffie11d30102018-11-02 16:09:09 +0100683
Francois Gaffie716e1432019-01-14 16:58:59 +0100684 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100685 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200686
687 disconnectTelephonyAudioSource(mCallRxSourceClient);
688 disconnectTelephonyAudioSource(mCallTxSourceClient);
689
690 if (rxDevices.isEmpty()) {
691 ALOGW("%s() no selected output device", __func__);
692 return INVALID_OPERATION;
693 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000694 if (txSourceDevice == nullptr) {
695 ALOGE("%s() selected input device not available", __func__);
696 return INVALID_OPERATION;
697 }
François Gaffiec005e562018-11-06 15:04:49 +0100698
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100699 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100700 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700701
François Gaffie9eb18552018-11-05 10:33:26 +0100702 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700703 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100704 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700705 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100706 // retrieve Rx Source and Tx Sink device descriptors
707 sp<DeviceDescriptor> rxSourceDevice =
708 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
709 String8(),
710 AUDIO_FORMAT_DEFAULT);
711 sp<DeviceDescriptor> txSinkDevice =
712 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
713 String8(),
714 AUDIO_FORMAT_DEFAULT);
715
716 // RX and TX Telephony device are declared by Primary Audio HAL
717 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
718 (telephonyRxModule->getHalVersionMajor() >= 3)) {
719 if (rxSourceDevice == 0 || txSinkDevice == 0) {
720 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100721 ALOGE("%s() no telephony Tx and/or RX device", __func__);
722 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100723 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100724 // createAudioPatchInternal now supports both HW / SW bridging
725 createRxPatch = true;
726 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100727 } else {
728 // If the RX device is on the primary HW module, then use legacy routing method for
729 // voice calls via setOutputDevice() on primary output.
730 // Otherwise, create two audio patches for TX and RX path.
731 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
732 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733 // If the TX device is also on the primary HW module, setOutputDevice() will take care
734 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100735 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
736 (txSinkDevice != 0);
737 }
738 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
739 // Otherwise, create two audio patches for TX and RX path.
740 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200741 if (!hasPrimaryOutput()) {
742 ALOGW("%s() no primary output available", __func__);
743 return INVALID_OPERATION;
744 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530745 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700746 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200747 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800748 // If the TX device is on the primary HW module but RX device is
749 // on other HW module, SinkMetaData of telephony input should handle it
750 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700751 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700752 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100753 // terminate active capture if on the same HW module as the call TX source device
754 // FIXME: would be better to refine to only inputs whose profile connects to the
755 // call TX device but this information is not in the audio patch and logic here must be
756 // symmetric to the one in startInput()
757 for (const auto& activeDesc : mInputs.getActiveInputs()) {
758 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
759 closeActiveClients(activeDesc);
760 }
761 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200762 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100764 if (waitMs != nullptr) {
765 *waitMs = muteWaitMs;
766 }
767 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800768}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700769
Mikhail Naganov100f0122018-11-29 11:22:16 -0800770bool AudioPolicyManager::isDeviceOfModule(
771 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
772 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
773 if (module != 0) {
774 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
775 .indexOf(devDesc) != NAME_NOT_FOUND
776 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
777 .indexOf(devDesc) != NAME_NOT_FOUND;
778 }
779 return false;
780}
781
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200782void AudioPolicyManager::connectTelephonyRxAudioSource()
783{
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200785 const struct audio_port_config source = {
786 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
787 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
788 };
789 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100790
791 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
792 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
793 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
794 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 ALOGE_IF(mCallRxSourceClient == nullptr,
796 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200797}
798
Francois Gaffie601801d2021-06-22 13:27:39 +0200799void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200800{
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 if (clientDesc == nullptr) {
802 return;
803 }
804 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
805 "%s error stopping audio source", __func__);
806 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807}
808
809void AudioPolicyManager::connectTelephonyTxAudioSource(
810 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
811 uint32_t delayMs)
812{
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200814 if (srcDevice == nullptr || sinkDevice == nullptr) {
815 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
816 return;
817 }
818 PatchBuilder patchBuilder;
819 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
820 ALOGV("%s between source %s and sink %s", __func__,
821 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200822 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200823 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
824
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 struct audio_port_config source = {};
826 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100827 mCallTxSourceClient = new SourceClientDescriptor(
828 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
829 mCommunnicationStrategy, toVolumeSource(aa), true);
830 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
831
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
833 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200834 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
835 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200836 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
837 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200839 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200840}
841
Eric Laurente0720872014-03-11 09:30:41 -0700842void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700843{
844 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100845 // store previous phone state for management of sonification strategy below
846 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100847 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100848
849 if (mEngine->setPhoneState(state) != NO_ERROR) {
850 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700851 return;
852 }
François Gaffie2110e042015-03-24 08:41:51 +0100853 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700854 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700855 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700856 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800857 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
859
François Gaffie2110e042015-03-24 08:41:51 +0100860 /**
861 * Switching to or from incall state or switching between telephony and VoIP lead to force
862 * routing command.
863 */
Eric Laurent74b71512019-11-06 17:21:57 -0800864 bool force = ((isStateInCall(oldState) != isStateInCall(state))
865 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700866
867 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700868 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700869
Eric Laurente552edb2014-03-10 17:42:56 -0700870 int delayMs = 0;
871 if (isStateInCall(state)) {
872 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100873 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
874 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700875 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 // mute media and sonification strategies and delay device switch by the largest
878 // latency of any output where either strategy is active.
879 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100880 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
881 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
882 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700883 (delayMs < (int)desc->latency()*2)) {
884 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700885 }
François Gaffiec005e562018-11-06 15:04:49 +0100886 setStrategyMute(musicStrategy, true, desc);
887 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
888 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
889 nullptr, true /*fromCache*/).types());
890 setStrategyMute(sonificationStrategy, true, desc);
891 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
892 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
893 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700894 }
895 }
896
François Gaffiedb1755b2023-09-01 11:50:35 +0200897 if (state == AUDIO_MODE_IN_CALL) {
898 (void)updateCallRouting(false /*fromCache*/, delayMs);
899 } else {
900 if (oldState == AUDIO_MODE_IN_CALL) {
901 disconnectTelephonyAudioSource(mCallRxSourceClient);
902 disconnectTelephonyAudioSource(mCallTxSourceClient);
903 }
904 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100905 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
906 // force routing command to audio hardware when ending call
907 // even if no device change is needed
908 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
909 rxDevices = mPrimaryOutput->devices();
910 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530911 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700912 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700913 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700914
jiabin3ff8d7d2022-12-13 06:27:44 +0000915 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700916 // reevaluate routing on all outputs in case tracks have been started during the call
917 for (size_t i = 0; i < mOutputs.size(); i++) {
918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100919 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200920 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
921 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000922 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
923 // If the device is using preferred mixer attributes, the output need to reopen
924 // with default configuration when the new selected devices are different from
925 // current routing devices.
926 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
927 continue;
928 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530929 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200930 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700931 }
932 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000933 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700934
Eric Laurent96d1dda2022-03-14 17:14:19 +0100935 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 if (isStateInCall(state)) {
938 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800940 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942
943 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100944 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
945 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700946}
947
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700948audio_mode_t AudioPolicyManager::getPhoneState() {
949 return mEngine->getPhoneState();
950}
951
Eric Laurente0720872014-03-11 09:30:41 -0700952void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100953 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700954{
François Gaffie2110e042015-03-24 08:41:51 +0100955 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700956 if (config == mEngine->getForceUse(usage)) {
957 return;
958 }
Eric Laurente552edb2014-03-10 17:42:56 -0700959
François Gaffie2110e042015-03-24 08:41:51 +0100960 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
961 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
962 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700963 }
François Gaffie2110e042015-03-24 08:41:51 +0100964 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
965 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
966 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700967
968 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700969 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800970
Eric Laurent22fcda22019-05-17 16:28:47 -0700971 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
972 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800973 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700974 }
975
Eric Laurentdc462862016-07-19 12:29:53 -0700976 //FIXME: workaround for truncated touch sounds
977 // to be removed when the problem is handled by system UI
978 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700979 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
980 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
981 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700982
983 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100984 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700985}
986
Eric Laurente0720872014-03-11 09:30:41 -0700987void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700988{
989 ALOGV("setSystemProperty() property %s, value %s", property, value);
990}
991
Dorin Drimusecc9f422022-03-09 17:57:40 +0100992// Find an MSD output profile compatible with the parameters passed.
993// When "directOnly" is set, restrict search to profiles for direct outputs.
994sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
995 const DeviceVector& devices,
996 uint32_t samplingRate,
997 audio_format_t format,
998 audio_channel_mask_t channelMask,
999 audio_output_flags_t flags,
1000 bool directOnly)
1001{
1002 flags = getRelevantFlags(flags, directOnly);
1003
1004 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1005 if (msdModule != nullptr) {
1006 // for the msd module check if there are patches to the output devices
1007 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1008 HwModuleCollection modules;
1009 modules.add(msdModule);
1010 return searchCompatibleProfileHwModules(
1011 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1012 flags, directOnly);
1013 }
1014 }
1015 return nullptr;
1016}
1017
Michael Chana94fbb22018-04-24 14:31:19 +10001018// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1019// search to profiles for direct outputs.
1020sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001021 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001022 uint32_t samplingRate,
1023 audio_format_t format,
1024 audio_channel_mask_t channelMask,
1025 audio_output_flags_t flags,
1026 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001027{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 flags = getRelevantFlags(flags, directOnly);
1029
1030 return searchCompatibleProfileHwModules(
1031 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1032}
1033
1034audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1035 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001036 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 // only retain flags that will drive the direct output profile selection
1038 // if explicitly requested
1039 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001040 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001041 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1042 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001043 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 return flags;
1045}
Eric Laurent861a6282015-05-18 15:40:16 -07001046
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1048 const HwModuleCollection& hwModules,
1049 const DeviceVector& devices,
1050 uint32_t samplingRate,
1051 audio_format_t format,
1052 audio_channel_mask_t channelMask,
1053 audio_output_flags_t flags,
1054 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001055 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001056 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001057 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001058 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059 samplingRate, NULL /*updatedSamplingRate*/,
1060 format, NULL /*updatedFormat*/,
1061 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001062 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 continue;
1064 }
1065 // reject profiles not corresponding to a device currently available
1066 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1067 continue;
1068 }
1069 // reject profiles if connected device does not support codec
1070 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1071 continue;
1072 }
1073 if (!directOnly) {
1074 return curProfile;
1075 }
1076
1077 // when searching for direct outputs, if several profiles are compatible, give priority
1078 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001079 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001080 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001081 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001082 }
1083 profile = curProfile;
1084 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1085 break;
1086 }
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
1088 }
Eric Laurent861a6282015-05-18 15:40:16 -07001089 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001090}
1091
Eric Laurentfa0f6742021-08-17 18:39:44 +02001092sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001093 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001094{
1095 for (const auto& hwModule : mHwModules) {
1096 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001097 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098 continue;
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001101 // reject profiles not corresponding to a device currently available
1102 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1103 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1104 continue;
1105 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1107 != devices.size()) {
1108 continue;
1109 }
1110 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001111 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1112 return curProfile;
1113 }
1114 }
1115 return nullptr;
1116}
1117
Eric Laurentf4e63452017-11-06 19:31:46 +00001118audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001119{
François Gaffiec005e562018-11-06 15:04:49 +01001120 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001121
1122 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1123 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1124 // format, flags, etc. This may result in some discrepancy for functions that utilize
1125 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1126 // and AudioSystem::getOutputSamplingRate().
1127
François Gaffie11d30102018-11-02 16:09:09 +01001128 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001129 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1130 if (stream == AUDIO_STREAM_MUSIC &&
1131 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1132 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1133 }
1134 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001135
François Gaffie11d30102018-11-02 16:09:09 +01001136 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1137 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001138 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001139}
1140
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1142 const audio_attributes_t *srcAttr,
1143 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001144{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001145 if (srcAttr != NULL) {
1146 if (!isValidAttributes(srcAttr)) {
1147 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1148 __func__,
1149 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1150 srcAttr->tags);
1151 return BAD_VALUE;
1152 }
1153 *dstAttr = *srcAttr;
1154 } else {
1155 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1156 ALOGE("%s: invalid stream type", __func__);
1157 return BAD_VALUE;
1158 }
François Gaffiec005e562018-11-06 15:04:49 +01001159 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001160 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001161
1162 // Only honor audibility enforced when required. The client will be
1163 // forced to reconnect if the forced usage changes.
1164 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001165 dstAttr->flags = static_cast<audio_flags_mask_t>(
1166 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001167 }
1168
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169 return NO_ERROR;
1170}
1171
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172status_t AudioPolicyManager::getOutputForAttrInt(
1173 audio_attributes_t *resultAttr,
1174 audio_io_handle_t *output,
1175 audio_session_t session,
1176 const audio_attributes_t *attr,
1177 audio_stream_type_t *stream,
1178 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001179 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180 audio_output_flags_t *flags,
1181 audio_port_handle_t *selectedDeviceId,
1182 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001183 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001185 bool *isSpatialized,
1186 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001187{
François Gaffiec005e562018-11-06 15:04:49 +01001188 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001189 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001190 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001191 const sp<DeviceDescriptor> requestedDevice =
1192 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1193
Eric Laurent8a1095a2019-11-08 14:44:16 -08001194 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001195 *isSpatialized = false;
1196
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001197 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1198 if (status != NO_ERROR) {
1199 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001200 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001201 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001202 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001203 }
François Gaffiec005e562018-11-06 15:04:49 +01001204 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001205
François Gaffiec005e562018-11-06 15:04:49 +01001206 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1207 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001208
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 bool usePrimaryOutputFromPolicyMixes = false;
1210
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1212 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1213 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001215 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1216 .channel_mask = config->channel_mask,
1217 .format = config->format,
1218 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001219 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001220 mAvailableOutputDevices, requestedDevice, primaryMix,
1221 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001222 if (status != OK) {
1223 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001224 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001225
Kevin Rocard153f92d2018-12-18 18:33:28 -08001226 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001227 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1228 && !audio_is_linear_pcm(config->format)) {
1229 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 return BAD_VALUE;
1231 }
1232 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001233 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1235 primaryMix->mDeviceAddress,
1236 AUDIO_FORMAT_DEFAULT);
1237 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001238 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001239 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1240 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001241 // if a direct output can be opened to deliver the track's multi-channel content to the
1242 // output rather than being downmixed by the primary output, then use this direct
1243 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1244 // mix.
1245 bool tryDirectForChannelMask = policyDesc != nullptr
1246 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1247 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001248 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001249 audio_io_handle_t newOutput;
1250 status = openDirectOutput(
1251 *stream, session, config,
1252 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001253 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001255 policyDesc = mOutputs.valueFor(newOutput);
1256 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001257 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001258 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001259 policyDesc = nullptr;
1260 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001261 }
1262 if (policyDesc != nullptr) {
1263 policyDesc->mPolicyMix = primaryMix;
1264 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001265 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1266 : AUDIO_PORT_HANDLE_NONE;
1267 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1268 // Remove direct flag as it is not on a direct output.
1269 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1270 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001271
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001272 ALOGV("getOutputForAttr() returns output %d", *output);
1273 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1274 *outputType = API_OUT_MIX_PLAYBACK;
1275 } else {
1276 *outputType = API_OUTPUT_LEGACY;
1277 }
1278 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001279 } else {
1280 if (policyMixDevice != nullptr) {
1281 ALOGE("%s, try to use primary mix but no output found", __func__);
1282 return INVALID_OPERATION;
1283 }
1284 // Fallback to default engine selection as the selected primary mix device is not
1285 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001286 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287 }
François Gaffiec005e562018-11-06 15:04:49 +01001288 // Virtual sources must always be dynamicaly or explicitly routed
1289 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1290 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1291 return BAD_VALUE;
1292 }
1293 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1294 // in order to let the choice of the order to future vendor engine
1295 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001296
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001297 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001298 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001299 }
1300
Nadav Barb2f18162018-07-18 13:01:53 +03001301 // Set incall music only if device was explicitly set, and fallback to the device which is
1302 // chosen by the engine if not.
1303 // FIXME: provide a more generic approach which is not device specific and move this back
1304 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001305 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001306 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001307 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001308 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001309 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001310 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001311 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001312 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001313 }
1314 }
1315
François Gaffiec005e562018-11-06 15:04:49 +01001316 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1317 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1318 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001319
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001320 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001321 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001322 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001323 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001324 ALOGV("%s() Using MSD devices %s instead of devices %s",
1325 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001326 } else {
1327 *output = AUDIO_IO_HANDLE_NONE;
1328 }
1329 }
1330 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001331 sp<PreferredMixerAttributesInfo> info = nullptr;
1332 if (outputDevices.size() == 1) {
1333 info = getPreferredMixerAttributesInfo(
1334 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001335 mEngine->getProductStrategyForAttributes(*resultAttr),
1336 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001337 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1338 // and it is currently active.
1339 if (info != nullptr && info->getUid() != uid &&
1340 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1341 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001342 info = nullptr;
1343 }
1344 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001345 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001346 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001347 // The client will be active if the client is currently preferred mixer owner and the
1348 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001349 *isBitPerfect = (info != nullptr
1350 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001351 && info->getUid() == uid
1352 && *output != AUDIO_IO_HANDLE_NONE
1353 // When bit-perfect output is selected for the preferred mixer attributes owner,
1354 // only need to consider the config matches.
1355 && mOutputs.valueFor(*output)->isConfigurationMatched(
1356 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001357 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001358 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001359 AudioProfileVector profiles;
1360 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1361 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001362 const auto channels = profiles[0]->getChannels();
1363 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1364 config->channel_mask = *channels.begin();
1365 }
1366 const auto sampleRates = profiles[0]->getSampleRates();
1367 if (!sampleRates.empty() &&
1368 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1369 config->sample_rate = *sampleRates.begin();
1370 }
jiabinf1c73972022-04-14 16:28:52 -07001371 config->format = profiles[0]->getFormat();
1372 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001373 return INVALID_OPERATION;
1374 }
Paul McLeanaa981192015-03-21 09:55:15 -07001375
François Gaffiec005e562018-11-06 15:04:49 +01001376 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001377 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001378 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001379 *selectedDeviceId = outputDevice->getId();
1380 break;
1381 }
1382 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001383
Eric Laurent8a1095a2019-11-08 14:44:16 -08001384 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1385 *outputType = API_OUTPUT_TELEPHONY_TX;
1386 } else {
1387 *outputType = API_OUTPUT_LEGACY;
1388 }
1389
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001390 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1391
1392 return NO_ERROR;
1393}
1394
1395status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1396 audio_io_handle_t *output,
1397 audio_session_t session,
1398 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001399 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001400 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001401 audio_output_flags_t *flags,
1402 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001403 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001404 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001405 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001406 bool *isSpatialized,
1407 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001408{
1409 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1410 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1411 return INVALID_OPERATION;
1412 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001413 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001414 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001415 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001417 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001418 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001419 const sp<DeviceDescriptor> requestedDevice =
1420 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1421
1422 // Prevent from storing invalid requested device id in clients
1423 const audio_port_handle_t sanitizedRequestedPortId =
1424 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1425 *selectedDeviceId = sanitizedRequestedPortId;
1426
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001428 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001429 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1430 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001431 if (status != NO_ERROR) {
1432 return status;
1433 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001434 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001435 if (secondaryOutputs != nullptr) {
1436 for (auto &secondaryMix : secondaryMixes) {
1437 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1438 if (outputDesc != nullptr &&
1439 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1440 secondaryOutputs->push_back(outputDesc->mIoHandle);
1441 weakSecondaryOutputDescs.push_back(outputDesc);
1442 }
1443 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001444 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001445
Eric Laurent8fc147b2018-07-22 19:13:55 -07001446 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001447 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001448 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001449 };
jiabin4ef93452019-09-10 14:29:54 -07001450 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001451
Eric Laurentc209fe42020-06-05 18:11:23 -07001452 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001453 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001454 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001455 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001456 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001457 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001458 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001459 std::move(weakSecondaryOutputDescs),
1460 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001461 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001462
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001463 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1464 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001465
Eric Laurente83b55d2014-11-14 10:06:21 -08001466 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001467}
1468
Eric Laurentc529cf62020-04-17 18:19:10 -07001469status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1470 audio_session_t session,
1471 const audio_config_t *config,
1472 audio_output_flags_t flags,
1473 const DeviceVector &devices,
1474 audio_io_handle_t *output) {
1475
1476 *output = AUDIO_IO_HANDLE_NONE;
1477
1478 // skip direct output selection if the request can obviously be attached to a mixed output
1479 // and not explicitly requested
1480 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1481 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1482 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1483 return NAME_NOT_FOUND;
1484 }
1485
1486 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1487 // This prevents creating an offloaded track and tearing it down immediately after start
1488 // when audioflinger detects there is an active non offloadable effect.
1489 // FIXME: We should check the audio session here but we do not have it in this context.
1490 // This may prevent offloading in rare situations where effects are left active by apps
1491 // in the background.
1492 sp<IOProfile> profile;
1493 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1494 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1495 profile = getProfileForOutput(
1496 devices, config->sample_rate, config->format, config->channel_mask,
1497 flags, true /* directOnly */);
1498 }
1499
1500 if (profile == nullptr) {
1501 return NAME_NOT_FOUND;
1502 }
1503
1504 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1505 for (size_t i = 0; i < mOutputs.size(); i++) {
1506 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1507 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1508 // reuse direct output if currently open by the same client
1509 // and configured with same parameters
1510 if ((config->sample_rate == desc->getSamplingRate()) &&
1511 (config->format == desc->getFormat()) &&
1512 (config->channel_mask == desc->getChannelMask()) &&
1513 (session == desc->mDirectClientSession)) {
1514 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001515 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001516 mOutputs.keyAt(i), session);
1517 *output = mOutputs.keyAt(i);
1518 return NO_ERROR;
1519 }
1520 }
1521 }
1522
1523 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001524 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1525 return NAME_NOT_FOUND;
1526 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1527 // MMAP gracefully handles lack of an exclusive track resource by mixing
1528 // above the audio framework. For AAudio to know that the limit is reached,
1529 // return an error.
1530 return NAME_NOT_FOUND;
1531 } else {
1532 // Close outputs on this profile, if available, to free resources for this request
1533 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1534 const auto desc = mOutputs.valueAt(i);
1535 if (desc->mProfile == profile) {
1536 closeOutput(desc->mIoHandle);
1537 }
1538 }
1539 }
1540 }
1541
1542 // Unable to close streams to find free resources for this request
1543 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001544 return NAME_NOT_FOUND;
1545 }
1546
Atneya Nairb16666a2023-12-11 20:18:33 -08001547 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001548
Michael Chan6fb34492020-12-08 15:44:49 +11001549 // An MSD patch may be using the only output stream that can service this request. Release
1550 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001551 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001552
Eric Laurentf1f22e72021-07-13 14:04:14 +02001553 status_t status =
1554 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001555
1556 // only accept an output with the requested parameters
1557 if (status != NO_ERROR ||
1558 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1559 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1560 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1561 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1562 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1563 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1564 config->channel_mask, outputDesc->getChannelMask());
1565 if (*output != AUDIO_IO_HANDLE_NONE) {
1566 outputDesc->close();
1567 }
1568 // fall back to mixer output if possible when the direct output could not be open
1569 if (audio_is_linear_pcm(config->format) &&
1570 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1571 return NAME_NOT_FOUND;
1572 }
1573 *output = AUDIO_IO_HANDLE_NONE;
1574 return BAD_VALUE;
1575 }
1576 outputDesc->mDirectOpenCount = 1;
1577 outputDesc->mDirectClientSession = session;
1578
1579 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001580 setOutputDevices(__func__, outputDesc,
1581 devices,
1582 true,
1583 0,
1584 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001585 mPreviousOutputs = mOutputs;
1586 ALOGV("%s returns new direct output %d", __func__, *output);
1587 mpClientInterface->onAudioPortListUpdate();
1588 return NO_ERROR;
1589}
1590
François Gaffie11d30102018-11-02 16:09:09 +01001591audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1592 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001593 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001594 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001595 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001596 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001597 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001598 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001599 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001600{
Andy Hungc88b0642018-04-27 15:42:35 -07001601 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001602
jiabine375d412019-02-26 12:54:53 -08001603 // Discard haptic channel mask when forcing muting haptic channels.
1604 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001605 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1606 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001607
Eric Laurente552edb2014-03-10 17:42:56 -07001608 // open a direct output if required by specified parameters
1609 //force direct flag if offload flag is set: offloading implies a direct output stream
1610 // and all common behaviors are driven by checking only the direct flag
1611 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001612 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1613 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001614 }
Nadav Bar766fb022018-01-07 12:18:03 +02001615 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1616 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001617 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001618
1619 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1620
Eric Laurente83b55d2014-11-14 10:06:21 -08001621 // only allow deep buffering for music stream type
1622 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001623 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001624 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001625 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001626 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1627 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001628 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001629 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001630 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001631 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001632 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001633 audio_is_linear_pcm(config->format) &&
1634 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001635 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001636 AUDIO_OUTPUT_FLAG_DIRECT);
1637 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001638 }
Eric Laurente552edb2014-03-10 17:42:56 -07001639
Carter Hsua3abb402021-10-26 11:11:20 +08001640 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1641 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1642 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1643 }
1644
Eric Laurentf9230d52024-01-26 18:49:09 +01001645 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001646 // was specified and offload or direct playback is not explicitly requested, and there is no
1647 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001648 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001649 if (mSpatializerOutput != nullptr &&
1650 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1651 prefMixerConfigInfo == nullptr &&
1652 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1653 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001654 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001655 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001656 }
1657
Eric Laurentc529cf62020-04-17 18:19:10 -07001658 audio_config_t directConfig = *config;
1659 directConfig.channel_mask = channelMask;
1660 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1661 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001662 return output;
1663 }
1664
Eric Laurent14cbfca2016-03-17 09:42:16 -07001665 // A request for HW A/V sync cannot fallback to a mixed output because time
1666 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001667 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001668 return AUDIO_IO_HANDLE_NONE;
1669 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001670 // A request for Tuner cannot fallback to a mixed output
1671 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1672 return AUDIO_IO_HANDLE_NONE;
1673 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001674
Eric Laurente552edb2014-03-10 17:42:56 -07001675 // ignoring channel mask due to downmix capability in mixer
1676
1677 // open a non direct output
1678
1679 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001680 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001681 // get which output is suitable for the specified stream. The actual
1682 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001683 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001684 if (prefMixerConfigInfo != nullptr) {
1685 for (audio_io_handle_t outputHandle : outputs) {
1686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1687 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1688 output = outputHandle;
1689 break;
1690 }
1691 }
1692 if (output == AUDIO_IO_HANDLE_NONE) {
1693 // No output open with the preferred profile. Open a new one.
1694 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1695 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1696 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1697 config.format = prefMixerConfigInfo->getConfigBase().format;
1698 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1699 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1700 &config, prefMixerConfigInfo->getFlags());
1701 if (preferredOutput == nullptr) {
1702 ALOGE("%s failed to open output with preferred mixer config", __func__);
1703 } else {
1704 output = preferredOutput->mIoHandle;
1705 }
1706 }
1707 } else {
1708 // at this stage we should ignore the DIRECT flag as no direct output could be
1709 // found earlier
1710 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1711 output = selectOutput(
1712 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1713 }
Eric Laurente552edb2014-03-10 17:42:56 -07001714 }
François Gaffie11d30102018-11-02 16:09:09 +01001715 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001716 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001717 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001718
Eric Laurente552edb2014-03-10 17:42:56 -07001719 return output;
1720}
1721
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001722sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001723 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1724 mAvailableInputDevices);
1725 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1726}
1727
1728DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1729 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1730 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001731}
1732
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001733const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001735 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1736 if (msdModule != 0) {
1737 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1738 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1739 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1740 const struct audio_port_config *source = &patch->mPatch.sources[j];
1741 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1742 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001743 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001744 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001745 }
1746 }
1747 }
1748 return msdPatches;
1749}
1750
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001751bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1752 ssize_t index = mAudioPatches.indexOfKey(handle);
1753 if (index < 0) {
1754 return false;
1755 }
1756 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1757 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1758 if (msdModule == nullptr) {
1759 return false;
1760 }
1761 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1762 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1763 return true;
1764 }
1765 index = getMsdOutputPatches().indexOfKey(handle);
1766 if (index < 0) {
1767 return false;
1768 }
1769 return true;
1770}
1771
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001772status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1773 const InputProfileCollection &inputProfiles,
1774 const OutputProfileCollection &outputProfiles,
1775 const sp<DeviceDescriptor> &sourceDevice,
1776 const sp<DeviceDescriptor> &sinkDevice,
1777 AudioProfileVector& sourceProfiles,
1778 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001780 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001781 return NO_INIT;
1782 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 return NO_INIT;
1786 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001787 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1789 inProfile->supportsDevice(sourceDevice)) {
1790 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001791 }
1792 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001793 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001794 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001795 outProfile->supportsDevice(sinkDevice)) {
1796 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001797 }
1798 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001799 return NO_ERROR;
1800}
1801
1802status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1803 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1804 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1805{
Dean Wheatley16809da2022-12-09 14:55:46 +11001806 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1807 static const std::vector<audio_format_t> formatsOrder = {{
1808 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001809 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1810 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001811 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1812 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1813 // preferred).
1814 std::vector<audio_channel_mask_t> masks = {{
1815 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1816 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1817 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1818 // insert index masks (higher counts most preferred) as preferred over position masks
1819 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1820 masks.insert(
1821 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1822 }
1823 return masks;
1824 }();
1825
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001827 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1828 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1831 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001832 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001833 }
1834 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1835 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1836 sinkConfig->format = bestSinkConfig.format;
1837 // For encoded streams force direct flag to prevent downstream mixing.
1838 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1839 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001840 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1841 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001842 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001843 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1844 // raw and IEC61937 framed streams.
1845 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1846 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1847 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1849 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001850 sourceConfig->channel_mask =
1851 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1852 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1853 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 sourceConfig->format = bestSinkConfig.format;
1855 // Copy input stream directly without any processing (e.g. resampling).
1856 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1857 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1858 if (hwAvSync) {
1859 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1860 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1861 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1862 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1863 }
1864 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1865 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1866 sinkConfig->config_mask |= config_mask;
1867 sourceConfig->config_mask |= config_mask;
1868 return NO_ERROR;
1869}
1870
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001871PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1872 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001873{
1874 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001875 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1876 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1877 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1878 if (deviceModule == nullptr) {
1879 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1880 return patchBuilder;
1881 }
1882 const InputProfileCollection inputProfiles = msdIsSource ?
1883 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1884 const OutputProfileCollection outputProfiles = msdIsSource ?
1885 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1886
1887 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1888 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1889 device : getMsdAudioOutDevices().itemAt(0);
1890 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1891
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001892 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1893 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001894 AudioProfileVector sourceProfiles;
1895 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001896 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1897 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001898 for (auto hwAvSync : { true, false }) {
1899 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1900 sourceProfiles, sinkProfiles) != NO_ERROR) {
1901 continue;
1902 }
1903 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1904 &sinkConfig) == NO_ERROR) {
1905 // Found a matching config. Re-create PatchBuilder with this config.
1906 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1907 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001908 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001910 " supporting PCM format conversion.", __func__);
1911 return patchBuilder;
1912}
1913
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001914status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001915 DeviceVector devices;
1916 if (outputDevices != nullptr && outputDevices->size() > 0) {
1917 devices.add(*outputDevices);
1918 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001919 // Use media strategy for unspecified output device. This should only
1920 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1921 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001922 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001923 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001924 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001925 }
Michael Chan6fb34492020-12-08 15:44:49 +11001926 std::vector<PatchBuilder> patchesToCreate;
1927 for (auto i = 0u; i < devices.size(); ++i) {
1928 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001929 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001930 }
1931 // Retain only the MSD patches associated with outputDevices request.
1932 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001933 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001934 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1935 auto retainedPatch = false;
1936 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1937 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1938 patchesToRemove.removeItemsAt(i);
1939 retainedPatch = true;
1940 break;
1941 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001942 }
Michael Chan6fb34492020-12-08 15:44:49 +11001943 if (retainedPatch) {
1944 it = patchesToCreate.erase(it);
1945 continue;
1946 }
1947 ++it;
1948 }
1949 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1950 return NO_ERROR;
1951 }
1952 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1953 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001954 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001955 }
Michael Chan6fb34492020-12-08 15:44:49 +11001956 status_t status = NO_ERROR;
1957 for (const auto &p : patchesToCreate) {
1958 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1959 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1960 char message[256];
1961 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1962 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1963 currStatus == NO_ERROR ? "Success" : "Error",
1964 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1965 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1966 if (currStatus == NO_ERROR) {
1967 ALOGD("%s", message);
1968 } else {
1969 ALOGE("%s", message);
1970 if (status == NO_ERROR) {
1971 status = currStatus;
1972 }
1973 }
1974 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001975 return status;
1976}
1977
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001978void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1979 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001980 for (size_t i = 0; i < msdPatches.size(); i++) {
1981 const auto& patch = msdPatches[i];
1982 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1983 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1984 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1985 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1986 releaseAudioPatch(patch->getHandle(), mUidCached);
1987 break;
1988 }
1989 }
1990 }
1991}
1992
Dorin Drimus94d94412022-02-02 09:05:02 +01001993bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001994 DeviceVector devicesToCheck =
1995 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001996 AudioPatchCollection msdPatches = getMsdOutputPatches();
1997 for (size_t i = 0; i < msdPatches.size(); i++) {
1998 const auto& patch = msdPatches[i];
1999 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2000 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2001 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2002 const auto& foundDevice = devicesToCheck.getDevice(
2003 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2004 if (foundDevice != nullptr) {
2005 devicesToCheck.remove(foundDevice);
2006 if (devicesToCheck.isEmpty()) {
2007 return true;
2008 }
2009 }
2010 }
2011 }
2012 }
2013 return false;
2014}
2015
Eric Laurente0720872014-03-11 09:30:41 -07002016audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002017 audio_output_flags_t flags,
2018 audio_format_t format,
2019 audio_channel_mask_t channelMask,
2020 uint32_t samplingRate,
2021 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002022{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002023 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2024 "%s called with format %#x", __func__, format);
2025
jiabinebb6af42020-06-09 17:31:17 -07002026 // Return the output that haptic-generating attached to when 1) session id is specified,
2027 // 2) haptic-generating effect exists for given session id and 3) the output that
2028 // haptic-generating effect attached to is in given outputs.
2029 if (sessionId != AUDIO_SESSION_NONE) {
2030 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2031 sessionId, FX_IID_HAPTICGENERATOR);
2032 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2033 return hapticGeneratingOutput;
2034 }
2035 }
2036
Eric Laurent16c66dd2019-05-01 17:54:10 -07002037 // Flags disqualifying an output: the match must happen before calling selectOutput()
2038 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2039 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2040
2041 // Flags expressing a functional request: must be honored in priority over
2042 // other criteria
2043 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2044 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002045 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2046 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 // Flags expressing a performance request: have lower priority than serving
2048 // requested sampling rate or channel mask
2049 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2050 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2051 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2052
2053 const audio_output_flags_t functionalFlags =
2054 (audio_output_flags_t)(flags & kFunctionalFlags);
2055 const audio_output_flags_t performanceFlags =
2056 (audio_output_flags_t)(flags & kPerformanceFlags);
2057
2058 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2059
Eric Laurente552edb2014-03-10 17:42:56 -07002060 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002061 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002062 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002063 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002065 // with tiebreak preferring the minimum number of extra functional flags
2066 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 // 3: the output supporting the exact channel mask
2068 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002069 // 5: the output with the highest sampling rate if the requested sample rate is
2070 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002071 // 6: the output with the highest number of requested performance flags
2072 // 7: the output with the bit depth the closest to the requested one
2073 // 8: the primary output
2074 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002075
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 // matching criteria values in priority order for best matching output so far
2077 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002078
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002079 const bool hasOrphanHaptic =
2080 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002081 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2082 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2083 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002084
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002085 for (audio_io_handle_t output : outputs) {
2086 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 // matching criteria values in priority order for current output
2088 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002089
Eric Laurent16c66dd2019-05-01 17:54:10 -07002090 if (outputDesc->isDuplicated()) {
2091 continue;
2092 }
2093 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2094 continue;
2095 }
Eric Laurent8838a382014-09-08 16:44:28 -07002096
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 // If haptic channel is specified, use the haptic output if present.
2098 // When using haptic output, same audio format and sample rate are required.
2099 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002100 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002101 // skip if haptic channel specified but output does not support it, or output support haptic
2102 // but there is no haptic channel requested AND no orphan haptic effect exist
2103 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2104 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002105 continue;
2106 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002107 // In the case of audio-coupled-haptic playback, there is no format conversion and
2108 // resampling in the framework, same format/channel/sampleRate for client and the output
2109 // thread is required. In the case of HapticGenerator effect, do not require format
2110 // matching.
2111 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2112 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002113 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002114 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 }
2116
2117 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002118 const int matchingFunctionalFlags =
2119 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2120 const int totalFunctionalFlags =
2121 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2122 // Prefer matching functional flags, but subtract unnecessary functional flags.
2123 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002124
2125 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002126 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2127 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002128 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2129 channelCount <= outputChannelCount) {
2130 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002131 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2132 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002133 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002134 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135 currentMatchCriteria[3] = outputChannelCount;
2136 }
2137
2138 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002139 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002140 int diff; // avoid unsigned integer overflow.
2141 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2142
2143 // prefer the closest output sampling rate greater than or equal to target
2144 // if none exists, prefer the closest output sampling rate less than target.
2145 //
2146 // criteria is offset to make non-negative.
2147 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002148 }
2149
2150 // performance flags match
2151 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2152
2153 // format match
2154 if (format != AUDIO_FORMAT_INVALID) {
2155 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002156 PolicyAudioPort::kFormatDistanceMax -
2157 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002158 }
2159
2160 // primary output match
2161 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2162
2163 // compare match criteria by priority then value
2164 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2165 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2166 bestMatchCriteria = currentMatchCriteria;
2167 bestOutput = output;
2168
2169 std::stringstream result;
2170 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2171 std::ostream_iterator<int>(result, " "));
2172 ALOGV("%s new bestOutput %d criteria %s",
2173 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002174 }
2175 }
2176
Eric Laurent16c66dd2019-05-01 17:54:10 -07002177 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002178}
2179
Eric Laurent8fc147b2018-07-22 19:13:55 -07002180status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002181{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002182 ALOGV("%s portId %d", __FUNCTION__, portId);
2183
2184 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2185 if (outputDesc == 0) {
2186 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002187 return BAD_VALUE;
2188 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002189 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002190
Eric Laurent8fc147b2018-07-22 19:13:55 -07002191 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002192 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002193
Eric Laurent733ce942017-12-07 12:18:25 -08002194 status_t status = outputDesc->start();
2195 if (status != NO_ERROR) {
2196 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002197 }
2198
Eric Laurent97ac8712018-07-27 18:59:02 -07002199 uint32_t delayMs;
2200 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002201
2202 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002203 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002204 if (status == DEAD_OBJECT) {
2205 sp<SwAudioOutputDescriptor> desc =
2206 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2207 if (desc == nullptr) {
2208 // This is not common, it may indicate something wrong with the HAL.
2209 ALOGE("%s unable to open output with default config", __func__);
2210 return status;
2211 }
2212 desc->mUsePreferredMixerAttributes = true;
2213 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002214 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002215 }
jiabina84c3d32022-12-02 18:59:55 +00002216
2217 // If the client is the first one active on preferred mixer parameters, reopen the output
2218 // if the current mixer parameters doesn't match the preferred one.
2219 if (outputDesc->devices().size() == 1) {
2220 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2221 outputDesc->devices()[0]->getId(), client->strategy());
2222 if (info != nullptr && info->getUid() == client->uid()) {
2223 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2224 info->getConfigBase(), info->getFlags())) {
2225 stopSource(outputDesc, client);
2226 outputDesc->stop();
2227 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2228 config.channel_mask = info->getConfigBase().channel_mask;
2229 config.sample_rate = info->getConfigBase().sample_rate;
2230 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002231 sp<SwAudioOutputDescriptor> desc =
2232 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2233 if (desc == nullptr) {
2234 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002235 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002236 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002237 // Intentionally return error to let the client side resending request for
2238 // creating and starting.
2239 return DEAD_OBJECT;
2240 }
2241 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002242 if (info->getActiveClientCount() == 1 &&
2243 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2244 // If it is first bit-perfect client, reroute all clients that will be routed to
2245 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2246 PortHandleVector clientsToInvalidate;
2247 for (size_t i = 0; i < mOutputs.size(); i++) {
2248 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002249 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002250 continue;
2251 }
2252 for (const auto& c : mOutputs[i]->getClientIterable()) {
2253 clientsToInvalidate.push_back(c->portId());
2254 }
2255 }
2256 if (!clientsToInvalidate.empty()) {
2257 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2258 __func__);
2259 mpClientInterface->invalidateTracks(clientsToInvalidate);
2260 }
2261 }
jiabina84c3d32022-12-02 18:59:55 +00002262 }
2263 }
2264
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002265 if (client->hasPreferredDevice()) {
2266 // playback activity with preferred device impacts routing occurred, inform upper layers
2267 mpClientInterface->onRoutingUpdated();
2268 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002269 if (delayMs != 0) {
2270 usleep(delayMs * 1000);
2271 }
2272
2273 return status;
2274}
2275
Eric Laurent96d1dda2022-03-14 17:14:19 +01002276bool AudioPolicyManager::isLeUnicastActive() const {
2277 if (isInCall()) {
2278 return true;
2279 }
2280 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2281}
2282
2283bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2284 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2285 return false;
2286 }
2287 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2288 ALOGV("%s active %d", __func__, active);
2289 return active;
2290}
2291
Eric Laurent97ac8712018-07-27 18:59:02 -07002292status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2293 const sp<TrackClientDescriptor>& client,
2294 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002295{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002296 // cannot start playback of STREAM_TTS if any other output is being used
2297 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002298
2299 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002300 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002301 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002302 auto clientStrategy = client->strategy();
2303 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002304 if (stream == AUDIO_STREAM_TTS) {
2305 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002306 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002307 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002308 return INVALID_OPERATION;
2309 } else {
2310 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2311 }
2312 } else {
2313 // some playback other than beacon starts
2314 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2315 }
2316
Eric Laurent77305a62016-07-25 16:39:22 -07002317 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002318 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002319 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002320
François Gaffie11d30102018-11-02 16:09:09 +01002321 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002322 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002323 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002324 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002325 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002326 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002327 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002328 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002329 } else {
2330 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002331 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002332 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2333 AUDIO_FORMAT_DEFAULT);
2334 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2335 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002336 }
2337
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002338 // requiresMuteCheck is false when we can bypass mute strategy.
2339 // It covers a common case when there is no materially active audio
2340 // and muting would result in unnecessary delay and dropped audio.
2341 const uint32_t outputLatencyMs = outputDesc->latency();
2342 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002343 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002344
Eric Laurente552edb2014-03-10 17:42:56 -07002345 // increment usage count for this stream on the requested output:
2346 // NOTE that the usage count is the same for duplicated output and hardware output which is
2347 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002348 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002349
2350 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002351 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002352 // Preferred device may be exclusive, use only if no other active clients on this output
2353 devices = DeviceVector(
2354 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2355 } else {
2356 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2357 }
François Gaffie11d30102018-11-02 16:09:09 +01002358 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002359 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002360 }
2361 }
Eric Laurente552edb2014-03-10 17:42:56 -07002362
François Gaffiec005e562018-11-06 15:04:49 +01002363 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002364 selectOutputForMusicEffects();
2365 }
2366
François Gaffie1c878552018-11-22 16:53:21 +01002367 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002368 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002369 if (devices.isEmpty()) {
2370 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002371 }
François Gaffiec005e562018-11-06 15:04:49 +01002372 bool shouldWait =
2373 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2374 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2375 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002376 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002377 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002378 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002379 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002380 // An output has a shared device if
2381 // - managed by the same hw module
2382 // - supports the currently selected device
2383 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002384 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002385
Eric Laurent77305a62016-07-25 16:39:22 -07002386 // force a device change if any other output is:
2387 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002388 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002389 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002390 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002391 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002392 // change the device currently selected by the other output.
2393 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002394 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002395 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002396 force = true;
2397 }
2398 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002399 // a notification so that audio focus effect can propagate, or that a mute/unmute
2400 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002401 const uint32_t latencyMs = desc->latency();
2402 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2403
2404 if (shouldWait && isActive && (waitMs < latencyMs)) {
2405 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002406 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002407
2408 // Require mute check if another output is on a shared device
2409 // and currently active to have proper drain and avoid pops.
2410 // Note restoring AudioTracks onto this output needs to invoke
2411 // a volume ramp if there is no mute.
2412 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002413 }
2414 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002415
jiabin3ff8d7d2022-12-13 06:27:44 +00002416 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2417 // If the output is open with preferred mixer attributes, but the routed device is
2418 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2419 // changed.
2420 return DEAD_OBJECT;
2421 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002422 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302423 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2424 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002425
Eric Laurente552edb2014-03-10 17:42:56 -07002426 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002427 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002428 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002429 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002430 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002431 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002432 outputDesc->useHwGain() /*force*/)) {
2433 // request AudioService to reinitialize the volume curves asynchronously
2434 ALOGE("checkAndSetVolume failed, requesting volume range init");
2435 mpClientInterface->onVolumeRangeInitRequest();
2436 };
Eric Laurente552edb2014-03-10 17:42:56 -07002437
2438 // update the outputs if starting an output with a stream that can affect notification
2439 // routing
2440 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002441
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002442 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002443 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002444 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002445 }
Eric Laurentdc462862016-07-19 12:29:53 -07002446
2447 if (waitMs > muteWaitMs) {
2448 *delayMs = waitMs - muteWaitMs;
2449 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002450
2451 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2452 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2453 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2454 // change occurs after the MixerThread starts and causes a stream volume
2455 // glitch.
2456 //
2457 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002458 }
Eric Laurentdc462862016-07-19 12:29:53 -07002459
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002460 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002461 mEngine->getForceUse(
2462 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002463 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002464 }
2465
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 // Automatically enable the remote submix input when output is started on a re routing mix
2467 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002468 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2469 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002470 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2471 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2472 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002473 "remote-submix",
2474 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002475 }
2476
Eric Laurent96d1dda2022-03-14 17:14:19 +01002477 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2478
Eric Laurente552edb2014-03-10 17:42:56 -07002479 return NO_ERROR;
2480}
2481
Eric Laurent96d1dda2022-03-14 17:14:19 +01002482void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2483 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2484 bool isUnicastActive = isLeUnicastActive();
2485
2486 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002487 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002488 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2489 for (size_t i = 0; i < mOutputs.size(); i++) {
2490 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2491 if (desc != ignoredOutput && desc->isActive()
2492 && ((isUnicastActive &&
2493 !desc->devices().
2494 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2495 || (wasUnicastActive &&
2496 !desc->devices().getDevicesFromTypes(
2497 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2498 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2499 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002500 if (desc->mUsePreferredMixerAttributes && force) {
2501 // If the device is using preferred mixer attributes, the output need to reopen
2502 // with default configuration when the new selected devices are different from
2503 // current routing devices.
2504 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2505 continue;
2506 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302507 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002508 // re-apply device specific volume if not done by setOutputDevice()
2509 if (!force) {
2510 applyStreamVolumes(desc, newDevices.types(), delayMs);
2511 }
2512 }
2513 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002514 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002515 }
2516}
2517
Eric Laurent8fc147b2018-07-22 19:13:55 -07002518status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002519{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002520 ALOGV("%s portId %d", __FUNCTION__, portId);
2521
2522 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2523 if (outputDesc == 0) {
2524 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002525 return BAD_VALUE;
2526 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002527 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002528
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002529 if (client->hasPreferredDevice(true)) {
2530 // playback activity with preferred device impacts routing occurred, inform upper layers
2531 mpClientInterface->onRoutingUpdated();
2532 }
2533
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 ALOGV("stopOutput() output %d, stream %d, session %d",
2535 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002536
Eric Laurent97ac8712018-07-27 18:59:02 -07002537 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002538
Eric Laurent733ce942017-12-07 12:18:25 -08002539 if (status == NO_ERROR ) {
2540 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002541 } else {
2542 return status;
2543 }
2544
2545 if (outputDesc->devices().size() == 1) {
2546 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2547 outputDesc->devices()[0]->getId(), client->strategy());
2548 if (info != nullptr && info->getUid() == client->uid()) {
2549 info->decreaseActiveClient();
2550 if (info->getActiveClientCount() == 0) {
2551 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2552 }
2553 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002554 }
2555 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002556}
2557
Eric Laurent97ac8712018-07-27 18:59:02 -07002558status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2559 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002560{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002561 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002562 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002563 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002564 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002565
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002566 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2567
François Gaffie1c878552018-11-22 16:53:21 +01002568 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2569 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002570 // Automatically disable the remote submix input when output is stopped on a
2571 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002572 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002573 if (isSingleDeviceType(
2574 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002575 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002576 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002577 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2578 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002579 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002580 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002581 }
2582 }
2583 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002584 if (client->hasPreferredDevice(true) &&
2585 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002586 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002587 forceDeviceUpdate = true;
2588 }
2589
Eric Laurente552edb2014-03-10 17:42:56 -07002590 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002591 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002592
Eric Laurente552edb2014-03-10 17:42:56 -07002593 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002594 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002595 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002596 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002597
2598 // If the routing does not change, if an output is routed on a device using HwGain
2599 // (aka setAudioPortConfig) and there are still active clients following different
2600 // volume group(s), force reapply volume
2601 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2602 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2603
Eric Laurente552edb2014-03-10 17:42:56 -07002604 // delay the device switch by twice the latency because stopOutput() is executed when
2605 // the track stop() command is received and at that time the audio track buffer can
2606 // still contain data that needs to be drained. The latency only covers the audio HAL
2607 // and kernel buffers. Also the latency does not always include additional delay in the
2608 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302609 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002610 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002611
2612 // force restoring the device selection on other active outputs if it differs from the
2613 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002614 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002615 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002616 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002617 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002618 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002619 desc->isActive() &&
2620 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002621 (newDevices != desc->devices())) {
2622 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2623 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002624
jiabin3ff8d7d2022-12-13 06:27:44 +00002625 if (desc->mUsePreferredMixerAttributes && force) {
2626 // If the device is using preferred mixer attributes, the output need to
2627 // reopen with default configuration when the new selected devices are
2628 // different from current routing devices.
2629 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2630 continue;
2631 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302632 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002633
Eric Laurent57de36c2016-09-28 16:59:11 -07002634 // re-apply device specific volume if not done by setOutputDevice()
2635 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002636 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002637 }
Eric Laurente552edb2014-03-10 17:42:56 -07002638 }
2639 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002640 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002641 // update the outputs if stopping one with a stream that can affect notification routing
2642 handleNotificationRoutingForStream(stream);
2643 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002644
2645 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2646 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002647 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002648 }
2649
François Gaffiec005e562018-11-06 15:04:49 +01002650 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002651 selectOutputForMusicEffects();
2652 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002653
2654 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2655
Eric Laurente552edb2014-03-10 17:42:56 -07002656 return NO_ERROR;
2657 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002658 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002659 return INVALID_OPERATION;
2660 }
2661}
2662
jiabinbce0c1d2020-10-05 11:20:18 -07002663bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002664{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002665 ALOGV("%s portId %d", __FUNCTION__, portId);
2666
2667 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2668 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002669 // If an output descriptor is closed due to a device routing change,
2670 // then there are race conditions with releaseOutput from tracks
2671 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2672 // destroyed shortly thereafter.
2673 //
2674 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002675 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002676 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002677 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002678
2679 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002680
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302681 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2682 if (outputDesc->isClientActive(client)) {
2683 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2684 stopOutput(portId);
2685 }
2686
Eric Laurent8fc147b2018-07-22 19:13:55 -07002687 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2688 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002689 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002690 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002691 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002692 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002693 if (--outputDesc->mDirectOpenCount == 0) {
2694 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002695 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002696 }
2697 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302698
Andy Hung39efb7a2018-09-26 15:39:28 -07002699 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002700 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2701 // The output is pending reopened to query dynamic profiles and
2702 // there is no active clients
2703 closeOutput(outputDesc->mIoHandle);
2704 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2705 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2706 if (newOutputDesc == nullptr) {
2707 ALOGE("%s failed to open output", __func__);
2708 }
2709 return true;
2710 }
2711 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002712}
2713
Eric Laurentcaf7f482014-11-25 17:50:47 -08002714status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2715 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002716 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002717 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002718 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002719 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002720 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002721 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002722 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002723 audio_port_handle_t *portId,
2724 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002725{
François Gaffiec005e562018-11-06 15:04:49 +01002726 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002727 "flags %#x attributes=%s requested device ID %d",
2728 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2729 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002730
Eric Laurentad2e7b92017-09-14 20:06:42 -07002731 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002732 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002733 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002734 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002735 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002736 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002737 sp<RecordClientDescriptor> clientDesc;
2738 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002739 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002740 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002741
2742 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2743 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2744 return INVALID_OPERATION;
2745 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002746
Francois Gaffie716e1432019-01-14 16:58:59 +01002747 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2748 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002749 }
2750
Paul McLean466dc8e2015-04-17 13:15:36 -06002751 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002752 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002753 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002754
Eric Laurentad2e7b92017-09-14 20:06:42 -07002755 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2756 // possible
2757 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2758 *input != AUDIO_IO_HANDLE_NONE) {
2759 ssize_t index = mInputs.indexOfKey(*input);
2760 if (index < 0) {
2761 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2762 status = BAD_VALUE;
2763 goto error;
2764 }
2765 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002766 RecordClientVector clients = inputDesc->getClientsForSession(session);
2767 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002768 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2769 status = BAD_VALUE;
2770 goto error;
2771 }
2772 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2773 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002774 // corresponds to a new client and is only permitted from the same UID.
2775 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002776 if (clients.size() > 1) {
2777 for (const auto& client : clients) {
2778 // The client map is ordered by key values (portId) and portIds are allocated
2779 // incrementaly. So the first client in this list is the one opened by audio flinger
2780 // when the mmap stream is created and should be ignored as it does not correspond
2781 // to an actual client
2782 if (client == *clients.cbegin()) {
2783 continue;
2784 }
2785 if (uid != client->uid() && !client->isSilenced()) {
2786 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2787 uid, client->portId(), client->uid());
2788 status = INVALID_OPERATION;
2789 goto error;
2790 }
Eric Laurent331679c2018-04-16 17:03:16 -07002791 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002792 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002793 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002794 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002795
Eric Laurentfecbceb2021-02-09 14:46:43 +01002796 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002797 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002798 }
2799
2800 *input = AUDIO_IO_HANDLE_NONE;
2801 *inputType = API_INPUT_INVALID;
2802
Francois Gaffie716e1432019-01-14 16:58:59 +01002803 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002804 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002805 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002806 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002807 ALOGW("%s could not find input mix for attr %s",
2808 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002809 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002810 }
jiabinc1de2df2019-05-07 14:26:40 -07002811 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2812 String8(attr->tags + strlen("addr=")),
2813 AUDIO_FORMAT_DEFAULT);
2814 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002815 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002816 __func__, attributes.source, attributes.tags);
2817 status = BAD_VALUE;
2818 goto error;
2819 }
2820
Kevin Rocard25f9b052019-02-27 15:08:54 -08002821 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2822 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2823 } else {
2824 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2825 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002826 if (virtualDeviceId) {
2827 *virtualDeviceId = policyMix->mVirtualDeviceId;
2828 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002829 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002830 if (explicitRoutingDevice != nullptr) {
2831 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002832 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002833 // Prevent from storing invalid requested device id in clients
2834 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002835 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002836 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2837 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002838 }
François Gaffie11d30102018-11-02 16:09:09 +01002839 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002840 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002841 status = BAD_VALUE;
2842 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002843 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002844 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2845 *inputType = API_INPUT_MIX_CAPTURE;
2846 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002847 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2848 // there is an external policy, but this input is attached to a mix of recorders,
2849 // meaning it receives audio injected into the framework, so the recorder doesn't
2850 // know about it and is therefore considered "legacy"
2851 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002852
2853 if (virtualDeviceId) {
2854 *virtualDeviceId = policyMix->mVirtualDeviceId;
2855 }
François Gaffie11d30102018-11-02 16:09:09 +01002856 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002857 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002858 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002859 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002860 } else {
2861 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002862 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002863
Eric Laurent599c7582015-12-07 18:05:55 -08002864 }
2865
François Gaffiec005e562018-11-06 15:04:49 +01002866 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002867 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002868 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002869 AudioProfileVector profiles;
2870 status_t ret = getProfilesForDevices(
2871 DeviceVector(device), profiles, flags, true /*isInput*/);
2872 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002873 const auto channels = profiles[0]->getChannels();
2874 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2875 config->channel_mask = *channels.begin();
2876 }
2877 const auto sampleRates = profiles[0]->getSampleRates();
2878 if (!sampleRates.empty() &&
2879 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2880 config->sample_rate = *sampleRates.begin();
2881 }
jiabinf1c73972022-04-14 16:28:52 -07002882 config->format = profiles[0]->getFormat();
2883 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002884 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002885 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002886
Marvin Ramine5a122d2023-12-07 13:57:59 +01002887
2888 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2889 *virtualDeviceId = policyMix->mVirtualDeviceId;
2890 }
2891
Eric Laurent8f42ea12018-08-08 09:08:25 -07002892exit:
2893
François Gaffiec005e562018-11-06 15:04:49 +01002894 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2895 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002896
Francois Gaffie716e1432019-01-14 16:58:59 +01002897 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002898 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002899 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002900
Mikhail Naganov2996f672019-04-18 12:29:59 -07002901 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002902 requestedDeviceId, attributes.source, flags,
2903 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002905 // Move (if found) effect for the client session to its input
2906 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002907 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002908
2909 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2910 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002911
Eric Laurent599c7582015-12-07 18:05:55 -08002912 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002913
2914error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002915 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002916}
2917
2918
François Gaffie11d30102018-11-02 16:09:09 +01002919audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002920 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002921 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002922 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002923 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002924 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002925{
2926 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002927 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002928 bool isSoundTrigger = false;
2929
François Gaffiec005e562018-11-06 15:04:49 +01002930 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002931 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2932 if (index >= 0) {
2933 input = mSoundTriggerSessions.valueFor(session);
2934 isSoundTrigger = true;
2935 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2936 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2937 } else {
2938 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002939 }
François Gaffiec005e562018-11-06 15:04:49 +01002940 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002941 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002942 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002943 }
2944
Carter Hsua3abb402021-10-26 11:11:20 +08002945 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2946 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2947 }
2948
Eric Laurentfe231122017-11-17 17:48:06 -08002949 // sampling rate and flags may be updated by getInputProfile
2950 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2951 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002952 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002953 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002954 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002955 // find a compatible input profile (not necessarily identical in parameters)
2956 sp<IOProfile> profile = getInputProfile(
2957 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2958 if (profile == nullptr) {
2959 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002960 }
jiabin2fd710d2022-05-02 23:20:22 +00002961
Glenn Kasten05ddca52016-02-11 08:17:12 -08002962 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002963 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002964 if (samplingRate == 0) {
2965 samplingRate = profileSamplingRate;
2966 }
Eric Laurente552edb2014-03-10 17:42:56 -07002967
Eric Laurent322b4d22015-04-03 15:57:54 -07002968 if (profile->getModuleHandle() == 0) {
2969 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002970 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002971 }
2972
Eric Laurentec376dc2021-04-08 20:41:22 +02002973 // Reuse an already opened input if a client with the same session ID already exists
2974 // on that input
2975 for (size_t i = 0; i < mInputs.size(); i++) {
2976 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2977 if (desc->mProfile != profile) {
2978 continue;
2979 }
2980 RecordClientVector clients = desc->clientsList();
2981 for (const auto &client : clients) {
2982 if (session == client->session()) {
2983 return desc->mIoHandle;
2984 }
2985 }
2986 }
2987
Eric Laurent3974e3b2017-12-07 17:58:43 -08002988 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002989 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002990 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002991 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002992 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002993 continue;
2994 }
2995 // if sound trigger, reuse input if used by other sound trigger on same session
2996 // else
2997 // reuse input if active client app is not in IDLE state
2998 //
2999 RecordClientVector clients = desc->clientsList();
3000 bool doClose = false;
3001 for (const auto& client : clients) {
3002 if (isSoundTrigger != client->isSoundTrigger()) {
3003 continue;
3004 }
3005 if (client->isSoundTrigger()) {
3006 if (session == client->session()) {
3007 return desc->mIoHandle;
3008 }
3009 continue;
3010 }
3011 if (client->active() && client->appState() != APP_STATE_IDLE) {
3012 return desc->mIoHandle;
3013 }
3014 doClose = true;
3015 }
3016 if (doClose) {
3017 closeInput(desc->mIoHandle);
3018 } else {
3019 i++;
3020 }
3021 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003022 }
3023
Eric Laurentfe231122017-11-17 17:48:06 -08003024 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003025
Eric Laurentfe231122017-11-17 17:48:06 -08003026 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3027 lConfig.sample_rate = profileSamplingRate;
3028 lConfig.channel_mask = profileChannelMask;
3029 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003030
François Gaffie11d30102018-11-02 16:09:09 +01003031 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003032
3033 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003034 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003035 (profileSamplingRate != lConfig.sample_rate) ||
3036 !audio_formats_match(profileFormat, lConfig.format) ||
3037 (profileChannelMask != lConfig.channel_mask)) {
3038 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003039 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003040 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003041 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003042 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003043 }
Eric Laurent599c7582015-12-07 18:05:55 -08003044 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003045 }
3046
Eric Laurentc722f302014-12-10 11:21:49 -08003047 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003048
Eric Laurent599c7582015-12-07 18:05:55 -08003049 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003050 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003051
Eric Laurent599c7582015-12-07 18:05:55 -08003052 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003053}
3054
Eric Laurent4eb58f12018-12-07 16:41:02 -08003055status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003056{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003057 ALOGV("%s portId %d", __FUNCTION__, portId);
3058
3059 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3060 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003062 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003063 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003064 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003065 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 if (client->active()) {
3067 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3068 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003069 }
3070
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 audio_session_t session = client->session();
3072
Eric Laurent4eb58f12018-12-07 16:41:02 -08003073 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074
Eric Laurent4eb58f12018-12-07 16:41:02 -08003075 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003076
Eric Laurent4eb58f12018-12-07 16:41:02 -08003077 status_t status = inputDesc->start();
3078 if (status != NO_ERROR) {
3079 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003080 }
Eric Laurente552edb2014-03-10 17:42:56 -07003081
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003082 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003083 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003085
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 // indicate active capture to sound trigger service if starting capture from a mic on
3087 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003088 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003089 if (device != nullptr) {
3090 status = setInputDevice(input, device, true /* force */);
3091 } else {
3092 ALOGW("%s no new input device can be found for descriptor %d",
3093 __FUNCTION__, inputDesc->getId());
3094 status = BAD_VALUE;
3095 }
Eric Laurente552edb2014-03-10 17:42:56 -07003096
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003097 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003098 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003100 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003101 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3102 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003104 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003105
François Gaffie11d30102018-11-02 16:09:09 +01003106 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3107 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003109 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003111
Eric Laurent8f42ea12018-08-08 09:08:25 -07003112 // automatically enable the remote submix output when input is started if not
3113 // used by a policy mix of type MIX_TYPE_RECORDERS
3114 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003115 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003116 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003117 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003119 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3120 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003121 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 if (address != "") {
3123 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3124 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003125 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003126 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003127 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003128 } else if (status != NO_ERROR) {
3129 // Restore client activity state.
3130 inputDesc->setClientActive(client, false);
3131 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003132 }
3133
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003134 ALOGV("%s input %d source = %d status = %d exit",
3135 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003136
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003137 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003138}
3139
Eric Laurent8fc147b2018-07-22 19:13:55 -07003140status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003141{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003142 ALOGV("%s portId %d", __FUNCTION__, portId);
3143
3144 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3145 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003146 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003147 return BAD_VALUE;
3148 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003149 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003150 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003151 if (!client->active()) {
3152 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003153 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003154 }
Carter Hsue6139d52021-07-08 10:30:20 +08003155 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003156 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003157
Eric Laurent8f42ea12018-08-08 09:08:25 -07003158 inputDesc->stop();
3159 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003160 auto current_source = inputDesc->source();
3161 setInputDevice(input, getNewInputDevice(inputDesc),
3162 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003164 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003165 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003166 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003167 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3168 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003169 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003170 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003171
3172 // automatically disable the remote submix output when input is stopped if not
3173 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003174 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003175 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003176 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003177 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003178 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3179 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003180 }
3181 if (address != "") {
3182 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3183 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003184 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 }
3186 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003187 resetInputDevice(input);
3188
3189 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3190 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003191 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3192 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003193 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003194 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003195 }
3196 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003197 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003198 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003199}
3200
Eric Laurent8fc147b2018-07-22 19:13:55 -07003201void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003202{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003203 ALOGV("%s portId %d", __FUNCTION__, portId);
3204
3205 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3206 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003207 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003208 return;
3209 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003210 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003211 audio_io_handle_t input = inputDesc->mIoHandle;
3212
Eric Laurent8f42ea12018-08-08 09:08:25 -07003213 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003214
Andy Hung39efb7a2018-09-26 15:39:28 -07003215 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003216
3217 // If no more clients are present in this session, park effects to an orphan chain
3218 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3219 if (clientsOnSession.size() == 0) {
3220 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3221 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003222 if (inputDesc->getClientCount() > 0) {
3223 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003224 return;
3225 }
3226
Eric Laurent05b90f82014-08-27 15:32:29 -07003227 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003228 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003229 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003230}
3231
Eric Laurent8f42ea12018-08-08 09:08:25 -07003232void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003233{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003234 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003235
3236 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003238 }
3239}
3240
Eric Laurent8f42ea12018-08-08 09:08:25 -07003241void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3242{
3243 stopInput(portId);
3244 releaseInput(portId);
3245}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003246
Eric Laurent0dd51852019-04-19 18:18:58 -07003247void AudioPolicyManager::checkCloseInputs() {
3248 // After connecting or disconnecting an input device, close input if:
3249 // - it has no client (was just opened to check profile) OR
3250 // - none of its supported devices are connected anymore OR
3251 // - one of its clients cannot be routed to one of its supported
3252 // devices anymore. Otherwise update device selection
3253 std::vector<audio_io_handle_t> inputsToClose;
3254 for (size_t i = 0; i < mInputs.size(); i++) {
3255 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3256 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003257 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003258 inputsToClose.push_back(mInputs.keyAt(i));
3259 } else {
3260 bool close = false;
3261 for (const auto& client : input->clientsList()) {
3262 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003263 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3264 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003265 if (!input->supportedDevices().contains(device)) {
3266 close = true;
3267 break;
3268 }
3269 }
3270 if (close) {
3271 inputsToClose.push_back(mInputs.keyAt(i));
3272 } else {
3273 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3274 }
3275 }
3276 }
3277
3278 for (const audio_io_handle_t handle : inputsToClose) {
3279 ALOGV("%s closing input %d", __func__, handle);
3280 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003281 }
Eric Laurentd4692962014-05-05 18:13:44 -07003282}
3283
François Gaffie251c7f02018-11-07 10:41:08 +01003284void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003285{
3286 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003287 if (indexMin < 0 || indexMax < 0) {
3288 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3289 return;
3290 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003291 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003292
3293 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003294 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3295 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003296 continue;
3297 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003298 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003299 }
Eric Laurente552edb2014-03-10 17:42:56 -07003300}
3301
Eric Laurente0720872014-03-11 09:30:41 -07003302status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003303 int index,
3304 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003305{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003306 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003307 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3308 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3309 return NO_ERROR;
3310 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003311 ALOGV("%s: stream %s attributes=%s", __func__,
3312 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003313 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003314}
3315
Eric Laurente0720872014-03-11 09:30:41 -07003316status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003317 int *index,
3318 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003319{
François Gaffiec005e562018-11-06 15:04:49 +01003320 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3321 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003322 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003323 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003324 deviceTypes = mEngine->getOutputDevicesForStream(
3325 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003326 }
jiabin9a3361e2019-10-01 09:38:30 -07003327 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003328}
3329
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003330status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003331 int index,
3332 audio_devices_t device)
3333{
3334 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003335 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3336 if (group == VOLUME_GROUP_NONE) {
3337 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003338 return BAD_VALUE;
3339 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003340 ALOGV("%s: group %d matching with %s index %d",
3341 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003342 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003343 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003344 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003345 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3346 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3347 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3348 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003349 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3350
3351 status = setVolumeCurveIndex(index, device, curves);
3352 if (status != NO_ERROR) {
3353 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3354 return status;
3355 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003356
jiabin9a3361e2019-10-01 09:38:30 -07003357 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003358 auto curCurvAttrs = curves.getAttributes();
3359 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3360 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003361 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003362 } else if (!curves.getStreamTypes().empty()) {
3363 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003364 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003365 } else {
3366 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3367 return BAD_VALUE;
3368 }
jiabin9a3361e2019-10-01 09:38:30 -07003369 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3370 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003371
François Gaffiecfe17322018-11-07 13:41:29 +01003372 // update volume on all outputs and streams matching the following:
3373 // - The requested stream (or a stream matching for volume control) is active on the output
3374 // - The device (or devices) selected by the engine for this stream includes
3375 // the requested device
3376 // - For non default requested device, currently selected device on the output is either the
3377 // requested device or one of the devices selected by the engine for this stream
3378 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3379 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003380 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003381 for (size_t i = 0; i < mOutputs.size(); i++) {
3382 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003383 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003384
jiabin9a3361e2019-10-01 09:38:30 -07003385 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3386 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003387 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003388
3389 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003390 continue;
3391 }
3392 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3393 curDevices.find(device) == curDevices.end()) {
3394 continue;
3395 }
3396 bool applyVolume = false;
3397 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3398 curSrcDevices.insert(device);
3399 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003400 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3401 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003402 } else {
3403 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3404 }
3405 if (!applyVolume) {
3406 continue; // next output
3407 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003408 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3409 // If a higher priority strategy is active, and the output is routed to a device with a
3410 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003411 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003412 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003413 // If the volume source is active with higher priority source, ensure at least Sw Muted
3414 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003415 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3416 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3417 false /*preferredDevice*/);
3418 if (activeClients.empty()) {
3419 continue;
3420 }
3421 bool isPreempted = false;
3422 bool isHigherPriority = productStrategy < strategy;
3423 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003424 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003425 ALOGV("%s: Strategy=%d (\nrequester:\n"
3426 " group %d, volumeGroup=%d attributes=%s)\n"
3427 " higher priority source active:\n"
3428 " volumeGroup=%d attributes=%s) \n"
3429 " on output %zu, bailing out", __func__, productStrategy,
3430 group, group, toString(attributes).c_str(),
3431 client->volumeSource(), toString(client->attributes()).c_str(), i);
3432 applyVolume = false;
3433 isPreempted = true;
3434 break;
3435 }
3436 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003437 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003438 applyVolume = true;
3439 }
3440 }
3441 if (isPreempted || applyVolume) {
3442 break;
3443 }
3444 }
3445 if (!applyVolume) {
3446 continue; // next output
3447 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003448 }
François Gaffieed91f582020-01-31 10:35:37 +01003449 //FIXME: workaround for truncated touch sounds
3450 // delayed volume change for system stream to be removed when the problem is
3451 // handled by system UI
3452 status_t volStatus = checkAndSetVolume(
3453 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003454 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003455 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3456 if (volStatus != NO_ERROR) {
3457 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003458 }
3459 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003460
3461 // update voice volume if the an active call route exists
3462 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3463 && (curSrcDevices.find(
3464 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3465 != curSrcDevices.end())) {
3466 bool isVoiceVolSrc;
3467 bool isBtScoVolSrc;
3468 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3469 isVoiceVolSrc, isBtScoVolSrc, __func__)
3470 && (isVoiceVolSrc || isBtScoVolSrc)) {
3471 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3472 }
3473 }
3474
François Gaffiecfe17322018-11-07 13:41:29 +01003475 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3476 return status;
3477}
3478
François Gaffieaaac0fd2018-11-22 17:56:39 +01003479status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003480 audio_devices_t device,
3481 IVolumeCurves &volumeCurves)
3482{
3483 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3484 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003485 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3486 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003487 (index > volumeCurves.getVolumeIndexMax())) {
3488 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3489 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3490 return BAD_VALUE;
3491 }
3492 if (!audio_is_output_device(device)) {
3493 return BAD_VALUE;
3494 }
3495
3496 // Force max volume if stream cannot be muted
3497 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3498
François Gaffieaaac0fd2018-11-22 17:56:39 +01003499 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003500 volumeCurves.addCurrentVolumeIndex(device, index);
3501 return NO_ERROR;
3502}
3503
3504status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3505 int &index,
3506 audio_devices_t device)
3507{
3508 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3509 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003510 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003511 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003512 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003513 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003514 }
jiabin9a3361e2019-10-01 09:38:30 -07003515 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003516}
3517
3518status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3519 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003520 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003521{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003522 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003523 return BAD_VALUE;
3524 }
jiabin9a3361e2019-10-01 09:38:30 -07003525 index = curves.getVolumeIndex(deviceTypes);
3526 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003527 return NO_ERROR;
3528}
3529
3530status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3531 int &index)
3532{
3533 index = getVolumeCurves(attr).getVolumeIndexMin();
3534 return NO_ERROR;
3535}
3536
3537status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3538 int &index)
3539{
3540 index = getVolumeCurves(attr).getVolumeIndexMax();
3541 return NO_ERROR;
3542}
3543
Eric Laurent36829f92017-04-07 19:04:42 -07003544audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003545{
3546 // select one output among several suitable for global effects.
3547 // The priority is as follows:
3548 // 1: An offloaded output. If the effect ends up not being offloadable,
3549 // AudioFlinger will invalidate the track and the offloaded output
3550 // will be closed causing the effect to be moved to a PCM output.
3551 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003552 // 3: The primary output
3553 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003554
François Gaffiec005e562018-11-06 15:04:49 +01003555 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3556 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003557 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003558
Eric Laurent36829f92017-04-07 19:04:42 -07003559 if (outputs.size() == 0) {
3560 return AUDIO_IO_HANDLE_NONE;
3561 }
Eric Laurente552edb2014-03-10 17:42:56 -07003562
Eric Laurent36829f92017-04-07 19:04:42 -07003563 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3564 bool activeOnly = true;
3565
3566 while (output == AUDIO_IO_HANDLE_NONE) {
3567 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3568 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3569 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3570
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003571 for (audio_io_handle_t output : outputs) {
3572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003573 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003574 continue;
3575 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003576 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3577 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003578 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003579 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003580 }
3581 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003582 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003583 }
3584 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003585 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003586 }
3587 }
3588 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3589 output = outputOffloaded;
3590 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3591 output = outputDeepBuffer;
3592 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3593 output = outputPrimary;
3594 } else {
3595 output = outputs[0];
3596 }
3597 activeOnly = false;
3598 }
3599
3600 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003601 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3602 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003603 mMusicEffectOutput = output;
3604 }
3605
3606 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003607 return output;
3608}
3609
Eric Laurent36829f92017-04-07 19:04:42 -07003610audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3611{
3612 return selectOutputForMusicEffects();
3613}
3614
Eric Laurente0720872014-03-11 09:30:41 -07003615status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003616 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003617 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003618 int session,
3619 int id)
3620{
Shunkai Yao29d10572024-03-19 04:31:47 +00003621 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003622 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003623 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003624 index = mInputs.indexOfKey(io);
3625 if (index < 0) {
3626 ALOGW("registerEffect() unknown io %d", io);
3627 return INVALID_OPERATION;
3628 }
Eric Laurente552edb2014-03-10 17:42:56 -07003629 }
3630 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003631 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3632 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3633 || strategy == PRODUCT_STRATEGY_NONE));
3634 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003635}
3636
Eric Laurentc241b0d2018-11-28 09:08:49 -08003637status_t AudioPolicyManager::unregisterEffect(int id)
3638{
3639 if (mEffects.getEffect(id) == nullptr) {
3640 return INVALID_OPERATION;
3641 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003642 if (mEffects.isEffectEnabled(id)) {
3643 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3644 setEffectEnabled(id, false);
3645 }
3646 return mEffects.unregisterEffect(id);
3647}
3648
3649status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3650{
3651 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3652 if (effect == nullptr) {
3653 return INVALID_OPERATION;
3654 }
3655
3656 status_t status = mEffects.setEffectEnabled(id, enabled);
3657 if (status == NO_ERROR) {
3658 mInputs.trackEffectEnabled(effect, enabled);
3659 }
3660 return status;
3661}
3662
Eric Laurent6c796322019-04-09 14:13:17 -07003663
3664status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3665{
3666 mEffects.moveEffects(ids, io);
3667 return NO_ERROR;
3668}
3669
Eric Laurentc75307b2015-03-17 15:29:32 -07003670bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3671{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003672 auto vs = toVolumeSource(stream, false);
3673 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003674}
3675
3676bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3677{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003678 auto vs = toVolumeSource(stream, false);
3679 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003680}
3681
Eric Laurente0720872014-03-11 09:30:41 -07003682bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003683{
3684 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003685 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003686 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003687 return true;
3688 }
3689 }
3690 return false;
3691}
3692
Eric Laurent275e8e92014-11-30 15:14:47 -08003693// Register a list of custom mixes with their attributes and format.
3694// When a mix is registered, corresponding input and output profiles are
3695// added to the remote submix hw module. The profile contains only the
3696// parameters (sampling rate, format...) specified by the mix.
3697// The corresponding input remote submix device is also connected.
3698//
3699// When a remote submix device is connected, the address is checked to select the
3700// appropriate profile and the corresponding input or output stream is opened.
3701//
3702// When capture starts, getInputForAttr() will:
3703// - 1 look for a mix matching the address passed in attribtutes tags if any
3704// - 2 if none found, getDeviceForInputSource() will:
3705// - 2.1 look for a mix matching the attributes source
3706// - 2.2 if none found, default to device selection by policy rules
3707// At this time, the corresponding output remote submix device is also connected
3708// and active playback use cases can be transferred to this mix if needed when reconnecting
3709// after AudioTracks are invalidated
3710//
3711// When playback starts, getOutputForAttr() will:
3712// - 1 look for a mix matching the address passed in attribtutes tags if any
3713// - 2 if none found, look for a mix matching the attributes usage
3714// - 3 if none found, default to device and output selection by policy rules.
3715
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003716status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003717{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003718 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3719 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003720 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003721 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003722 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 // examine each mix's route type
3724 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003725 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003726 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3727 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3728 ALOGE("Unsupported Policy Mix %zu of %zu: "
3729 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3730 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003731 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003732 break;
3733 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003734 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3735 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003736 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003737 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3738 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003740 rSubmixModule = mHwModules.getModuleFromName(
3741 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3742 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003743 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003744 i);
3745 res = INVALID_OPERATION;
3746 break;
3747 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003748 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003749
Eric Laurent97ac8712018-07-27 18:59:02 -07003750 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003751 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003752 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003753 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003754 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3755 } else {
3756 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3757 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003758 }
François Gaffie036e1e92015-03-19 10:16:24 +01003759
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003760 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003761 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762 res = INVALID_OPERATION;
3763 break;
3764 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003765 audio_config_t outputConfig = mix.mFormat;
3766 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003767 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3768 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003769 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3770 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003771 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003772 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3773 audio_is_linear_pcm(outputConfig.format)
3774 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003775 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003776 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3777 audio_is_linear_pcm(inputConfig.format)
3778 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003779
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003780 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003781 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003782 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003783 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003784 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003785 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003786 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003787 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3788 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003789 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003790 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003791 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003792
3793 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3794 mix.mDeviceType, mix.mDeviceAddress,
3795 String8(), AUDIO_FORMAT_DEFAULT);
3796 if (device == nullptr) {
3797 res = INVALID_OPERATION;
3798 break;
3799 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003801 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003802 // First try to find an already opened output supporting the device
3803 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003804 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003805
Eric Laurentc529cf62020-04-17 18:19:10 -07003806 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003807 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003808 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003809 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003810 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003811 } else {
3812 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003813 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003814 }
3815 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003816 // If no output found, try to find a direct output profile supporting the device
3817 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3818 sp<HwModule> module = mHwModules[i];
3819 for (size_t j = 0;
3820 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3821 j++) {
3822 sp<IOProfile> profile = module->getOutputProfiles()[j];
3823 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3824 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3825 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003826 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003827 res = INVALID_OPERATION;
3828 } else {
3829 foundOutput = true;
3830 }
3831 }
3832 }
3833 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003834 if (res != NO_ERROR) {
3835 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003836 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003837 res = INVALID_OPERATION;
3838 break;
3839 } else if (!foundOutput) {
3840 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003841 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003842 res = INVALID_OPERATION;
3843 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003844 } else {
3845 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003846 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003847 }
Eric Laurentc722f302014-12-10 11:21:49 -08003848 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003849 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003850 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003851 if (audio_flags::audio_mix_ownership()) {
3852 // Only unregister mixes that were actually registered to not accidentally unregister
3853 // mixes that already existed previously.
3854 unregisterPolicyMixes(registeredMixes);
3855 registeredMixes.clear();
3856 } else {
3857 unregisterPolicyMixes(mixes);
3858 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003859 } else if (checkOutputs) {
3860 checkForDeviceAndOutputChanges();
3861 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 }
3863 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003864}
3865
3866status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3867{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003868 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003869 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003870 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003871 sp<HwModule> rSubmixModule;
3872 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003873 for (const auto& mix : mixes) {
3874 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003875
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003876 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003877 rSubmixModule = mHwModules.getModuleFromName(
3878 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3879 if (rSubmixModule == 0) {
3880 res = INVALID_OPERATION;
3881 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003882 }
3883 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003884
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003885 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003886
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003887 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003888 res = INVALID_OPERATION;
3889 continue;
3890 }
3891
Marvin Ramin0783e202024-03-05 12:45:50 +01003892 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003893 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01003894 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3895 status_t currentRes =
3896 setDeviceConnectionStateInt(device,
3897 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3898 address.c_str(),
3899 "remote-submix",
3900 AUDIO_FORMAT_DEFAULT);
3901 if (!audio_flags::audio_mix_ownership()) {
3902 res = currentRes;
3903 }
3904 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003905 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003906 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01003907 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003908 }
3909 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003910 }
jiabin5740f082019-08-19 15:08:30 -07003911 rSubmixModule->removeOutputProfile(address.c_str());
3912 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003913
Kevin Rocard153f92d2018-12-18 18:33:28 -08003914 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003915 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003916 res = INVALID_OPERATION;
3917 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003918 } else {
3919 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003920 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003921 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003922 }
Marvin Ramin0783e202024-03-05 12:45:50 +01003923
3924 if (res == NO_ERROR && checkOutputs) {
3925 checkForDeviceAndOutputChanges();
3926 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07003927 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003928 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003929}
3930
Marvin Raminbdefaf02023-11-01 09:10:32 +01003931status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3932 if (!audio_flags::audio_mix_test_api()) {
3933 return INVALID_OPERATION;
3934 }
3935
3936 _aidl_return.clear();
3937 _aidl_return.reserve(mPolicyMixes.size());
3938 for (const auto &policyMix: mPolicyMixes) {
3939 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3940 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3941 policyMix->mCbFlags);
3942 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003943 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003944 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003945 }
3946
Vlad Popaa5d73f32024-03-08 16:05:38 -08003947 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01003948 return OK;
3949}
3950
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003951status_t AudioPolicyManager::updatePolicyMix(
3952 const AudioMix& mix,
3953 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3954 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3955 if (res == NO_ERROR) {
3956 checkForDeviceAndOutputChanges();
3957 updateCallAndOutputRouting();
3958 }
3959 return res;
3960}
3961
Mikhail Naganov100f0122018-11-29 11:22:16 -08003962void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3963{
3964 size_t i = 0;
3965 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3966 for (const auto& fmt : mManualSurroundFormats) {
3967 if (i++ != 0) dst->append(", ");
3968 std::string sfmt;
3969 FormatConverter::toString(fmt, sfmt);
3970 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3971 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3972 }
3973}
3974
Eric Laurentc529cf62020-04-17 18:19:10 -07003975// Returns true if all devices types match the predicate and are supported by one HW module
3976bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003977 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003978 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003979 const char *context,
3980 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003981 for (size_t i = 0; i < devices.size(); i++) {
3982 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003983 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003984 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003985 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003986 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003987 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003988 return false;
3989 }
3990 }
3991 return true;
3992}
3993
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003994void AudioPolicyManager::changeOutputDevicesMuteState(
3995 const AudioDeviceTypeAddrVector& devices) {
3996 ALOGVV("%s() num devices %zu", __func__, devices.size());
3997
3998 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3999 getSoftwareOutputsForDevices(devices);
4000
4001 for (size_t i = 0; i < outputs.size(); i++) {
4002 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4003 DeviceVector prevDevices = outputDesc->devices();
4004 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4005 }
4006}
4007
4008std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4009 const AudioDeviceTypeAddrVector& devices) const
4010{
4011 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4012 DeviceVector deviceDescriptors;
4013 for (size_t j = 0; j < devices.size(); j++) {
4014 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4015 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4016 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4017 ALOGE("%s: device type %#x address %s not supported or not an output device",
4018 __func__, devices[j].mType, devices[j].getAddress());
4019 continue;
4020 }
4021 deviceDescriptors.add(desc);
4022 }
4023 for (size_t i = 0; i < mOutputs.size(); i++) {
4024 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4025 continue;
4026 }
4027 outputs.push_back(mOutputs.valueAt(i));
4028 }
4029 return outputs;
4030}
4031
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004032status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004033 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004034 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004035 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4036 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004037 }
4038 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004039 if (res != NO_ERROR) {
4040 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4041 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004042 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004043
4044 checkForDeviceAndOutputChanges();
4045 updateCallAndOutputRouting();
4046
4047 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004048}
4049
4050status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4051 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004052 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4053 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004054 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004055 __FUNCTION__, uid);
4056 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004057 }
4058
Eric Laurentc529cf62020-04-17 18:19:10 -07004059 checkForDeviceAndOutputChanges();
4060 updateCallAndOutputRouting();
4061
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004062 return res;
4063}
4064
Eric Laurent2517af32020-11-25 15:31:27 +01004065
jiabin0a488932020-08-07 17:32:40 -07004066status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4067 device_role_t role,
4068 const AudioDeviceTypeAddrVector &devices) {
4069 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4070 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004071
Eric Laurentc529cf62020-04-17 18:19:10 -07004072 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004073 return BAD_VALUE;
4074 }
jiabin0a488932020-08-07 17:32:40 -07004075 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004076 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004077 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4078 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004079 return status;
4080 }
4081
4082 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004083
4084 bool forceVolumeReeval = false;
4085 // FIXME: workaround for truncated touch sounds
4086 // to be removed when the problem is handled by system UI
4087 uint32_t delayMs = 0;
4088 if (strategy == mCommunnicationStrategy) {
4089 forceVolumeReeval = true;
4090 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4091 updateInputRouting();
4092 }
4093 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004094
4095 return NO_ERROR;
4096}
4097
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004098void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4099 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004100{
4101 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004102 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004103 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004104 // Only apply special touch sound delay once
4105 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004106 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004107 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004108 for (size_t i = 0; i < mOutputs.size(); i++) {
4109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4110 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004111 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4112 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004113 // As done in setDeviceConnectionState, we could also fix default device issue by
4114 // preventing the force re-routing in case of default dev that distinguishes on address.
4115 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004116 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004117 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4118 // If the device is using preferred mixer attributes, the output need to reopen
4119 // with default configuration when the new selected devices are different from
4120 // current routing devices.
4121 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4122 continue;
4123 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304124
4125 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4126 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004127 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004128 // Only apply special touch sound delay once
4129 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004130 }
4131 if (forceVolumeReeval && !newDevices.isEmpty()) {
4132 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4133 }
4134 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004135 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004136 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004137}
4138
Eric Laurent2517af32020-11-25 15:31:27 +01004139void AudioPolicyManager::updateInputRouting() {
4140 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304141 // Skip for hotword recording as the input device switch
4142 // is handled within sound trigger HAL
4143 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4144 continue;
4145 }
Eric Laurent2517af32020-11-25 15:31:27 +01004146 auto newDevice = getNewInputDevice(activeDesc);
4147 // Force new input selection if the new device can not be reached via current input
4148 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4149 setInputDevice(activeDesc->mIoHandle, newDevice);
4150 } else {
4151 closeInput(activeDesc->mIoHandle);
4152 }
4153 }
4154}
4155
Paul Wang5d7cdb52022-11-22 09:45:06 +00004156status_t
4157AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4158 device_role_t role,
4159 const AudioDeviceTypeAddrVector &devices) {
4160 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4161 dumpAudioDeviceTypeAddrVector(devices).c_str());
4162
Eric Laurent78fedbf2023-03-09 14:40:44 +01004163 if (!areAllDevicesSupported(
4164 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004165 return BAD_VALUE;
4166 }
4167 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4168 if (status != NO_ERROR) {
4169 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4170 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4171 return status;
4172 }
4173
4174 checkForDeviceAndOutputChanges();
4175
4176 bool forceVolumeReeval = false;
4177 // TODO(b/263479999): workaround for truncated touch sounds
4178 // to be removed when the problem is handled by system UI
4179 uint32_t delayMs = 0;
4180 if (strategy == mCommunnicationStrategy) {
4181 forceVolumeReeval = true;
4182 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4183 updateInputRouting();
4184 }
4185 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4186
4187 return NO_ERROR;
4188}
4189
4190status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4191 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004192{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004193 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004194
Paul Wang5d7cdb52022-11-22 09:45:06 +00004195 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004196 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004197 ALOGW_IF(status != NAME_NOT_FOUND,
4198 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004199 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004200 return status;
4201 }
4202
4203 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004204
4205 bool forceVolumeReeval = false;
4206 // FIXME: workaround for truncated touch sounds
4207 // to be removed when the problem is handled by system UI
4208 uint32_t delayMs = 0;
4209 if (strategy == mCommunnicationStrategy) {
4210 forceVolumeReeval = true;
4211 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4212 updateInputRouting();
4213 }
4214 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004215
4216 return NO_ERROR;
4217}
4218
jiabin0a488932020-08-07 17:32:40 -07004219status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4220 device_role_t role,
4221 AudioDeviceTypeAddrVector &devices) {
4222 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004223}
4224
Jiabin Huang3b98d322020-09-03 17:54:16 +00004225status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4226 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4227 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4228 dumpAudioDeviceTypeAddrVector(devices).c_str());
4229
Mikhail Naganov55773032020-10-01 15:08:13 -07004230 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004231 return BAD_VALUE;
4232 }
4233 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4234 ALOGW_IF(status != NO_ERROR,
4235 "Engine could not set preferred devices %s for audio source %d role %d",
4236 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4237
4238 return status;
4239}
4240
4241status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4242 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4243 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4244 dumpAudioDeviceTypeAddrVector(devices).c_str());
4245
Mikhail Naganov55773032020-10-01 15:08:13 -07004246 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004247 return BAD_VALUE;
4248 }
4249 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4250 ALOGW_IF(status != NO_ERROR,
4251 "Engine could not add preferred devices %s for audio source %d role %d",
4252 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4253
Eric Laurent2517af32020-11-25 15:31:27 +01004254 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004255 return status;
4256}
4257
4258status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4259 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4260{
4261 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4262 dumpAudioDeviceTypeAddrVector(devices).c_str());
4263
Eric Laurent78fedbf2023-03-09 14:40:44 +01004264 if (!areAllDevicesSupported(
4265 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004266 return BAD_VALUE;
4267 }
4268
4269 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4270 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004271 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004272 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004273 if (status == NO_ERROR) {
4274 updateInputRouting();
4275 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004276 return status;
4277}
4278
4279status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4280 device_role_t role) {
4281 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4282
4283 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004284 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004285 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004286 if (status == NO_ERROR) {
4287 updateInputRouting();
4288 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004289 return status;
4290}
4291
4292status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4293 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4294 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4295}
4296
Oscar Azucena90e77632019-11-27 17:12:28 -08004297status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004298 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004299 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004300 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4301 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004302 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004303 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4304 if (status != NO_ERROR) {
4305 ALOGE("%s() could not set device affinity for userId %d",
4306 __FUNCTION__, userId);
4307 return status;
4308 }
4309
4310 // reevaluate outputs for all devices
4311 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004312 changeOutputDevicesMuteState(devices);
4313 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4314 true /* skipDelays */);
4315 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004316
4317 return NO_ERROR;
4318}
4319
4320status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004321 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004322 AudioDeviceTypeAddrVector devices;
4323 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004324 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4325 if (status != NO_ERROR) {
4326 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4327 __FUNCTION__, userId);
4328 return status;
4329 }
4330
4331 // reevaluate outputs for all devices
4332 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004333 changeOutputDevicesMuteState(devices);
4334 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4335 true /* skipDelays */);
4336 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004337
4338 return NO_ERROR;
4339}
4340
Andy Hungc29d82b2018-10-05 12:23:17 -07004341void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004342{
Andy Hungc29d82b2018-10-05 12:23:17 -07004343 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004344 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004345 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004346 std::string stateLiteral;
4347 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004348 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004349 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4350 "communications", "media", "record", "dock", "system",
4351 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4352 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4353 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004354 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4355 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4356 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4357 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4358 dst->append(" (MANUAL: ");
4359 dumpManualSurroundFormats(dst);
4360 dst->append(")");
4361 }
4362 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004363 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004364 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4365 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004366 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004367 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004368
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004369 dst->append("\n");
4370 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4371 dst->append("\n");
4372 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004373 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004374 mOutputs.dump(dst);
4375 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004376 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004377 mAudioPatches.dump(dst);
4378 mPolicyMixes.dump(dst);
4379 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004380
Kevin Rocardb99cc752019-03-21 20:52:24 -07004381 dst->appendFormat(" AllowedCapturePolicies:\n");
4382 for (auto& policy : mAllowedCapturePolicies) {
4383 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4384 }
4385
jiabina84c3d32022-12-02 18:59:55 +00004386 dst->appendFormat(" Preferred mixer audio configuration:\n");
4387 for (const auto it : mPreferredMixerAttrInfos) {
4388 dst->appendFormat(" - device port id: %d\n", it.first);
4389 for (const auto preferredMixerInfoIt : it.second) {
4390 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4391 preferredMixerInfoIt.second->dump(dst);
4392 }
4393 }
4394
François Gaffiec005e562018-11-06 15:04:49 +01004395 dst->appendFormat("\nPolicy Engine dump:\n");
4396 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004397}
4398
4399status_t AudioPolicyManager::dump(int fd)
4400{
4401 String8 result;
4402 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004403 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004404 return NO_ERROR;
4405}
4406
Kevin Rocardb99cc752019-03-21 20:52:24 -07004407status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4408{
4409 mAllowedCapturePolicies[uid] = capturePolicy;
4410 return NO_ERROR;
4411}
4412
Eric Laurente552edb2014-03-10 17:42:56 -07004413// This function checks for the parameters which can be offloaded.
4414// This can be enhanced depending on the capability of the DSP and policy
4415// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004416audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004417{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004418 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004419 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004420 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004421 offloadInfo.format,
4422 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4423 offloadInfo.has_video);
4424
jiabin2b9d5a12021-12-10 01:06:29 +00004425 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004426 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004427 }
4428
4429 // See if there is a profile to support this.
4430 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004431 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004432 offloadInfo.sample_rate,
4433 offloadInfo.format,
4434 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004435 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4436 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004437 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4438 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4439 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004440 if (profile == nullptr) {
4441 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4442 }
4443 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4444 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4445 }
4446 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004447}
4448
Michael Chana94fbb22018-04-24 14:31:19 +10004449bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4450 const audio_attributes_t& attributes) {
4451 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004452 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004453 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4454 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004455 config.sample_rate,
4456 config.format,
4457 config.channel_mask,
4458 output_flags,
4459 true /* directOnly */);
4460 ALOGV("%s() profile %sfound with name: %s, "
4461 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4462 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004463 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004464 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004465
4466 // also try the MSD module if compatible profile not found
4467 if (profile == nullptr) {
4468 profile = getMsdProfileForOutput(outputDevices,
4469 config.sample_rate,
4470 config.format,
4471 config.channel_mask,
4472 output_flags,
4473 true /* directOnly */);
4474 ALOGV("%s() MSD profile %sfound with name: %s, "
4475 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4476 __FUNCTION__, profile != 0 ? "" : "NOT ",
4477 (profile != 0 ? profile->getTagName().c_str() : "null"),
4478 config.sample_rate, config.format, config.channel_mask, output_flags);
4479 }
4480 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004481}
4482
jiabin2b9d5a12021-12-10 01:06:29 +00004483bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4484 bool durationIgnored) {
4485 if (mMasterMono) {
4486 return false; // no offloading if mono is set.
4487 }
4488
4489 // Check if offload has been disabled
4490 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4491 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4492 return false;
4493 }
4494
4495 // Check if stream type is music, then only allow offload as of now.
4496 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4497 {
4498 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4499 return false;
4500 }
4501
4502 //TODO: enable audio offloading with video when ready
4503 const bool allowOffloadWithVideo =
4504 property_get_bool("audio.offload.video", false /* default_value */);
4505 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4506 ALOGV("%s: has_video == true, returning false", __func__);
4507 return false;
4508 }
4509
4510 //If duration is less than minimum value defined in property, return false
4511 const int min_duration_secs = property_get_int32(
4512 "audio.offload.min.duration.secs", -1 /* default_value */);
4513 if (!durationIgnored) {
4514 if (min_duration_secs >= 0) {
4515 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4516 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4517 __func__, min_duration_secs);
4518 return false;
4519 }
4520 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4521 ALOGV("%s: Offload denied by duration < default min(=%u)",
4522 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4523 return false;
4524 }
4525 }
4526
4527 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4528 // creating an offloaded track and tearing it down immediately after start when audioflinger
4529 // detects there is an active non offloadable effect.
4530 // FIXME: We should check the audio session here but we do not have it in this context.
4531 // This may prevent offloading in rare situations where effects are left active by apps
4532 // in the background.
4533 if (mEffects.isNonOffloadableEffectEnabled()) {
4534 return false;
4535 }
4536
4537 return true;
4538}
4539
4540audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4541 const audio_config_t *config) {
4542 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4543 offloadInfo.format = config->format;
4544 offloadInfo.sample_rate = config->sample_rate;
4545 offloadInfo.channel_mask = config->channel_mask;
4546 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4547 offloadInfo.has_video = false;
4548 offloadInfo.is_streaming = false;
4549 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4550
4551 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4552 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4553 audio_flags_to_audio_output_flags(attr->flags, &flags);
4554 // only retain flags that will drive compressed offload or passthrough
4555 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4556 if (offloadPossible) {
4557 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4558 }
4559 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4560
Dorin Drimusfae3c642022-03-17 18:36:30 +01004561 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004562 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004563 DeviceVector outputDevices = engineOutputDevices;
4564 // the MSD module checks for different conditions and output devices
4565 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4566 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4567 continue;
4568 }
4569 outputDevices = getMsdAudioOutDevices();
4570 }
jiabin2b9d5a12021-12-10 01:06:29 +00004571 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004572 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004573 config->sample_rate, nullptr /*updatedSamplingRate*/,
4574 config->format, nullptr /*updatedFormat*/,
4575 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004576 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004577 continue;
4578 }
4579 // reject profiles not corresponding to a device currently available
4580 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4581 continue;
4582 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004583 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4584 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004585 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004586 != AUDIO_DIRECT_NOT_SUPPORTED) {
4587 // Already reports offload gapless supported. No need to report offload support.
4588 continue;
4589 }
4590 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4591 != AUDIO_OUTPUT_FLAG_NONE) {
4592 // If offload gapless is reported, no need to report offload support.
4593 directMode = (audio_direct_mode_t) ((directMode &
4594 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4595 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4596 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004597 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004598 }
4599 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004600 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004601 }
4602 }
4603 }
4604 return directMode;
4605}
4606
Dorin Drimusf2196d82022-01-03 12:11:18 +01004607status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4608 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004609 if (mEffects.isNonOffloadableEffectEnabled()) {
4610 return OK;
4611 }
jiabinf1c73972022-04-14 16:28:52 -07004612 DeviceVector devices;
4613 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004614 if (status != OK) {
4615 return status;
4616 }
4617 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4618 if (devices.empty()) {
4619 return OK; // no output devices for the attributes
4620 }
jiabinf1c73972022-04-14 16:28:52 -07004621 return getProfilesForDevices(devices, audioProfilesVector,
4622 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004623}
4624
jiabina84c3d32022-12-02 18:59:55 +00004625status_t AudioPolicyManager::getSupportedMixerAttributes(
4626 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4627 ALOGV("%s, portId=%d", __func__, portId);
4628 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4629 if (deviceDescriptor == nullptr) {
4630 ALOGE("%s the requested device is currently unavailable", __func__);
4631 return BAD_VALUE;
4632 }
jiabin96daffc2023-05-11 17:51:55 +00004633 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4634 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4635 deviceDescriptor->type());
4636 return BAD_VALUE;
4637 }
jiabina84c3d32022-12-02 18:59:55 +00004638 for (const auto& hwModule : mHwModules) {
4639 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4640 if (curProfile->supportsDevice(deviceDescriptor)) {
4641 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4642 }
4643 }
4644 }
4645 return NO_ERROR;
4646}
4647
4648status_t AudioPolicyManager::setPreferredMixerAttributes(
4649 const audio_attributes_t *attr,
4650 audio_port_handle_t portId,
4651 uid_t uid,
4652 const audio_mixer_attributes_t *mixerAttributes) {
4653 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4654 "mixerBehavior=%d}, uid=%d, portId=%u",
4655 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4656 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4657 mixerAttributes->mixer_behavior, uid, portId);
4658 if (attr->usage != AUDIO_USAGE_MEDIA) {
4659 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4660 return BAD_VALUE;
4661 }
4662 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4663 if (deviceDescriptor == nullptr) {
4664 ALOGE("%s the requested device is currently unavailable", __func__);
4665 return BAD_VALUE;
4666 }
4667 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4668 ALOGE("%s(%d), type=%d, is not a usb output device",
4669 __func__, portId, deviceDescriptor->type());
4670 return BAD_VALUE;
4671 }
4672
4673 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4674 audio_flags_to_audio_output_flags(attr->flags, &flags);
4675 flags = (audio_output_flags_t) (flags |
4676 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4677 sp<IOProfile> profile = nullptr;
4678 DeviceVector devices(deviceDescriptor);
4679 for (const auto& hwModule : mHwModules) {
4680 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4681 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004682 && curProfile->getCompatibilityScore(
4683 devices,
4684 mixerAttributes->config.sample_rate,
4685 nullptr /*updatedSamplingRate*/,
4686 mixerAttributes->config.format,
4687 nullptr /*updatedFormat*/,
4688 mixerAttributes->config.channel_mask,
4689 nullptr /*updatedChannelMask*/,
4690 flags,
4691 false /*exactMatchRequiredForInputFlags*/)
4692 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004693 profile = curProfile;
4694 break;
4695 }
4696 }
4697 }
4698 if (profile == nullptr) {
4699 ALOGE("%s, there is no compatible profile found", __func__);
4700 return BAD_VALUE;
4701 }
4702
4703 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4704 sp<PreferredMixerAttributesInfo>::make(
4705 uid, portId, profile, flags, *mixerAttributes);
4706 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4707 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4708
4709 // If 1) there is any client from the preferred mixer configuration owner that is currently
4710 // active and matches the strategy and 2) current output is on the preferred device and the
4711 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4712 // configuration.
4713 std::vector<audio_io_handle_t> outputsToReopen;
4714 for (size_t i = 0; i < mOutputs.size(); i++) {
4715 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004716 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4717 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4718 output->mUsePreferredMixerAttributes = true;
4719 } else {
4720 for (const auto &client: output->getActiveClients()) {
4721 if (client->uid() == uid && client->strategy() == strategy) {
4722 client->setIsInvalid();
4723 outputsToReopen.push_back(output->mIoHandle);
4724 }
jiabina84c3d32022-12-02 18:59:55 +00004725 }
4726 }
4727 }
4728 }
4729 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4730 config.sample_rate = mixerAttributes->config.sample_rate;
4731 config.channel_mask = mixerAttributes->config.channel_mask;
4732 config.format = mixerAttributes->config.format;
4733 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004734 sp<SwAudioOutputDescriptor> desc =
4735 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4736 if (desc == nullptr) {
4737 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4738 continue;
4739 }
4740 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004741 }
4742
4743 return NO_ERROR;
4744}
4745
4746sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004747 audio_port_handle_t devicePortId,
4748 product_strategy_t strategy,
4749 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004750 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4751 if (it == mPreferredMixerAttrInfos.end()) {
4752 return nullptr;
4753 }
jiabind9a58d32023-06-01 17:57:30 +00004754 if (activeBitPerfectPreferred) {
4755 for (auto [strategy, info] : it->second) {
4756 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4757 && info->getActiveClientCount() != 0) {
4758 return info;
4759 }
4760 }
jiabina84c3d32022-12-02 18:59:55 +00004761 }
jiabind9a58d32023-06-01 17:57:30 +00004762 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4763 return strategyMatchedMixerAttrInfoIt == it->second.end()
4764 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004765}
4766
4767status_t AudioPolicyManager::getPreferredMixerAttributes(
4768 const audio_attributes_t *attr,
4769 audio_port_handle_t portId,
4770 audio_mixer_attributes_t* mixerAttributes) {
4771 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4772 portId, mEngine->getProductStrategyForAttributes(*attr));
4773 if (info == nullptr) {
4774 return NAME_NOT_FOUND;
4775 }
4776 *mixerAttributes = info->getMixerAttributes();
4777 return NO_ERROR;
4778}
4779
4780status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4781 audio_port_handle_t portId,
4782 uid_t uid) {
4783 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4784 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4785 if (preferredMixerAttrInfo == nullptr) {
4786 return NAME_NOT_FOUND;
4787 }
4788 if (preferredMixerAttrInfo->getUid() != uid) {
4789 ALOGE("%s, requested uid=%d, owned uid=%d",
4790 __func__, uid, preferredMixerAttrInfo->getUid());
4791 return PERMISSION_DENIED;
4792 }
4793 mPreferredMixerAttrInfos[portId].erase(strategy);
4794 if (mPreferredMixerAttrInfos[portId].empty()) {
4795 mPreferredMixerAttrInfos.erase(portId);
4796 }
4797
4798 // Reconfig existing output
4799 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4800 for (size_t i = 0; i < mOutputs.size(); i++) {
4801 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4802 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4803 }
4804 }
4805 for (const auto output : potentialOutputsToReopen) {
4806 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4807 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4808 preferredMixerAttrInfo->getFlags())) {
4809 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4810 }
4811 }
4812 return NO_ERROR;
4813}
4814
Eric Laurent6a94d692014-05-20 11:18:06 -07004815status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4816 audio_port_type_t type,
4817 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004818 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 unsigned int *generation)
4820{
jiabin19cdba52020-11-24 11:28:58 -08004821 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4822 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004823 return BAD_VALUE;
4824 }
4825 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004826 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 *num_ports = 0;
4828 }
4829
4830 size_t portsWritten = 0;
4831 size_t portsMax = *num_ports;
4832 *num_ports = 0;
4833 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004834 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4835 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004837 for (const auto& dev : mAvailableOutputDevices) {
4838 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004839 continue;
4840 }
4841 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004842 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004843 }
4844 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004846 }
4847 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004848 for (const auto& dev : mAvailableInputDevices) {
4849 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004850 continue;
4851 }
4852 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004853 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004854 }
4855 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 }
4858 }
4859 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4860 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4861 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4862 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4863 }
4864 *num_ports += mInputs.size();
4865 }
4866 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004867 size_t numOutputs = 0;
4868 for (size_t i = 0; i < mOutputs.size(); i++) {
4869 if (!mOutputs[i]->isDuplicated()) {
4870 numOutputs++;
4871 if (portsWritten < portsMax) {
4872 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4873 }
4874 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 }
Eric Laurent84c70242014-06-23 08:46:27 -07004876 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 }
4878 }
jiabina84c3d32022-12-02 18:59:55 +00004879
Eric Laurent6a94d692014-05-20 11:18:06 -07004880 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004881 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004882 return NO_ERROR;
4883}
4884
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004885status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4886 std::vector<media::AudioPortFw>* _aidl_return) {
4887 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4888 audio_port_v7 port;
4889 dev->toAudioPort(&port);
4890 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4891 _aidl_return->push_back(std::move(aidlPort));
4892 return OK;
4893 };
4894
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004895 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004896 for (const auto& dev : module->getDeclaredDevices()) {
4897 if (role == media::AudioPortRole::NONE ||
4898 ((role == media::AudioPortRole::SOURCE)
4899 == audio_is_input_device(dev->type()))) {
4900 RETURN_STATUS_IF_ERROR(pushPort(dev));
4901 }
4902 }
4903 }
4904 return OK;
4905}
4906
jiabin19cdba52020-11-24 11:28:58 -08004907status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004908{
Eric Laurent99fcae42018-05-17 16:59:18 -07004909 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4910 return BAD_VALUE;
4911 }
4912 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4913 if (dev != 0) {
4914 dev->toAudioPort(port);
4915 return NO_ERROR;
4916 }
4917 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4918 if (dev != 0) {
4919 dev->toAudioPort(port);
4920 return NO_ERROR;
4921 }
4922 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4923 if (out != 0) {
4924 out->toAudioPort(port);
4925 return NO_ERROR;
4926 }
4927 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4928 if (in != 0) {
4929 in->toAudioPort(port);
4930 return NO_ERROR;
4931 }
4932 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004933}
4934
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004935status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4936 audio_patch_handle_t *handle,
4937 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004938{
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 if (handle == NULL || patch == NULL) {
4941 return BAD_VALUE;
4942 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004943 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004944 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004945 return BAD_VALUE;
4946 }
4947 // only one source per audio patch supported for now
4948 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 return INVALID_OPERATION;
4950 }
Eric Laurent874c42872014-08-08 15:13:39 -07004951 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004952 return INVALID_OPERATION;
4953 }
Eric Laurent874c42872014-08-08 15:13:39 -07004954 for (size_t i = 0; i < patch->num_sinks; i++) {
4955 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4956 return INVALID_OPERATION;
4957 }
4958 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004959
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004960 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4961 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4962 if (srcDevice == nullptr || sinkDevice == nullptr) {
4963 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4964 return BAD_VALUE;
4965 }
4966 ALOGV("%s between source %s and sink %s", __func__,
4967 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4968 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4969 // Default attributes, default volume priority, not to infer with non raw audio patches.
4970 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4971 const struct audio_port_config *source = &patch->sources[0];
4972 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004973 new SourceClientDescriptor(
4974 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4975 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4976 true);
4977 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004978
4979 status_t status =
4980 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4981
4982 if (status != NO_ERROR) {
4983 return INVALID_OPERATION;
4984 }
4985 mAudioSources.add(portId, sourceDesc);
4986 return NO_ERROR;
4987}
4988
4989status_t AudioPolicyManager::connectAudioSourceToSink(
4990 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4991 const struct audio_patch *patch,
4992 audio_patch_handle_t &handle,
4993 uid_t uid, uint32_t delayMs)
4994{
4995 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4996 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4997 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4998 return INVALID_OPERATION;
4999 }
5000 sourceDesc->connect(handle, sinkDevice);
5001 if (isMsdPatch(handle)) {
5002 return NO_ERROR;
5003 }
5004 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5005 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5006 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5007 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5008 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5009 goto FailurePatchAdded;
5010 }
5011 status = swOutput->start();
5012 if (status != NO_ERROR) {
5013 goto FailureSourceAdded;
5014 }
5015 swOutput->addClient(sourceDesc);
5016 status = startSource(swOutput, sourceDesc, &delayMs);
5017 if (status != NO_ERROR) {
5018 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5019 goto FailureSourceActive;
5020 }
5021 if (delayMs != 0) {
5022 usleep(delayMs * 1000);
5023 }
5024 return NO_ERROR;
5025
5026FailureSourceActive:
5027 swOutput->stop();
5028 releaseOutput(sourceDesc->portId());
5029FailureSourceAdded:
5030 sourceDesc->setSwOutput(nullptr);
5031FailurePatchAdded:
5032 releaseAudioPatchInternal(handle);
5033 return INVALID_OPERATION;
5034}
5035
5036status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5037 audio_patch_handle_t *handle,
5038 uid_t uid, uint32_t delayMs,
5039 const sp<SourceClientDescriptor>& sourceDesc)
5040{
5041 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 sp<AudioPatch> patchDesc;
5043 ssize_t index = mAudioPatches.indexOfKey(*handle);
5044
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5046 patch->sources[0].role,
5047 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005048#if LOG_NDEBUG == 0
5049 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005050 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5051 patch->sinks[i].role,
5052 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005053 }
5054#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005055
5056 if (index >= 0) {
5057 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005058 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5059 __func__, mUidCached, patchDesc->getUid(), uid);
5060 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005061 return INVALID_OPERATION;
5062 }
5063 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005064 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 }
5066
5067 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005068 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005070 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005071 return BAD_VALUE;
5072 }
Eric Laurent84c70242014-06-23 08:46:27 -07005073 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5074 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 if (patchDesc != 0) {
5076 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005077 ALOGV("%s source id differs for patch current id %d new id %d",
5078 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 return BAD_VALUE;
5080 }
5081 }
Eric Laurent874c42872014-08-08 15:13:39 -07005082 DeviceVector devices;
5083 for (size_t i = 0; i < patch->num_sinks; i++) {
5084 // Only support mix to devices connection
5085 // TODO add support for mix to mix connection
5086 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005087 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005088 return INVALID_OPERATION;
5089 }
5090 sp<DeviceDescriptor> devDesc =
5091 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5092 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005093 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005094 return BAD_VALUE;
5095 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005096
jiabin66acc432024-02-06 00:57:36 +00005097 if (outputDesc->mProfile->getCompatibilityScore(
5098 DeviceVector(devDesc),
5099 patch->sources[0].sample_rate,
5100 nullptr, // updatedSamplingRate
5101 patch->sources[0].format,
5102 nullptr, // updatedFormat
5103 patch->sources[0].channel_mask,
5104 nullptr, // updatedChannelMask
5105 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005106 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005107 return INVALID_OPERATION;
5108 }
5109 devices.add(devDesc);
5110 }
5111 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005112 return INVALID_OPERATION;
5113 }
Eric Laurent874c42872014-08-08 15:13:39 -07005114
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005116 ALOGV("%s setting device %s on output %d",
5117 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305118 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 index = mAudioPatches.indexOfKey(*handle);
5120 if (index >= 0) {
5121 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005122 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 }
5124 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005125 patchDesc->setUid(uid);
5126 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005128 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005129 return INVALID_OPERATION;
5130 }
5131 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5132 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5133 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005134 // only one sink supported when connecting an input device to a mix
5135 if (patch->num_sinks > 1) {
5136 return INVALID_OPERATION;
5137 }
François Gaffie53615e22015-03-19 09:24:12 +01005138 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005139 if (inputDesc == NULL) {
5140 return BAD_VALUE;
5141 }
5142 if (patchDesc != 0) {
5143 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5144 return BAD_VALUE;
5145 }
5146 }
François Gaffie11d30102018-11-02 16:09:09 +01005147 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005148 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005149 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005150 return BAD_VALUE;
5151 }
5152
jiabin66acc432024-02-06 00:57:36 +00005153 if (inputDesc->mProfile->getCompatibilityScore(
5154 DeviceVector(device),
5155 patch->sinks[0].sample_rate,
5156 nullptr, /*updatedSampleRate*/
5157 patch->sinks[0].format,
5158 nullptr, /*updatedFormat*/
5159 patch->sinks[0].channel_mask,
5160 nullptr, /*updatedChannelMask*/
5161 // FIXME for the parameter type,
5162 // and the NONE
5163 (audio_output_flags_t)
5164 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005165 return INVALID_OPERATION;
5166 }
5167 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005168 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005169 device->toString().c_str(), inputDesc->mIoHandle);
5170 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005171 index = mAudioPatches.indexOfKey(*handle);
5172 if (index >= 0) {
5173 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005174 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005175 }
5176 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005177 patchDesc->setUid(uid);
5178 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005179 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005180 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 return INVALID_OPERATION;
5182 }
5183 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5184 // device to device connection
5185 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005186 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005187 return BAD_VALUE;
5188 }
5189 }
François Gaffie11d30102018-11-02 16:09:09 +01005190 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005192 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005193 return BAD_VALUE;
5194 }
Eric Laurent874c42872014-08-08 15:13:39 -07005195
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 //update source and sink with our own data as the data passed in the patch may
5197 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005198 PatchBuilder patchBuilder;
5199 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005200
5201 // if first sink is to MSD, establish single MSD patch
5202 if (getMsdAudioOutDevices().contains(
5203 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5204 ALOGV("%s patching to MSD", __FUNCTION__);
5205 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5206 goto installPatch;
5207 }
5208
François Gaffieafd4cea2019-11-18 15:50:22 +01005209 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5210 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005211
Eric Laurent874c42872014-08-08 15:13:39 -07005212 for (size_t i = 0; i < patch->num_sinks; i++) {
5213 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005214 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005215 return INVALID_OPERATION;
5216 }
François Gaffie11d30102018-11-02 16:09:09 +01005217 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005218 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005219 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005220 return BAD_VALUE;
5221 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005222 audio_port_config sinkPortConfig = {};
5223 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5224 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005225
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005226 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5227 // volume management purpose (tracking activity)
5228 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5229 // in config XML to reach the sink so that is can be declared as available.
5230 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005231 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005232 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005233 // take care of dynamic routing for SwOutput selection,
5234 audio_attributes_t attributes = sourceDesc->attributes();
5235 audio_stream_type_t stream = sourceDesc->stream();
5236 audio_attributes_t resultAttr;
5237 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5238 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005239 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5240 config.channel_mask =
5241 (audio_channel_mask_get_representation(sourceMask)
5242 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5243 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005244 config.format = sourceDesc->config().format;
5245 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5246 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5247 bool isRequestedDeviceForExclusiveUse = false;
5248 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005249 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005250 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005251 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5252 &stream, sourceDesc->uid(), &config, &flags,
5253 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005254 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005255 if (output == AUDIO_IO_HANDLE_NONE) {
5256 ALOGV("%s no output for device %s",
5257 __FUNCTION__, sinkDevice->toString().c_str());
5258 return INVALID_OPERATION;
5259 }
5260 outputDesc = mOutputs.valueFor(output);
5261 if (outputDesc->isDuplicated()) {
5262 ALOGE("%s output is duplicated", __func__);
5263 return INVALID_OPERATION;
5264 }
François Gaffie7e39df22022-04-26 12:48:49 +02005265 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5266 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005267 } else {
5268 // Same for "raw patches" aka created from createAudioPatch API
5269 SortedVector<audio_io_handle_t> outputs =
5270 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5271 // if the sink device is reachable via an opened output stream, request to
5272 // go via this output stream by adding a second source to the patch
5273 // description
5274 output = selectOutput(outputs);
5275 if (output == AUDIO_IO_HANDLE_NONE) {
5276 ALOGE("%s no output available for internal patch sink", __func__);
5277 return INVALID_OPERATION;
5278 }
5279 outputDesc = mOutputs.valueFor(output);
5280 if (outputDesc->isDuplicated()) {
5281 ALOGV("%s output for device %s is duplicated",
5282 __func__, sinkDevice->toString().c_str());
5283 return INVALID_OPERATION;
5284 }
François Gaffie7e39df22022-04-26 12:48:49 +02005285 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005286 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005287 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005288 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005289 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005290 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005291 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5292 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005293 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5294 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005296 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005297 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005298 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005299 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005300 return INVALID_OPERATION;
5301 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005302 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005303 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005305 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005306 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005307 srcMixPortConfig.ext.mix.usecase.stream =
5308 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005309 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5310 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005311 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005312 }
Eric Laurent83b88082014-06-20 18:31:16 -07005313 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 }
5315 // TODO: check from routing capabilities in config file and other conflicting patches
5316
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005317installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005318 status_t status = installPatch(
5319 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005320 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005321 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 return INVALID_OPERATION;
5323 }
5324 } else {
5325 return BAD_VALUE;
5326 }
5327 } else {
5328 return BAD_VALUE;
5329 }
5330 return NO_ERROR;
5331}
5332
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005333status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005334{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005335 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005336 ssize_t index = mAudioPatches.indexOfKey(handle);
5337
5338 if (index < 0) {
5339 return BAD_VALUE;
5340 }
5341 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005342 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5343 __func__, mUidCached, patchDesc->getUid(), uid);
5344 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 return INVALID_OPERATION;
5346 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005347 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5348 for (size_t i = 0; i < mAudioSources.size(); i++) {
5349 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5350 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5351 portId = sourceDesc->portId();
5352 break;
5353 }
5354 }
5355 return portId != AUDIO_PORT_HANDLE_NONE ?
5356 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005357}
Eric Laurent6a94d692014-05-20 11:18:06 -07005358
François Gaffieafd4cea2019-11-18 15:50:22 +01005359status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005360 uint32_t delayMs,
5361 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005362{
5363 ALOGV("%s patch %d", __func__, handle);
5364 if (mAudioPatches.indexOfKey(handle) < 0) {
5365 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5366 return BAD_VALUE;
5367 }
5368 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005370 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005371 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005372 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005375 return BAD_VALUE;
5376 }
5377
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305378 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005379 getNewOutputDevices(outputDesc, true /*fromCache*/),
5380 true,
5381 0,
5382 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5384 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005385 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005386 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005387 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005388 return BAD_VALUE;
5389 }
5390 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005391 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005392 true,
5393 NULL);
5394 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005395 status_t status =
5396 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5397 ALOGV("%s patch panel returned %d patchHandle %d",
5398 __func__, status, patchDesc->getAfHandle());
5399 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005400 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005401 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005402 // SW or HW Bridge
5403 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5404 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005405 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005406 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5407 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5408 outputDesc = sourceDesc->swOutput().promote();
5409 }
5410 if (outputDesc == nullptr) {
5411 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5412 // releaseOutput has already called closeOutput in case of direct output
5413 return NO_ERROR;
5414 }
François Gaffie7e39df22022-04-26 12:48:49 +02005415 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005416 // While using a HwBridge, force reconsidering device only if not reusing an existing
5417 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005418 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005419 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5420 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5421 // Reconsider device only for cases:
5422 // 1 / Active Output
5423 // 2 / Inactive Output previously hosting HwBridge
5424 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5425 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5426 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305427 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005428 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5429 outputDesc->devices(),
5430 force,
5431 0,
5432 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005433 } else {
5434 return BAD_VALUE;
5435 }
5436 } else {
5437 return BAD_VALUE;
5438 }
5439 return NO_ERROR;
5440}
5441
5442status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5443 struct audio_patch *patches,
5444 unsigned int *generation)
5445{
François Gaffie53615e22015-03-19 09:24:12 +01005446 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005447 return BAD_VALUE;
5448 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005449 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005450 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005451}
5452
Eric Laurente1715a42014-05-20 11:30:42 -07005453status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005454{
Eric Laurente1715a42014-05-20 11:30:42 -07005455 ALOGV("setAudioPortConfig()");
5456
5457 if (config == NULL) {
5458 return BAD_VALUE;
5459 }
5460 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5461 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005462 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5463 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005464 }
5465
Eric Laurenta121f902014-06-03 13:32:54 -07005466 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005467 if (config->type == AUDIO_PORT_TYPE_MIX) {
5468 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005469 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005470 if (outputDesc == NULL) {
5471 return BAD_VALUE;
5472 }
Eric Laurent84c70242014-06-23 08:46:27 -07005473 ALOG_ASSERT(!outputDesc->isDuplicated(),
5474 "setAudioPortConfig() called on duplicated output %d",
5475 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005476 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005477 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005478 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005479 if (inputDesc == NULL) {
5480 return BAD_VALUE;
5481 }
Eric Laurenta121f902014-06-03 13:32:54 -07005482 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005483 } else {
5484 return BAD_VALUE;
5485 }
5486 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5487 sp<DeviceDescriptor> deviceDesc;
5488 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5489 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5490 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5491 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5492 } else {
5493 return BAD_VALUE;
5494 }
5495 if (deviceDesc == NULL) {
5496 return BAD_VALUE;
5497 }
Eric Laurenta121f902014-06-03 13:32:54 -07005498 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005499 } else {
5500 return BAD_VALUE;
5501 }
5502
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005503 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005504 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5505 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005506 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005507 audioPortConfig->toAudioPortConfig(&newConfig, config);
5508 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005509 }
Eric Laurenta121f902014-06-03 13:32:54 -07005510 if (status != NO_ERROR) {
5511 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005512 }
Eric Laurente1715a42014-05-20 11:30:42 -07005513
5514 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005515}
5516
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005517void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5518{
Eric Laurentd60560a2015-04-10 11:31:20 -07005519 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005520 clearAudioPatches(uid);
5521 clearSessionRoutes(uid);
5522}
5523
Eric Laurent6a94d692014-05-20 11:18:06 -07005524void AudioPolicyManager::clearAudioPatches(uid_t uid)
5525{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005526 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005528 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005529 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005530 }
5531 }
5532}
5533
François Gaffiec005e562018-11-06 15:04:49 +01005534void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005535{
François Gaffiec005e562018-11-06 15:04:49 +01005536 // Take the first attributes following the product strategy as it is used to retrieve the routed
5537 // device. All attributes wihin a strategy follows the same "routing strategy"
5538 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5539 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005540 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005541 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005542 for (size_t j = 0; j < mOutputs.size(); j++) {
5543 if (mOutputs.keyAt(j) == ouptutToSkip) {
5544 continue;
5545 }
5546 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005547 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005548 continue;
5549 }
5550 // If the default device for this strategy is on another output mix,
5551 // invalidate all tracks in this strategy to force re connection.
5552 // Otherwise select new device on the output mix.
5553 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005554 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005555 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005556 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5557 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5558 // If the device is using preferred mixer attributes, the output need to reopen
5559 // with default configuration when the new selected devices are different from
5560 // current routing devices.
5561 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5562 continue;
5563 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305564 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005565 }
5566 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005567 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005568}
5569
5570void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5571{
5572 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005573 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005574 for (size_t i = 0; i < mOutputs.size(); i++) {
5575 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005576 for (const auto& client : outputDesc->getClientIterable()) {
5577 if (client->hasPreferredDevice() && client->uid() == uid) {
5578 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005579 auto clientStrategy = client->strategy();
5580 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5581 end(affectedStrategies)) {
5582 continue;
5583 }
5584 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005585 }
5586 }
5587 }
5588 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005589 for (const auto& strategy : affectedStrategies) {
5590 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005591 }
5592
5593 // remove input routes associated with this uid
5594 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005595 for (size_t i = 0; i < mInputs.size(); i++) {
5596 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005597 for (const auto& client : inputDesc->getClientIterable()) {
5598 if (client->hasPreferredDevice() && client->uid() == uid) {
5599 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5600 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005601 }
5602 }
5603 }
5604 // reroute inputs if necessary
5605 SortedVector<audio_io_handle_t> inputsToClose;
5606 for (size_t i = 0; i < mInputs.size(); i++) {
5607 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005608 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005609 inputsToClose.add(inputDesc->mIoHandle);
5610 }
5611 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005612 for (const auto& input : inputsToClose) {
5613 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005614 }
5615}
5616
Eric Laurentd60560a2015-04-10 11:31:20 -07005617void AudioPolicyManager::clearAudioSources(uid_t uid)
5618{
5619 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005620 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5621 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005622 stopAudioSource(mAudioSources.keyAt(i));
5623 }
5624 }
5625}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005626
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005627status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5628 audio_io_handle_t *ioHandle,
5629 audio_devices_t *device)
5630{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005631 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5632 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005633 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005634 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5635 if (deviceDesc == nullptr) {
5636 return INVALID_OPERATION;
5637 }
5638 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005639
François Gaffiedf372692015-03-19 10:43:27 +01005640 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005641}
5642
Eric Laurentd60560a2015-04-10 11:31:20 -07005643status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005644 const audio_attributes_t *attributes,
5645 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005646 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005647{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005648 ALOGV("%s", __FUNCTION__);
5649 *portId = AUDIO_PORT_HANDLE_NONE;
5650
5651 if (source == NULL || attributes == NULL || portId == NULL) {
5652 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5653 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005654 return BAD_VALUE;
5655 }
5656
Eric Laurentd60560a2015-04-10 11:31:20 -07005657 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5658 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005659 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5660 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005661 return INVALID_OPERATION;
5662 }
5663
François Gaffie11d30102018-11-02 16:09:09 +01005664 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005665 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005666 String8(source->ext.device.address),
5667 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005668 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005669 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005670 return BAD_VALUE;
5671 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005672
jiabin4ef93452019-09-10 14:29:54 -07005673 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005674
François Gaffieaaac0fd2018-11-22 17:56:39 +01005675 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005676 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005677 mEngine->getStreamTypeForAttributes(*attributes),
5678 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005679 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005680
5681 status_t status = connectAudioSource(sourceDesc);
5682 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005683 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005684 }
5685 return status;
5686}
5687
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005688status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005689{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005690 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005691
5692 // make sure we only have one patch per source.
5693 disconnectAudioSource(sourceDesc);
5694
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005695 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005696 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5697 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5698 sourceDesc->srcDevice()->type(),
5699 String8(sourceDesc->srcDevice()->address().c_str()),
5700 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005701 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005702 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005703 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005704 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005705 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5706 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5707 return INVALID_OPERATION;
5708 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005709 PatchBuilder patchBuilder;
5710 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5711 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005712
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005713 return connectAudioSourceToSink(
5714 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005715}
5716
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005717status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005718{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005719 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5720 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005721 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005722 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005723 return BAD_VALUE;
5724 }
5725 status_t status = disconnectAudioSource(sourceDesc);
5726
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005727 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005728 return status;
5729}
5730
Andy Hung2ddee192015-12-18 17:34:44 -08005731status_t AudioPolicyManager::setMasterMono(bool mono)
5732{
5733 if (mMasterMono == mono) {
5734 return NO_ERROR;
5735 }
5736 mMasterMono = mono;
5737 // if enabling mono we close all offloaded devices, which will invalidate the
5738 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5739 // for recreating the new AudioTrack as non-offloaded PCM.
5740 //
5741 // If disabling mono, we leave all tracks as is: we don't know which clients
5742 // and tracks are able to be recreated as offloaded. The next "song" should
5743 // play back offloaded.
5744 if (mMasterMono) {
5745 Vector<audio_io_handle_t> offloaded;
5746 for (size_t i = 0; i < mOutputs.size(); ++i) {
5747 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5748 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5749 offloaded.push(desc->mIoHandle);
5750 }
5751 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005752 for (const auto& handle : offloaded) {
5753 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005754 }
5755 }
5756 // update master mono for all remaining outputs
5757 for (size_t i = 0; i < mOutputs.size(); ++i) {
5758 updateMono(mOutputs.keyAt(i));
5759 }
5760 return NO_ERROR;
5761}
5762
5763status_t AudioPolicyManager::getMasterMono(bool *mono)
5764{
5765 *mono = mMasterMono;
5766 return NO_ERROR;
5767}
5768
Eric Laurentac9cef52017-06-09 15:46:26 -07005769float AudioPolicyManager::getStreamVolumeDB(
5770 audio_stream_type_t stream, int index, audio_devices_t device)
5771{
jiabin9a3361e2019-10-01 09:38:30 -07005772 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005773}
5774
jiabin81772902018-04-02 17:52:27 -07005775status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5776 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005777 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005778{
Kriti Dang6537def2021-03-02 13:46:59 +01005779 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5780 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005781 return BAD_VALUE;
5782 }
Kriti Dang6537def2021-03-02 13:46:59 +01005783 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5784 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005785
5786 size_t formatsWritten = 0;
5787 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005788
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005789 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005790 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5791 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005792 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005793 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005794 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005795 bool formatEnabled = true;
5796 switch (forceUse) {
5797 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005798 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005799 break;
5800 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5801 formatEnabled = false;
5802 break;
5803 default: // AUTO or ALWAYS => true
5804 break;
jiabin81772902018-04-02 17:52:27 -07005805 }
5806 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5807 }
jiabin81772902018-04-02 17:52:27 -07005808 }
5809 return NO_ERROR;
5810}
5811
Kriti Dang6537def2021-03-02 13:46:59 +01005812status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5813 audio_format_t *surroundFormats) {
5814 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5815 return BAD_VALUE;
5816 }
5817 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5818 __func__, *numSurroundFormats, surroundFormats);
5819
5820 size_t formatsWritten = 0;
5821 size_t formatsMax = *numSurroundFormats;
5822 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5823
5824 // Return formats from all device profiles that have already been resolved by
5825 // checkOutputsForDevice().
5826 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5827 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5828 audio_devices_t deviceType = device->type();
5829 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5830 // returns formats reported by HDMI devices.
5831 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5832 continue;
5833 }
5834 // Formats reported by sink devices
5835 std::unordered_set<audio_format_t> formatset;
5836 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5837 formatset.insert(it->second.begin(), it->second.end());
5838 }
5839
5840 // Formats hard-coded in the in policy configuration file (if any).
5841 FormatVector encodedFormats = device->encodedFormats();
5842 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5843 // Filter the formats which are supported by the vendor hardware.
5844 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005845 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005846 formats.insert(*it);
5847 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005848 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005849 if (pair.second.count(*it) != 0) {
5850 formats.insert(pair.first);
5851 break;
5852 }
5853 }
5854 }
5855 }
5856 }
5857 *numSurroundFormats = formats.size();
5858 for (const auto& format: formats) {
5859 if (formatsWritten < formatsMax) {
5860 surroundFormats[formatsWritten++] = format;
5861 }
5862 }
5863 return NO_ERROR;
5864}
5865
jiabin81772902018-04-02 17:52:27 -07005866status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5867{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005868 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005869 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5870 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005871 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005872 return BAD_VALUE;
5873 }
5874
Mikhail Naganov100f0122018-11-29 11:22:16 -08005875 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5876 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005877 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005878 return INVALID_OPERATION;
5879 }
5880
Mikhail Naganov100f0122018-11-29 11:22:16 -08005881 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005882 return NO_ERROR;
5883 }
5884
Mikhail Naganov100f0122018-11-29 11:22:16 -08005885 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005886 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005887 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005888 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005889 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005890 }
5891 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005892 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005893 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005894 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005895 }
5896 }
5897
5898 sp<SwAudioOutputDescriptor> outputDesc;
5899 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005900 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5901 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005902 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5903 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005904 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005905 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005906 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5907 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5908 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005909 name.c_str(),
5910 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005911 if (status != NO_ERROR) {
5912 continue;
5913 }
5914 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5915 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5916 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005917 name.c_str(),
5918 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005919 profileUpdated |= (status == NO_ERROR);
5920 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005921 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005922 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005923 AUDIO_DEVICE_IN_HDMI);
5924 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5925 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005926 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005927 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005928 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5929 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5930 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005931 name.c_str(),
5932 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005933 if (status != NO_ERROR) {
5934 continue;
5935 }
5936 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5937 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5938 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005939 name.c_str(),
5940 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005941 profileUpdated |= (status == NO_ERROR);
5942 }
5943
jiabin81772902018-04-02 17:52:27 -07005944 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005945 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005946 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005947 }
5948
5949 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5950}
5951
Eric Laurent5ada82e2019-08-29 17:53:54 -07005952void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005953{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005954 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005955 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005956 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005957 }
5958}
5959
jiabin6012f912018-11-02 17:06:30 -07005960bool AudioPolicyManager::isHapticPlaybackSupported()
5961{
5962 for (const auto& hwModule : mHwModules) {
5963 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5964 for (const auto &outProfile : outputProfiles) {
5965 struct audio_port audioPort;
5966 outProfile->toAudioPort(&audioPort);
5967 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5968 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5969 return true;
5970 }
5971 }
5972 }
5973 }
5974 return false;
5975}
5976
Carter Hsu325a8eb2022-01-19 19:56:51 +08005977bool AudioPolicyManager::isUltrasoundSupported()
5978{
5979 bool hasUltrasoundOutput = false;
5980 bool hasUltrasoundInput = false;
5981 for (const auto& hwModule : mHwModules) {
5982 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5983 if (!hasUltrasoundOutput) {
5984 for (const auto &outProfile : outputProfiles) {
5985 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5986 hasUltrasoundOutput = true;
5987 break;
5988 }
5989 }
5990 }
5991
5992 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5993 if (!hasUltrasoundInput) {
5994 for (const auto &inputProfile : inputProfiles) {
5995 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5996 hasUltrasoundInput = true;
5997 break;
5998 }
5999 }
6000 }
6001
6002 if (hasUltrasoundOutput && hasUltrasoundInput)
6003 return true;
6004 }
6005 return false;
6006}
6007
Atneya Nair698f5ef2022-12-15 16:15:09 -08006008bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6009{
6010 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6011 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6012 for (const auto& hwModule : mHwModules) {
6013 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6014 for (const auto &inputProfile : inputProfiles) {
6015 if ((inputProfile->getFlags() & mask) == mask) {
6016 return true;
6017 }
6018 }
6019 }
6020 return false;
6021}
6022
Eric Laurent8340e672019-11-06 11:01:08 -08006023bool AudioPolicyManager::isCallScreenModeSupported()
6024{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006025 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006026}
6027
6028
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006029status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006030{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006031 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006032 if (!sourceDesc->isConnected()) {
6033 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6034 return NO_ERROR;
6035 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006036 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6037 if (swOutput != 0) {
6038 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006039 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006040 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006041 }
jiabinbce0c1d2020-10-05 11:20:18 -07006042 if (releaseOutput(sourceDesc->portId())) {
6043 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6044 // no need to release audio patch here but just return NO_ERROR.
6045 return NO_ERROR;
6046 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006047 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006048 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006049 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006050 // close Hwoutput and remove from mHwOutputs
6051 } else {
6052 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6053 }
6054 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006055 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006056 sourceDesc->disconnect();
6057 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006058}
6059
François Gaffiec005e562018-11-06 15:04:49 +01006060sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6061 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006062{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006063 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006064 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006065 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006066 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006067 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6068 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006069 source = sourceDesc;
6070 break;
6071 }
6072 }
6073 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006074}
6075
Eric Laurentb4f42a92022-01-17 17:37:31 +01006076bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006077 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006078 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006079{
6080 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6081 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006082 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006083 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006084 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6085 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6086 return false;
6087 }
6088 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6089 return false;
6090 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006091 }
6092
Eric Laurentd332bc82023-08-04 11:45:23 +02006093 // The caller can have the audio config criteria ignored by either passing a null ptr or
6094 // the AUDIO_CONFIG_INITIALIZER value.
6095 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006096 // some positional channel masks and PCM format and for stereo if low latency performance
6097 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006098
6099 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006100 static const bool stereo_spatialization_enabled =
6101 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006102 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006103 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006104 ? audio_channel_mask_contains_stereo(config->channel_mask)
6105 : audio_is_channel_mask_spatialized(config->channel_mask);
6106 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006107 return false;
6108 }
6109 if (!audio_is_linear_pcm(config->format)) {
6110 return false;
6111 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006112 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6113 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6114 return false;
6115 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006116 }
6117
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006118 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006119 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006120 if (profile == nullptr) {
6121 return false;
6122 }
6123
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006124 return true;
6125}
6126
Shunkai Yao4c3af932024-04-26 04:12:21 +00006127// The Spatializer output is compatible with Haptic use cases if:
6128// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6129// with client if client haptic channel bits were set, or
6130// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6131// including the haptic bits or creating the HapticGenerator effect for same session.
6132bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6133 const audio_config_t* config, audio_session_t sessionId) const {
6134 const auto clientHapticChannel =
6135 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6136 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6137 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6138
6139 if (threadOutputHapticChannel) {
6140 // check format and sampleRate match if client haptic channel mask exist
6141 if (clientHapticChannel) {
6142 return mSpatializerOutput->getFormat() == config->format &&
6143 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6144 }
6145 return true;
6146 } else {
6147 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6148 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6149 // HapticGenerator effect for this session) are not supported.
6150 return clientHapticChannel == 0 &&
6151 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6152 }
6153}
6154
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006155void AudioPolicyManager::checkVirtualizerClientRoutes() {
6156 std::set<audio_stream_type_t> streamsToInvalidate;
6157 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006158 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6159 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006160 audio_attributes_t attr = client->attributes();
6161 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6162 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6163 audio_config_base_t clientConfig = client->config();
6164 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006165 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006166 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006167 streamsToInvalidate.insert(client->stream());
6168 }
6169 }
6170 }
6171
jiabinc44b3462022-12-08 12:52:31 -08006172 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006173}
6174
Eric Laurente191d1b2022-04-15 11:59:25 +02006175
6176bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6177 const sp<SwAudioOutputDescriptor>& outputDesc) {
6178 if (outputDesc->isDuplicated()) {
6179 return false;
6180 }
6181 DeviceVector devices = outputDesc->supportedDevices();
6182 for (size_t i = 0; i < mOutputs.size(); i++) {
6183 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6184 if (desc == outputDesc || desc->isDuplicated()) {
6185 continue;
6186 }
6187 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6188 if (!sharedDevices.isEmpty()
6189 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6190 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6191 return false;
6192 }
6193 }
6194 return true;
6195}
6196
6197
Eric Laurentfa0f6742021-08-17 18:39:44 +02006198status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006199 const audio_attributes_t *attr,
6200 audio_io_handle_t *output) {
6201 *output = AUDIO_IO_HANDLE_NONE;
6202
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006203 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6204 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6205 audio_config_t *configPtr = nullptr;
6206 audio_config_t config;
6207 if (mixerConfig != nullptr) {
6208 config = audio_config_initializer(mixerConfig);
6209 configPtr = &config;
6210 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006211 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006212 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006213 return BAD_VALUE;
6214 }
6215
6216 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006217 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006218 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006219 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006220 return BAD_VALUE;
6221 }
6222
Eric Laurente191d1b2022-04-15 11:59:25 +02006223 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006224 for (size_t i = 0; i < mOutputs.size(); i++) {
6225 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006226 if (!desc->isDuplicated()
6227 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6228 spatializerOutputs.push_back(desc);
6229 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006230 }
6231 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006232 mSpatializerOutput.clear();
6233 bool outputsChanged = false;
6234 for (const auto& desc : spatializerOutputs) {
6235 if (desc->mProfile == profile
6236 && (configPtr == nullptr
6237 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6238 mSpatializerOutput = desc;
6239 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6240 } else {
6241 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6242 " and devices %s", __func__, desc->mIoHandle,
6243 configPtr != nullptr ? configPtr->channel_mask : 0,
6244 devices.toString().c_str());
6245 closeOutput(desc->mIoHandle);
6246 outputsChanged = true;
6247 }
Eric Laurent39095982021-08-24 18:29:27 +02006248 }
6249
Eric Laurente191d1b2022-04-15 11:59:25 +02006250 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006251 sp<SwAudioOutputDescriptor> desc =
6252 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006253 if (desc != nullptr) {
6254 mSpatializerOutput = desc;
6255 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006256 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006257 }
6258
6259 checkVirtualizerClientRoutes();
6260
Eric Laurente191d1b2022-04-15 11:59:25 +02006261 if (outputsChanged) {
6262 mPreviousOutputs = mOutputs;
6263 mpClientInterface->onAudioPortListUpdate();
6264 }
6265
6266 if (mSpatializerOutput == nullptr) {
6267 ALOGV("%s could not open spatializer output with requested config", __func__);
6268 return BAD_VALUE;
6269 }
Eric Laurent39095982021-08-24 18:29:27 +02006270 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006271 ALOGV("%s returning new spatializer output %d", __func__, *output);
6272 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006273}
6274
Eric Laurentfa0f6742021-08-17 18:39:44 +02006275status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6276 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006277 return INVALID_OPERATION;
6278 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006279 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006280 return BAD_VALUE;
6281 }
Eric Laurent39095982021-08-24 18:29:27 +02006282
Eric Laurente191d1b2022-04-15 11:59:25 +02006283 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6284 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6285 closeOutput(mSpatializerOutput->mIoHandle);
6286 //from now on mSpatializerOutput is null
6287 checkVirtualizerClientRoutes();
6288 }
Eric Laurent39095982021-08-24 18:29:27 +02006289
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006290 return NO_ERROR;
6291}
6292
Eric Laurente552edb2014-03-10 17:42:56 -07006293// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006294// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006295// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006296uint32_t AudioPolicyManager::nextAudioPortGeneration()
6297{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006298 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006299}
6300
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006301AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006302 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006303 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006304 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006305 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006306 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006307 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006308 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006309 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006310 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006311 mAudioPortGeneration(1),
6312 mBeaconMuteRefCount(0),
6313 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006314 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006315 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006316 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006317 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006318{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006319}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006320
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006321status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006322 if (mEngine == nullptr) {
6323 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006324 }
6325 mEngine->setObserver(this);
6326 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006327 if (status != NO_ERROR) {
6328 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6329 return status;
6330 }
François Gaffie2110e042015-03-24 08:41:51 +01006331
jiabin29230182023-04-04 21:02:36 +00006332 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6333 // at the end of this function.
6334 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006335 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6336 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6337
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006338 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006339 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006340 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006341
Eric Laurent3a4311c2014-03-17 12:00:47 -07006342 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006343 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6344 defaultOutputDevice == nullptr ||
6345 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6346 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6347 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006348 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006349 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006350 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006351
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006352 // Silence ALOGV statements
6353 property_set("log.tag." LOG_TAG, "D");
6354
Eric Laurente552edb2014-03-10 17:42:56 -07006355 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006356 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006357}
6358
Eric Laurente0720872014-03-11 09:30:41 -07006359AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006360{
Eric Laurente552edb2014-03-10 17:42:56 -07006361 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006362 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006363 }
6364 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006365 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006366 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006367 mAvailableOutputDevices.clear();
6368 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006369 mOutputs.clear();
6370 mInputs.clear();
6371 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006372 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006373 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006374}
6375
Eric Laurente0720872014-03-11 09:30:41 -07006376status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006377{
Eric Laurent87ffa392015-05-22 10:32:38 -07006378 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006379}
6380
Eric Laurente552edb2014-03-10 17:42:56 -07006381// ---
6382
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006383void AudioPolicyManager::onNewAudioModulesAvailable()
6384{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006385 DeviceVector newDevices;
6386 onNewAudioModulesAvailableInt(&newDevices);
6387 if (!newDevices.empty()) {
6388 nextAudioPortGeneration();
6389 mpClientInterface->onAudioPortListUpdate();
6390 }
6391}
6392
6393void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6394{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006395 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006396 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6397 continue;
6398 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006399 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006400 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6401 handle != AUDIO_MODULE_HANDLE_NONE) {
6402 hwModule->setHandle(handle);
6403 } else {
6404 ALOGW("could not load HW module %s", hwModule->getName());
6405 continue;
6406 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006407 }
6408 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006409 // open all output streams needed to access attached devices.
6410 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006411 // This also validates mAvailableOutputDevices list
6412 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6413 if (!outProfile->canOpenNewIo()) {
6414 ALOGE("Invalid Output profile max open count %u for profile %s",
6415 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6416 continue;
6417 }
6418 if (!outProfile->hasSupportedDevices()) {
6419 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6420 continue;
6421 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006422 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6423 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006424 mTtsOutputAvailable = true;
6425 }
6426
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006427 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006428 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006429 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006430 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6431 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006432 } else {
6433 // choose first device present in profile's SupportedDevices also part of
6434 // mAvailableOutputDevices.
6435 if (availProfileDevices.isEmpty()) {
6436 continue;
6437 }
6438 supportedDevice = availProfileDevices.itemAt(0);
6439 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006440 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006441 continue;
6442 }
6443 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6444 mpClientInterface);
6445 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006446 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6447 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006448 AUDIO_STREAM_DEFAULT,
6449 AUDIO_OUTPUT_FLAG_NONE, &output);
6450 if (status != NO_ERROR) {
6451 ALOGW("Cannot open output stream for devices %s on hw module %s",
6452 supportedDevice->toString().c_str(), hwModule->getName());
6453 continue;
6454 }
6455 for (const auto &device : availProfileDevices) {
6456 // give a valid ID to an attached device once confirmed it is reachable
6457 if (!device->isAttached()) {
6458 device->attach(hwModule);
6459 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006460 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006461 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006462 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6463 }
6464 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006465 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006466 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6467 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006468 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006469 }
Eric Laurent39095982021-08-24 18:29:27 +02006470 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006471 outputDesc->close();
6472 } else {
6473 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306474 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006475 DeviceVector(supportedDevice),
6476 true,
6477 0,
6478 NULL);
6479 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006480 }
6481 // open input streams needed to access attached devices to validate
6482 // mAvailableInputDevices list
6483 for (const auto& inProfile : hwModule->getInputProfiles()) {
6484 if (!inProfile->canOpenNewIo()) {
6485 ALOGE("Invalid Input profile max open count %u for profile %s",
6486 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6487 continue;
6488 }
6489 if (!inProfile->hasSupportedDevices()) {
6490 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6491 continue;
6492 }
6493 // chose first device present in profile's SupportedDevices also part of
6494 // available input devices
6495 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006496 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006497 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006498 ALOGV("%s: Input device list is empty! for profile %s",
6499 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006500 continue;
6501 }
6502 sp<AudioInputDescriptor> inputDesc =
6503 new AudioInputDescriptor(inProfile, mpClientInterface);
6504
6505 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6506 status_t status = inputDesc->open(nullptr,
6507 availProfileDevices.itemAt(0),
6508 AUDIO_SOURCE_MIC,
6509 AUDIO_INPUT_FLAG_NONE,
6510 &input);
6511 if (status != NO_ERROR) {
6512 ALOGW("Cannot open input stream for device %s on hw module %s",
6513 availProfileDevices.toString().c_str(),
6514 hwModule->getName());
6515 continue;
6516 }
6517 for (const auto &device : availProfileDevices) {
6518 // give a valid ID to an attached device once confirmed it is reachable
6519 if (!device->isAttached()) {
6520 device->attach(hwModule);
6521 device->importAudioPortAndPickAudioProfile(inProfile, true);
6522 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006523 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006524 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6525 }
6526 }
6527 inputDesc->close();
6528 }
6529 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006530
6531 // Check if spatializer outputs can be closed until used.
6532 // mOutputs vector never contains duplicated outputs at this point.
6533 std::vector<audio_io_handle_t> outputsClosed;
6534 for (size_t i = 0; i < mOutputs.size(); i++) {
6535 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6536 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6537 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6538 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006539 nextAudioPortGeneration();
6540 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6541 if (index >= 0) {
6542 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6543 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6544 patchDesc->getAfHandle(), 0);
6545 mAudioPatches.removeItemsAt(index);
6546 mpClientInterface->onAudioPatchListUpdate();
6547 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006548 desc->close();
6549 }
6550 }
6551 for (auto output : outputsClosed) {
6552 removeOutput(output);
6553 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006554}
6555
Eric Laurent98e38192018-02-15 18:31:53 -08006556void AudioPolicyManager::addOutput(audio_io_handle_t output,
6557 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006558{
Eric Laurent1c333e22014-05-20 10:48:17 -07006559 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006560 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006561 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006562 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006563 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006564}
6565
François Gaffie53615e22015-03-19 09:24:12 +01006566void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6567{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006568 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6569 ALOGV("%s: removing primary output", __func__);
6570 mPrimaryOutput = nullptr;
6571 }
François Gaffie53615e22015-03-19 09:24:12 +01006572 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006573 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006574}
6575
Eric Laurent98e38192018-02-15 18:31:53 -08006576void AudioPolicyManager::addInput(audio_io_handle_t input,
6577 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006578{
Eric Laurent1c333e22014-05-20 10:48:17 -07006579 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006580 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006581}
Eric Laurente552edb2014-03-10 17:42:56 -07006582
François Gaffie11d30102018-11-02 16:09:09 +01006583status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006584 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006585 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006586{
François Gaffie11d30102018-11-02 16:09:09 +01006587 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006588 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006589 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006590
François Gaffie11d30102018-11-02 16:09:09 +01006591 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006592 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006593 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006594 }
Eric Laurente552edb2014-03-10 17:42:56 -07006595
Eric Laurent3b73df72014-03-11 09:06:29 -07006596 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006597 // first call getAudioPort to get the supported attributes from the HAL
6598 struct audio_port_v7 port = {};
6599 device->toAudioPort(&port);
6600 status_t status = mpClientInterface->getAudioPort(&port);
6601 if (status == NO_ERROR) {
6602 device->importAudioPort(port);
6603 }
6604
6605 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006606 for (size_t i = 0; i < mOutputs.size(); i++) {
6607 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006608 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006609 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006610 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6611 mOutputs.keyAt(i), device->toString().c_str());
6612 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006613 }
6614 }
6615 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006616 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006617 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006618 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6619 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006620 if (profile->supportsDevice(device)) {
6621 profiles.add(profile);
6622 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6623 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006624 }
6625 }
6626 }
6627
Eric Laurent7b279bb2015-12-14 10:18:23 -08006628 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006629
Eric Laurente552edb2014-03-10 17:42:56 -07006630 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006631 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006632 return BAD_VALUE;
6633 }
6634
6635 // open outputs for matching profiles if needed. Direct outputs are also opened to
6636 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6637 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006638 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006639
6640 // nothing to do if one output is already opened for this profile
6641 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006642 for (j = 0; j < outputs.size(); j++) {
6643 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006644 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006645 // matching profile: save the sample rates, format and channel masks supported
6646 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006647 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006648 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006649 }
Eric Laurente552edb2014-03-10 17:42:56 -07006650 break;
6651 }
6652 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006653 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006654 continue;
6655 }
6656
Eric Laurent3974e3b2017-12-07 17:58:43 -08006657 if (!profile->canOpenNewIo()) {
6658 ALOGW("Max Output number %u already opened for this profile %s",
6659 profile->maxOpenCount, profile->getTagName().c_str());
6660 continue;
6661 }
6662
Eric Laurent83efe1c2017-07-09 16:51:08 -07006663 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006664 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006665 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6666 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006667 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006668 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006669 profiles.removeAt(profile_index);
6670 profile_index--;
6671 } else {
6672 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006673 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006674 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006675 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6676 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006677 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006678 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006679
François Gaffie11d30102018-11-02 16:09:09 +01006680 if (device_distinguishes_on_address(deviceType)) {
6681 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6682 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306683 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6684 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006685 }
Eric Laurente552edb2014-03-10 17:42:56 -07006686 ALOGV("checkOutputsForDevice(): adding output %d", output);
6687 }
6688 }
6689
6690 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006691 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006692 return BAD_VALUE;
6693 }
Eric Laurentd4692962014-05-05 18:13:44 -07006694 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006695 // check if one opened output is not needed any more after disconnecting one device
6696 for (size_t i = 0; i < mOutputs.size(); i++) {
6697 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006698 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006699 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006700 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006701 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006702 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006703 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006704 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6705 mOutputs.keyAt(i));
6706 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006707 }
Eric Laurente552edb2014-03-10 17:42:56 -07006708 }
6709 }
Eric Laurentd4692962014-05-05 18:13:44 -07006710 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006711 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006712 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6713 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006714 if (!profile->supportsDevice(device)) {
6715 continue;
6716 }
6717 ALOGV("checkOutputsForDevice(): "
6718 "clearing direct output profile %zu on module %s",
6719 j, hwModule->getName());
6720 profile->clearAudioProfiles();
6721 if (!profile->hasDynamicAudioProfile()) {
6722 continue;
6723 }
6724 // When a device is disconnected, if there is an IOProfile that contains dynamic
6725 // profiles and supports the disconnected device, call getAudioPort to repopulate
6726 // the capabilities of the devices that is supported by the IOProfile.
6727 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6728 if (supportedDevice == device ||
6729 !mAvailableOutputDevices.contains(supportedDevice)) {
6730 continue;
6731 }
6732 struct audio_port_v7 port;
6733 supportedDevice->toAudioPort(&port);
6734 status_t status = mpClientInterface->getAudioPort(&port);
6735 if (status == NO_ERROR) {
6736 supportedDevice->importAudioPort(port);
6737 }
Eric Laurente552edb2014-03-10 17:42:56 -07006738 }
6739 }
6740 }
6741 }
6742 return NO_ERROR;
6743}
6744
François Gaffie11d30102018-11-02 16:09:09 +01006745status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006746 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006747{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006748 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006749
François Gaffie11d30102018-11-02 16:09:09 +01006750 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006751 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006752 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006753 }
6754
Eric Laurentd4692962014-05-05 18:13:44 -07006755 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006756 // first call getAudioPort to get the supported attributes from the HAL
6757 struct audio_port_v7 port = {};
6758 device->toAudioPort(&port);
6759 status_t status = mpClientInterface->getAudioPort(&port);
6760 if (status == NO_ERROR) {
6761 device->importAudioPort(port);
6762 }
6763
Eric Laurent0dd51852019-04-19 18:18:58 -07006764 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006765 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006766 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006767 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006768 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006769 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006770 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006771
François Gaffie11d30102018-11-02 16:09:09 +01006772 if (profile->supportsDevice(device)) {
6773 profiles.add(profile);
6774 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6775 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006776 }
6777 }
6778 }
6779
Eric Laurent0dd51852019-04-19 18:18:58 -07006780 if (profiles.isEmpty()) {
6781 ALOGW("%s: No input profile available for device %s",
6782 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006783 return BAD_VALUE;
6784 }
6785
6786 // open inputs for matching profiles if needed. Direct inputs are also opened to
6787 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6788 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6789
Eric Laurent1c333e22014-05-20 10:48:17 -07006790 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006791
Eric Laurentd4692962014-05-05 18:13:44 -07006792 // nothing to do if one input is already opened for this profile
6793 size_t input_index;
6794 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6795 desc = mInputs.valueAt(input_index);
6796 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006797 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006798 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006799 }
Eric Laurentd4692962014-05-05 18:13:44 -07006800 break;
6801 }
6802 }
6803 if (input_index != mInputs.size()) {
6804 continue;
6805 }
6806
Eric Laurent3974e3b2017-12-07 17:58:43 -08006807 if (!profile->canOpenNewIo()) {
6808 ALOGW("Max Input number %u already opened for this profile %s",
6809 profile->maxOpenCount, profile->getTagName().c_str());
6810 continue;
6811 }
6812
Eric Laurentfe231122017-11-17 17:48:06 -08006813 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006814 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006815 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006816
Eric Laurentcf2c0212014-07-25 16:20:43 -07006817 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006818 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006819 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006820 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006821 mpClientInterface->setParameters(input, String8(param));
6822 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006823 }
jiabin12537fc2023-10-12 17:56:08 +00006824 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006825 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006826 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006827 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006828 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006829 }
6830
Eric Laurent0dd51852019-04-19 18:18:58 -07006831 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006832 addInput(input, desc);
6833 }
6834 } // endif input != 0
6835
Eric Laurentcf2c0212014-07-25 16:20:43 -07006836 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006837 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006838 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006839 profiles.removeAt(profile_index);
6840 profile_index--;
6841 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006842 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006843 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006844 }
Eric Laurentd4692962014-05-05 18:13:44 -07006845 ALOGV("checkInputsForDevice(): adding input %d", input);
6846 }
6847 } // end scan profiles
6848
6849 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006850 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006851 return BAD_VALUE;
6852 }
6853 } else {
6854 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006855 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006856 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006857 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006858 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006859 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006860 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006861 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006862 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6863 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006864 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006865 }
6866 }
6867 }
6868 } // end disconnect
6869
6870 return NO_ERROR;
6871}
6872
6873
Eric Laurente0720872014-03-11 09:30:41 -07006874void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006875{
6876 ALOGV("closeOutput(%d)", output);
6877
François Gaffie1c878552018-11-22 16:53:21 +01006878 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6879 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006880 ALOGW("closeOutput() unknown output %d", output);
6881 return;
6882 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006883 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006884 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006885
Eric Laurente552edb2014-03-10 17:42:56 -07006886 // look for duplicated outputs connected to the output being removed.
6887 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006888 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6889 if (dupOutput->isDuplicated() &&
6890 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6891 sp<SwAudioOutputDescriptor> remainingOutput =
6892 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006893 // As all active tracks on duplicated output will be deleted,
6894 // and as they were also referenced on the other output, the reference
6895 // count for their stream type must be adjusted accordingly on
6896 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006897 const bool wasActive = remainingOutput->isActive();
6898 // Note: no-op on the closing output where all clients has already been set inactive
6899 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006900 // stop() will be a no op if the output is still active but is needed in case all
6901 // active streams refcounts where cleared above
6902 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006903 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006904 }
Eric Laurente552edb2014-03-10 17:42:56 -07006905 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6906 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6907
6908 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006909 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006910 }
6911 }
6912
Eric Laurent05b90f82014-08-27 15:32:29 -07006913 nextAudioPortGeneration();
6914
François Gaffie1c878552018-11-22 16:53:21 +01006915 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006916 if (index >= 0) {
6917 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006918 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6919 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006920 mAudioPatches.removeItemsAt(index);
6921 mpClientInterface->onAudioPatchListUpdate();
6922 }
6923
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006924 if (closingOutputWasActive) {
6925 closingOutput->stop();
6926 }
François Gaffie1c878552018-11-22 16:53:21 +01006927 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006928 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6929 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6930 for (const auto device : closingOutput->devices()) {
6931 device->setPreferredConfig(nullptr);
6932 }
6933 }
Eric Laurente552edb2014-03-10 17:42:56 -07006934
François Gaffie53615e22015-03-19 09:24:12 +01006935 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006936 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006937 if (closingOutput == mSpatializerOutput) {
6938 mSpatializerOutput.clear();
6939 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006940
6941 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6942 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006943 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006944 bool directOutputOpen = false;
6945 for (size_t i = 0; i < mOutputs.size(); i++) {
6946 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6947 directOutputOpen = true;
6948 break;
6949 }
6950 }
6951 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006952 ALOGV("no direct outputs open, reset MSD patches");
6953 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6954 // how output devices for patching are resolved. Avoid by caching and reusing the
6955 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6956 // devices to patch to. This may be complicated by the fact that devices may become
6957 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006958 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006959 }
6960 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006961}
6962
6963void AudioPolicyManager::closeInput(audio_io_handle_t input)
6964{
6965 ALOGV("closeInput(%d)", input);
6966
6967 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6968 if (inputDesc == NULL) {
6969 ALOGW("closeInput() unknown input %d", input);
6970 return;
6971 }
6972
Eric Laurent6a94d692014-05-20 11:18:06 -07006973 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006974
François Gaffie11d30102018-11-02 16:09:09 +01006975 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006976 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006977 if (index >= 0) {
6978 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006979 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6980 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006981 mAudioPatches.removeItemsAt(index);
6982 mpClientInterface->onAudioPatchListUpdate();
6983 }
6984
François Gaffie6ebbce02023-07-19 13:27:53 +02006985 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006986 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006987 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006988
François Gaffie11d30102018-11-02 16:09:09 +01006989 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6990 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006991 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006992 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006993 }
Eric Laurente552edb2014-03-10 17:42:56 -07006994}
6995
François Gaffie11d30102018-11-02 16:09:09 +01006996SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6997 const DeviceVector &devices,
6998 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006999{
7000 SortedVector<audio_io_handle_t> outputs;
7001
François Gaffie11d30102018-11-02 16:09:09 +01007002 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007003 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007004 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007005 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007006 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007007 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007008 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007009 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007010 outputs.add(openOutputs.keyAt(i));
7011 }
7012 }
7013 return outputs;
7014}
7015
Mikhail Naganov37977152018-07-11 15:54:44 -07007016void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7017{
7018 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7019 // output is suspended before any tracks are moved to it
7020 checkA2dpSuspend();
7021 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007022 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007023 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007024 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007025 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007026 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7027 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7028 // configuration changes will ultimately be rerouted correctly. We can still avoid
7029 // unnecessary rerouting by caching and reusing the arguments to
7030 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7031 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007032 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007033 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007034 // an event that changed routing likely occurred, inform upper layers
7035 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007036}
7037
François Gaffiec005e562018-11-06 15:04:49 +01007038bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7039 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007040{
François Gaffiec005e562018-11-06 15:04:49 +01007041 return mEngine->getProductStrategyForAttributes(lAttr) ==
7042 mEngine->getProductStrategyForAttributes(rAttr);
7043}
7044
Francois Gaffieff1eb522020-05-06 18:37:04 +02007045void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7046{
7047 for (size_t i = 0; i < mAudioSources.size(); i++) {
7048 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7049 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007050 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007051 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007052 connectAudioSource(sourceDesc);
7053 }
7054 }
7055}
7056
7057void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7058{
7059 for (size_t i = 0; i < mAudioSources.size(); i++) {
7060 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7061 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7062 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7063 disconnectAudioSource(sourceDesc);
7064 }
7065 }
7066}
7067
François Gaffiec005e562018-11-06 15:04:49 +01007068void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7069{
7070 auto psId = mEngine->getProductStrategyForAttributes(attr);
7071
7072 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7073 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007074
François Gaffie11d30102018-11-02 16:09:09 +01007075 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7076 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007077
Eric Laurentc209fe42020-06-05 18:11:23 -07007078 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007079 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007080 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007081 // take into account dynamic audio policies related changes: if a client is now associated
7082 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007083 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007084 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7085 if (desc->isDuplicated()) {
7086 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007087 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007088 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7089 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7090 continue;
7091 }
7092 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007093 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007094 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7095 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7096 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007097 if (status != OK) {
7098 continue;
7099 }
yucliuf4de36d2020-09-14 14:57:56 -07007100 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007101 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007102 maxLatency = desc->latency();
7103 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007104 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007105 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007106 }
7107 }
7108
Eric Laurent56ed8842022-11-15 16:04:41 +01007109 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007110 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7111 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007112 for (audio_io_handle_t srcOut : srcOutputs) {
7113 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007114 if (desc == nullptr) continue;
7115
7116 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007117 maxLatency = desc->latency();
7118 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007119
Eric Laurent56ed8842022-11-15 16:04:41 +01007120 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007121 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007122 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007123 // a client on a non direct outputs has necessarily a linear PCM format
7124 // so we can call selectOutput() safely
7125 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7126 client->flags(),
7127 client->config().format,
7128 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007129 client->config().sample_rate,
7130 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007131 if (newOutput != srcOut) {
7132 invalidate = true;
7133 break;
7134 }
7135 } else {
7136 sp<IOProfile> profile = getProfileForOutput(newDevices,
7137 client->config().sample_rate,
7138 client->config().format,
7139 client->config().channel_mask,
7140 client->flags(),
7141 true /* directOnly */);
7142 if (profile != desc->mProfile) {
7143 invalidate = true;
7144 break;
7145 }
7146 }
7147 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007148 // mute strategy while moving tracks from one output to another
7149 if (invalidate) {
7150 invalidatedOutputs.push_back(desc);
7151 if (desc->isStrategyActive(psId)) {
7152 setStrategyMute(psId, true, desc);
7153 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7154 newDevices.types());
7155 }
Eric Laurente552edb2014-03-10 17:42:56 -07007156 }
François Gaffiec005e562018-11-06 15:04:49 +01007157 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007158 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007159 connectAudioSource(source);
7160 }
Eric Laurente552edb2014-03-10 17:42:56 -07007161 }
7162
Eric Laurent56ed8842022-11-15 16:04:41 +01007163 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7164 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7165 std::to_string(srcOutputs[0]).c_str(),
7166 std::to_string(dstOutputs[0]).c_str());
7167
François Gaffiec005e562018-11-06 15:04:49 +01007168 // Move effects associated to this stream from previous output to new output
7169 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007170 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007171 }
François Gaffiec005e562018-11-06 15:04:49 +01007172 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007173 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007174 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007175 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007176 desc->setTracksInvalidatedStatusByStrategy(psId);
7177 }
Eric Laurente552edb2014-03-10 17:42:56 -07007178 }
7179 }
7180}
7181
Eric Laurente0720872014-03-11 09:30:41 -07007182void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007183{
François Gaffiec005e562018-11-06 15:04:49 +01007184 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7185 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7186 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007187 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007188 }
Eric Laurente552edb2014-03-10 17:42:56 -07007189}
7190
Kevin Rocard153f92d2018-12-18 18:33:28 -08007191void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007192 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007193 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007194 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007195 for (size_t i = 0; i < mOutputs.size(); i++) {
7196 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7197 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007198 sp<AudioPolicyMix> primaryMix;
7199 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007200 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007201 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7202 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7203 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007204 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7205 for (auto &secondaryMix : secondaryMixes) {
7206 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7207 if (outputDesc != nullptr &&
7208 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7209 secondaryDescs.push_back(outputDesc);
7210 }
7211 }
7212
jiabinc44b3462022-12-08 12:52:31 -08007213 if (status != OK &&
7214 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7215 // When it failed to query secondary output, only invalidate the client that is not
7216 // MMAP. The reason is that MMAP stream will not support secondary output.
7217 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007218 } else if (!std::equal(
7219 client->getSecondaryOutputs().begin(),
7220 client->getSecondaryOutputs().end(),
7221 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007222 if (!audio_is_linear_pcm(client->config().format)) {
7223 // If the format is not PCM, the tracks should be invalidated to get correct
7224 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007225 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007226 } else {
7227 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7228 std::vector<audio_io_handle_t> secondaryOutputIds;
7229 for (const auto &secondaryDesc: secondaryDescs) {
7230 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7231 weakSecondaryDescs.push_back(secondaryDesc);
7232 }
7233 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7234 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007235 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007236 }
7237 }
7238 }
jiabin10a03f12021-05-07 23:46:28 +00007239 if (!trackSecondaryOutputs.empty()) {
7240 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7241 }
jiabinc44b3462022-12-08 12:52:31 -08007242 if (!clientsToInvalidate.empty()) {
7243 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7244 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007245 }
7246}
7247
Eric Laurent2517af32020-11-25 15:31:27 +01007248bool AudioPolicyManager::isScoRequestedForComm() const {
7249 AudioDeviceTypeAddrVector devices;
7250 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7251 for (const auto &device : devices) {
7252 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7253 return true;
7254 }
7255 }
7256 return false;
7257}
7258
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007259bool AudioPolicyManager::isHearingAidUsedForComm() const {
7260 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7261 true /*fromCache*/);
7262 for (const auto &device : devices) {
7263 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7264 return true;
7265 }
7266 }
7267 return false;
7268}
7269
7270
Eric Laurente0720872014-03-11 09:30:41 -07007271void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007272{
François Gaffie53615e22015-03-19 09:24:12 +01007273 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007274 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007275 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007276 return;
7277 }
7278
Eric Laurent3a4311c2014-03-17 12:00:47 -07007279 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007280 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7281 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007282 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007283
7284 // if suspended, restore A2DP output if:
7285 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007286 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007287 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007288 //
Eric Laurentf732e072016-08-03 19:30:28 -07007289 // if not suspended, suspend A2DP output if:
7290 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007291 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007292 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007293 //
7294 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007295 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007296 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007297 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007298 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007299
7300 mpClientInterface->restoreOutput(a2dpOutput);
7301 mA2dpSuspended = false;
7302 }
7303 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007304 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007305 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007306 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007307 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007308
7309 mpClientInterface->suspendOutput(a2dpOutput);
7310 mA2dpSuspended = true;
7311 }
7312 }
7313}
7314
François Gaffie11d30102018-11-02 16:09:09 +01007315DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7316 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007317{
François Gaffiedb1755b2023-09-01 11:50:35 +02007318 if (outputDesc == nullptr) {
7319 return DeviceVector{};
7320 }
François Gaffie11d30102018-11-02 16:09:09 +01007321
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007322 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007323 if (index >= 0) {
7324 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007325 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007326 ALOGV("%s device %s forced by patch %d", __func__,
7327 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7328 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007329 }
7330 }
7331
Dean Wheatley514b4312020-06-17 21:45:00 +10007332 // Do not retrieve engine device for outputs through MSD
7333 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7334 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7335 return outputDesc->devices();
7336 }
7337
Eric Laurent97ac8712018-07-27 18:59:02 -07007338 // Honor explicit routing requests only if no client using default routing is active on this
7339 // input: a specific app can not force routing for other apps by setting a preferred device.
7340 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007341 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007342 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007343 if (device != nullptr) {
7344 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007345 }
7346
François Gaffiea807ef92018-11-05 10:44:33 +01007347 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7348 // of setForceUse / Default Bus device here
7349 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7350 if (device != nullptr) {
7351 return DeviceVector(device);
7352 }
7353
François Gaffiedb1755b2023-09-01 11:50:35 +02007354 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007355 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7356 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307357 auto hasStreamActive = [&](auto stream) {
7358 return hasStream(streams, stream) && isStreamActive(stream, 0);
7359 };
Eric Laurent484e9272018-06-07 17:29:23 -07007360
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307361 auto doGetOutputDevicesForVoice = [&]() {
7362 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007363 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307364 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007365 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7366 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307367 };
7368
7369 // With low-latency playing on speaker, music on WFD, when the first low-latency
7370 // output is stopped, getNewOutputDevices checks for a product strategy
7371 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007372 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307373 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7374 // stream is associated to the output descriptor.
7375 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7376 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7377 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7378 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007379 // Retrieval of devices for voice DL is done on primary output profile, cannot
7380 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007381 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007382 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7383 break;
7384 }
Eric Laurente552edb2014-03-10 17:42:56 -07007385 }
François Gaffiec005e562018-11-06 15:04:49 +01007386 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007387 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007388}
7389
François Gaffie11d30102018-11-02 16:09:09 +01007390sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7391 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007392{
François Gaffie11d30102018-11-02 16:09:09 +01007393 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007394
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007395 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007396 if (index >= 0) {
7397 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007398 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007399 ALOGV("getNewInputDevice() device %s forced by patch %d",
7400 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7401 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007402 }
7403 }
7404
Eric Laurent97ac8712018-07-27 18:59:02 -07007405 // Honor explicit routing requests only if no client using default routing is active on this
7406 // input: a specific app can not force routing for other apps by setting a preferred device.
7407 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007408 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7409 if (device != nullptr) {
7410 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007411 }
7412
Eric Laurentdc95a252018-04-12 12:46:56 -07007413 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007414 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007415 audio_attributes_t attributes;
7416 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007417 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007418 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7419 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007420 attributes = topClient->attributes();
7421 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007422 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007423 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007424 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7425 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007426 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007427 }
7428
Francois Gaffie716e1432019-01-14 16:58:59 +01007429 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7430 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007431 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007432 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007433 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007434 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007435
Eric Laurente552edb2014-03-10 17:42:56 -07007436 return device;
7437}
7438
Eric Laurent794fde22016-03-11 09:50:45 -08007439bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7440 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007441 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007442}
7443
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007444status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007445 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007446 if (devices == nullptr) {
7447 return BAD_VALUE;
7448 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007449
Andy Hung6d23c0f2022-02-16 09:37:15 -08007450 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007451 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7452 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007453 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007454 for (const auto& device : curDevices) {
7455 devices->push_back(device->getDeviceTypeAddr());
7456 }
7457 return NO_ERROR;
7458}
7459
Eric Laurente0720872014-03-11 09:30:41 -07007460void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007461 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007462 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007463 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007464 updateDevicesAndOutputs();
7465 break;
7466 default:
7467 break;
7468 }
7469}
7470
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007471uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007472
7473 // skip beacon mute management if a dedicated TTS output is available
7474 if (mTtsOutputAvailable) {
7475 return 0;
7476 }
7477
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007478 switch(event) {
7479 case STARTING_OUTPUT:
7480 mBeaconMuteRefCount++;
7481 break;
7482 case STOPPING_OUTPUT:
7483 if (mBeaconMuteRefCount > 0) {
7484 mBeaconMuteRefCount--;
7485 }
7486 break;
7487 case STARTING_BEACON:
7488 mBeaconPlayingRefCount++;
7489 break;
7490 case STOPPING_BEACON:
7491 if (mBeaconPlayingRefCount > 0) {
7492 mBeaconPlayingRefCount--;
7493 }
7494 break;
7495 }
7496
7497 if (mBeaconMuteRefCount > 0) {
7498 // any playback causes beacon to be muted
7499 return setBeaconMute(true);
7500 } else {
7501 // no other playback: unmute when beacon starts playing, mute when it stops
7502 return setBeaconMute(mBeaconPlayingRefCount == 0);
7503 }
7504}
7505
7506uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7507 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7508 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7509 // keep track of muted state to avoid repeating mute/unmute operations
7510 if (mBeaconMuted != mute) {
7511 // mute/unmute AUDIO_STREAM_TTS on all outputs
7512 ALOGV("\t muting %d", mute);
7513 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007514 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7515 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7516 ALOGV("\t no tts volume source available");
7517 return 0;
7518 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007519 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007520 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007521 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007522 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007523 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007524 maxLatency = latency;
7525 }
7526 }
7527 mBeaconMuted = mute;
7528 return maxLatency;
7529 }
7530 return 0;
7531}
7532
Eric Laurente0720872014-03-11 09:30:41 -07007533void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007534{
François Gaffiec005e562018-11-06 15:04:49 +01007535 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007536 mPreviousOutputs = mOutputs;
7537}
7538
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007539uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007540 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007541 uint32_t delayMs)
7542{
7543 // mute/unmute strategies using an incompatible device combination
7544 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7545 // if unmuting, unmute only after the specified delay
7546 if (outputDesc->isDuplicated()) {
7547 return 0;
7548 }
7549
7550 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007551 DeviceVector devices = outputDesc->devices();
7552 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007553
François Gaffiec005e562018-11-06 15:04:49 +01007554 auto productStrategies = mEngine->getOrderedProductStrategies();
7555 for (const auto &productStrategy : productStrategies) {
7556 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7557 DeviceVector curDevices =
7558 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7559 curDevices = curDevices.filter(outputDesc->supportedDevices());
7560 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007561 bool doMute = false;
7562
François Gaffiec005e562018-11-06 15:04:49 +01007563 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007564 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007565 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7566 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007567 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007568 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007569 }
Eric Laurent99401132014-05-07 19:48:15 -07007570 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007571 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007572 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007573 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007574 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007575 continue;
7576 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307577 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007578 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7579 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7580 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007581 if (mute) {
7582 // FIXME: should not need to double latency if volume could be applied
7583 // immediately by the audioflinger mixer. We must account for the delay
7584 // between now and the next time the audioflinger thread for this output
7585 // will process a buffer (which corresponds to one buffer size,
7586 // usually 1/2 or 1/4 of the latency).
7587 if (muteWaitMs < desc->latency() * 2) {
7588 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007589 }
7590 }
7591 }
7592 }
7593 }
7594 }
7595
Eric Laurent99401132014-05-07 19:48:15 -07007596 // temporary mute output if device selection changes to avoid volume bursts due to
7597 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007598 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007599 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007600
Eric Laurentdc462862016-07-19 12:29:53 -07007601 if (muteWaitMs < tempMuteWaitMs) {
7602 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007603 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007604
7605 // If recommended duration is defined, replace temporary mute duration to avoid
7606 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7607 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7608 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7609 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7610 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7611
François Gaffieaaac0fd2018-11-22 17:56:39 +01007612 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7613 // make sure that we do not start the temporary mute period too early in case of
7614 // delayed device change
7615 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7616 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007617 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007618 }
7619 }
7620
Eric Laurente552edb2014-03-10 17:42:56 -07007621 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7622 if (muteWaitMs > delayMs) {
7623 muteWaitMs -= delayMs;
7624 usleep(muteWaitMs * 1000);
7625 return muteWaitMs;
7626 }
7627 return 0;
7628}
7629
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307630uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7631 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007632 const DeviceVector &devices,
7633 bool force,
7634 int delayMs,
7635 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007636 bool requiresMuteCheck, bool requiresVolumeCheck,
7637 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007638{
jiabin3ff8d7d2022-12-13 06:27:44 +00007639 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307640 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7641 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7642 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007643 uint32_t muteWaitMs;
7644
7645 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307646 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007647 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307648 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007649 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007650 return muteWaitMs;
7651 }
Eric Laurente552edb2014-03-10 17:42:56 -07007652
7653 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007654 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007655 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007656 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007657
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307658 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7659 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007660
7661 if (!filteredDevices.isEmpty()) {
7662 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007663 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007664
7665 // if the outputs are not materially active, there is no need to mute.
7666 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007667 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007668 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307669 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7670 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007671 muteWaitMs = 0;
7672 }
Eric Laurente552edb2014-03-10 17:42:56 -07007673
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007674 bool outputRouted = outputDesc->isRouted();
7675
Eric Laurent79ea9582020-06-11 18:49:24 -07007676 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7677 // output profile or if new device is not supported AND previous device(s) is(are) still
7678 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007679 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307680 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7681 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007682 // restore previous device after evaluating strategy mute state
7683 outputDesc->setDevices(prevDevices);
7684 return muteWaitMs;
7685 }
7686
Eric Laurente552edb2014-03-10 17:42:56 -07007687 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007688 // the requested device is AUDIO_DEVICE_NONE
7689 // OR the requested device is the same as current device
7690 // AND force is not specified
7691 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007692 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007693 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307694 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7695 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7696 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007697 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307698 ALOGV("%s %s setting same device on routed output, force apply volumes",
7699 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007700 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7701 }
Eric Laurente552edb2014-03-10 17:42:56 -07007702 return muteWaitMs;
7703 }
7704
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307705 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7706 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007707
Eric Laurente552edb2014-03-10 17:42:56 -07007708 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007709 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007710 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007711 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007712 PatchBuilder patchBuilder;
7713 patchBuilder.addSource(outputDesc);
7714 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7715 for (const auto &filteredDevice : filteredDevices) {
7716 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007717 }
7718
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007719 // Add half reported latency to delayMs when muteWaitMs is null in order
7720 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007721 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7722 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7723 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007724 }
Eric Laurente552edb2014-03-10 17:42:56 -07007725
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007726 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7727 if (!skipMuteDelay) {
7728 // update stream volumes according to new device
7729 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7730 }
Eric Laurente552edb2014-03-10 17:42:56 -07007731
7732 return muteWaitMs;
7733}
7734
Eric Laurentc75307b2015-03-17 15:29:32 -07007735status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007736 int delayMs,
7737 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007738{
Eric Laurent6a94d692014-05-20 11:18:06 -07007739 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007740 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7741 return INVALID_OPERATION;
7742 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007743 if (patchHandle) {
7744 index = mAudioPatches.indexOfKey(*patchHandle);
7745 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007746 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007747 }
7748 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007749 return INVALID_OPERATION;
7750 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007751 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007752 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007753 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007754 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007755 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007756 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007757 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007758 return status;
7759}
7760
7761status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007762 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007763 bool force,
7764 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007765{
7766 status_t status = NO_ERROR;
7767
Eric Laurent1f2f2232014-06-02 12:01:23 -07007768 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007769 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7770 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007771
François Gaffie11d30102018-11-02 16:09:09 +01007772 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007773 PatchBuilder patchBuilder;
7774 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007775 // AUDIO_SOURCE_HOTWORD is for internal use only:
7776 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007777 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7778 auto result = usecase;
7779 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7780 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7781 }
7782 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007783 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007784 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007785 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007786 }
7787 }
7788 return status;
7789}
7790
Eric Laurent6a94d692014-05-20 11:18:06 -07007791status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7792 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007793{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007794 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007795 ssize_t index;
7796 if (patchHandle) {
7797 index = mAudioPatches.indexOfKey(*patchHandle);
7798 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007799 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007800 }
7801 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007802 return INVALID_OPERATION;
7803 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007804 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007805 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007806 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007807 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007808 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007809 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007810 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007811 return status;
7812}
7813
François Gaffie11d30102018-11-02 16:09:09 +01007814sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007815 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007816 audio_format_t& format,
7817 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007818 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007819{
7820 // Choose an input profile based on the requested capture parameters: select the first available
7821 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007822 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007823
Atneya Nair0f0a8032022-12-12 16:20:12 -08007824 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7825 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7826 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7827
7828 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007829
jiabin2fd710d2022-05-02 23:20:22 +00007830 for (;;) {
7831 sp<IOProfile> firstInexact = nullptr;
7832 uint32_t updatedSamplingRate = 0;
7833 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7834 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7835 for (const auto& hwModule : mHwModules) {
7836 for (const auto& profile : hwModule->getInputProfiles()) {
7837 // profile->log();
7838 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007839 if (profile->getCompatibilityScore(
7840 DeviceVector(device),
7841 samplingRate,
7842 &updatedSamplingRate,
7843 format,
7844 &updatedFormat,
7845 channelMask,
7846 &updatedChannelMask,
7847 // FIXME ugly cast
7848 (audio_output_flags_t) flags,
7849 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7850 samplingRate = updatedSamplingRate;
7851 format = updatedFormat;
7852 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007853 return profile;
7854 }
jiabin66acc432024-02-06 00:57:36 +00007855 if (firstInexact == nullptr
7856 && profile->getCompatibilityScore(
7857 DeviceVector(device),
7858 samplingRate,
7859 &updatedSamplingRate,
7860 format,
7861 &updatedFormat,
7862 channelMask,
7863 &updatedChannelMask,
7864 // FIXME ugly cast
7865 (audio_output_flags_t) flags,
7866 false /*exactMatchRequiredForInputFlags*/)
7867 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007868 firstInexact = profile;
7869 }
7870 }
7871 }
7872
7873 if (firstInexact != nullptr) {
7874 samplingRate = updatedSamplingRate;
7875 format = updatedFormat;
7876 channelMask = updatedChannelMask;
7877 return firstInexact;
7878 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7879 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7880 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7881 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7882 flags = AUDIO_INPUT_FLAG_NONE;
7883 } else { // fail
7884 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7885 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7886 samplingRate, format, channelMask, oriFlags);
7887 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007888 }
7889 }
jiabin2fd710d2022-05-02 23:20:22 +00007890
7891 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007892}
7893
François Gaffieaaac0fd2018-11-22 17:56:39 +01007894float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7895 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007896 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007897 const DeviceTypeSet& deviceTypes,
7898 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07007899{
jiabin9a3361e2019-10-01 09:38:30 -07007900 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007901
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007902 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
7903 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
7904
7905 if (!computeInternalInteraction) {
7906 return volumeDb;
7907 }
7908
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007909 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7910 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7911 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7912 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007913 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7914 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7915 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7916 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7917 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007918 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007919 mOutputs.isActive(ringVolumeSrc, 0)) {
7920 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007921 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
7922 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007924 }
7925
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007926 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007927 if ((volumeSource != callVolumeSrc && (isInCall() ||
7928 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007929 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007930 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7931 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007932 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7933 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7934 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007935 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007936 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007937 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007938 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007939 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
7940 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007941 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007942 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7943 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7944 // programmatically muted.
7945 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7946 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7947 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007948 bool exemptFromCapping =
7949 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7950 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007951 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7952 volumeSource, volumeDb);
7953 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007954 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7955 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7956 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007957 }
7958 }
Eric Laurente552edb2014-03-10 17:42:56 -07007959 // if a headset is connected, apply the following rules to ring tones and notifications
7960 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007961 // - always attenuate notifications volume by 6dB
7962 // - attenuate ring tones volume by 6dB unless music is not playing and
7963 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007964 // - if music is playing, always limit the volume to current music volume,
7965 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007966 if (!Intersection(deviceTypes,
7967 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7968 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007969 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7970 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007971 ((volumeSource == alarmVolumeSrc ||
7972 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007973 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7974 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7975 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007976 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7977 curves.canBeMuted()) {
7978
Eric Laurente552edb2014-03-10 17:42:56 -07007979 // when the phone is ringing we must consider that music could have been paused just before
7980 // by the music application and behave as if music was active if the last music track was
7981 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007982 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7983 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007984 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007985 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007986 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7987 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007988 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007989 float musicVolDb = computeVolume(musicCurves,
7990 musicVolumeSrc,
7991 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007992 musicDevice,
7993 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007994 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7995 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7996 if (volumeDb > minVolDb) {
7997 volumeDb = minVolDb;
7998 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007999 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008000 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8001 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8002 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008003 // on A2DP, also ensure notification volume is not too low compared to media when
8004 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01008005 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008006 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008007 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8008 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008009 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8010 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008011 }
8012 }
jiabin9a3361e2019-10-01 09:38:30 -07008013 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008014 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008015 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008016 }
8017 }
8018
François Gaffie43c73442018-11-08 08:21:55 +01008019 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008020}
8021
Eric Laurent3839bc02018-07-10 18:33:34 -07008022int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008023 VolumeSource fromVolumeSource,
8024 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008025{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008026 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008027 return srcIndex;
8028 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008029 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8030 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008031 float minSrc = (float)srcCurves.getVolumeIndexMin();
8032 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8033 float minDst = (float)dstCurves.getVolumeIndexMin();
8034 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008035
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008036 // preserve mute request or correct range
8037 if (srcIndex < minSrc) {
8038 if (srcIndex == 0) {
8039 return 0;
8040 }
8041 srcIndex = minSrc;
8042 } else if (srcIndex > maxSrc) {
8043 srcIndex = maxSrc;
8044 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008045 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8046}
8047
François Gaffieaaac0fd2018-11-22 17:56:39 +01008048status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8049 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008050 int index,
8051 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008052 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008053 int delayMs,
8054 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008055{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008056 // do not change actual attributes volume if the attributes is muted
8057 if (outputDesc->isMuted(volumeSource)) {
8058 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8059 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008060 return NO_ERROR;
8061 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008062
Eric Laurentae6e88c2024-01-10 14:42:57 +01008063 bool isVoiceVolSrc;
8064 bool isBtScoVolSrc;
8065 if (!isVolumeConsistentForCalls(
8066 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008067 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008068 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008069 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008070 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008071
jiabin9a3361e2019-10-01 09:38:30 -07008072 if (deviceTypes.empty()) {
8073 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008074 index = curves.getVolumeIndex(deviceTypes);
8075 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
8076 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008077 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008078
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008079 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8080 ALOGE("invalid volume index range");
8081 return BAD_VALUE;
8082 }
8083
jiabin9a3361e2019-10-01 09:38:30 -07008084 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8085 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008086 // Force VoIP volume to max for bluetooth SCO device except if muted
8087 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008088 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008089 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008090 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008091 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008092 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8093 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008094
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008095 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008096 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008097 }
Eric Laurente552edb2014-03-10 17:42:56 -07008098 return NO_ERROR;
8099}
8100
Eric Laurentae6e88c2024-01-10 14:42:57 +01008101void AudioPolicyManager::setVoiceVolume(
8102 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8103 float voiceVolume;
8104 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8105 // by the headset
8106 if (isVoiceVolSrc) {
8107 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8108 } else {
8109 voiceVolume = index == 0 ? 0.0 : 1.0;
8110 }
8111 if (voiceVolume != mLastVoiceVolume) {
8112 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8113 mLastVoiceVolume = voiceVolume;
8114 }
8115}
8116
8117bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8118 const DeviceTypeSet& deviceTypes,
8119 bool& isVoiceVolSrc,
8120 bool& isBtScoVolSrc,
8121 const char* caller) {
8122 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8123 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8124 const bool isScoRequested = isScoRequestedForComm();
8125 const bool isHAUsed = isHearingAidUsedForComm();
8126
8127 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8128 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8129
8130 if ((callVolSrc != btScoVolSrc) &&
8131 ((isVoiceVolSrc && isScoRequested) ||
8132 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8133 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8134 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8135 volumeSource, isScoRequested ? " " : " not ");
8136 return false;
8137 }
8138 return true;
8139}
8140
Eric Laurentc75307b2015-03-17 15:29:32 -07008141void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008142 const DeviceTypeSet& deviceTypes,
8143 int delayMs,
8144 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008145{
jiabincd510522020-01-22 09:40:55 -08008146 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008147 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8148 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8149 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008150 curves.getVolumeIndex(deviceTypes),
8151 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008152 }
8153}
8154
François Gaffiec005e562018-11-06 15:04:49 +01008155void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8156 bool on,
8157 const sp<AudioOutputDescriptor>& outputDesc,
8158 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008159 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008160{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008161 std::vector<VolumeSource> sourcesToMute;
8162 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8163 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8164 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008165 VolumeSource source = toVolumeSource(attributes, false);
8166 if ((source != VOLUME_SOURCE_NONE) &&
8167 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8168 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008169 sourcesToMute.push_back(source);
8170 }
Eric Laurente552edb2014-03-10 17:42:56 -07008171 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008172 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008173 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008174 }
8175
Eric Laurente552edb2014-03-10 17:42:56 -07008176}
8177
François Gaffieaaac0fd2018-11-22 17:56:39 +01008178void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8179 bool on,
8180 const sp<AudioOutputDescriptor>& outputDesc,
8181 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008182 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008183{
jiabin9a3361e2019-10-01 09:38:30 -07008184 if (deviceTypes.empty()) {
8185 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008186 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008187 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008188 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008189 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008190 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008191 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008192 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8193 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008194 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008195 }
8196 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008197 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8198 // ignored
8199 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008200 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008201 if (!outputDesc->isMuted(volumeSource)) {
8202 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008203 return;
8204 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008205 if (outputDesc->decMuteCount(volumeSource) == 0) {
8206 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008207 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008208 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008209 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008210 delayMs);
8211 }
8212 }
8213}
8214
François Gaffie53615e22015-03-19 09:24:12 +01008215bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8216{
François Gaffiec005e562018-11-06 15:04:49 +01008217 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008218 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8219 return true;
8220 }
8221
8222 // has known usage?
8223 switch (paa->usage) {
8224 case AUDIO_USAGE_UNKNOWN:
8225 case AUDIO_USAGE_MEDIA:
8226 case AUDIO_USAGE_VOICE_COMMUNICATION:
8227 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8228 case AUDIO_USAGE_ALARM:
8229 case AUDIO_USAGE_NOTIFICATION:
8230 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8231 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8232 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8233 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8234 case AUDIO_USAGE_NOTIFICATION_EVENT:
8235 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8236 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8237 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8238 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008239 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008240 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008241 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008242 case AUDIO_USAGE_EMERGENCY:
8243 case AUDIO_USAGE_SAFETY:
8244 case AUDIO_USAGE_VEHICLE_STATUS:
8245 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008246 break;
8247 default:
8248 return false;
8249 }
8250 return true;
8251}
8252
François Gaffie2110e042015-03-24 08:41:51 +01008253audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8254{
8255 return mEngine->getForceUse(usage);
8256}
8257
Eric Laurent96d1dda2022-03-14 17:14:19 +01008258bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008259 return isStateInCall(mEngine->getPhoneState());
8260}
8261
Eric Laurent96d1dda2022-03-14 17:14:19 +01008262bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008263 return is_state_in_call(state);
8264}
8265
Eric Laurentf9cccec2022-11-16 19:12:00 +01008266bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008267 audio_mode_t mode = mEngine->getPhoneState();
8268 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008269 || (mode == AUDIO_MODE_CALL_SCREEN)
8270 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008271}
8272
Eric Laurentf9cccec2022-11-16 19:12:00 +01008273bool AudioPolicyManager::isInCallOrScreening() const {
8274 audio_mode_t mode = mEngine->getPhoneState();
8275 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8276}
8277
Eric Laurentd60560a2015-04-10 11:31:20 -07008278void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8279{
8280 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008281 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008282 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008283 sourceDesc->sinkDevice()->equals(deviceDesc))
8284 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008285 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008286 }
8287 }
8288
8289 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8290 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8291 bool release = false;
8292 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8293 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8294 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8295 source->ext.device.type == deviceDesc->type()) {
8296 release = true;
8297 }
8298 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008299 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008300 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8301 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8302 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008303 sink->ext.device.type == deviceDesc->type() &&
8304 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8305 || strncmp(sink->ext.device.address, address,
8306 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008307 release = true;
8308 }
8309 }
8310 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008311 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8312 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008313 }
8314 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008315
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008316 mInputs.clearSessionRoutesForDevice(deviceDesc);
8317
Francois Gaffie716e1432019-01-14 16:58:59 +01008318 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008319}
8320
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008321void AudioPolicyManager::modifySurroundFormats(
8322 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008323 std::unordered_set<audio_format_t> enforcedSurround(
8324 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008325 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008326 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008327 allSurround.insert(pair.first);
8328 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8329 }
Phil Burk09bc4612016-02-24 15:58:15 -08008330
8331 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8332 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008333 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008334 // This is the resulting set of formats depending on the surround mode:
8335 // 'all surround' = allSurround
8336 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8337 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8338 // 'manual surround' = mManualSurroundFormats
8339 // AUTO: formats v 'enforced surround'
8340 // ALWAYS: formats v 'all surround' v 'enforced surround'
8341 // NEVER: formats ^ 'non-surround'
8342 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008343
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008344 std::unordered_set<audio_format_t> formatSet;
8345 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8346 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008347 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008348 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008349 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008350 formatSet.insert(*formatIter);
8351 }
8352 }
8353 } else {
8354 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8355 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008356 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008357
jiabin81772902018-04-02 17:52:27 -07008358 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008359 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008360 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8361 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8362 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008363 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008364 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8365 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8366 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008367 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008368 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008369 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008370 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008371 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008372 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008373}
8374
jiabin06e4bab2019-07-29 10:13:34 -07008375void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8376 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008377 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8378 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8379
8380 // If NEVER, then remove support for channelMasks > stereo.
8381 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008382 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8383 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008384 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008385 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008386 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008387 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008388 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008389 }
8390 }
jiabin81772902018-04-02 17:52:27 -07008391 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8392 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8393 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008394 bool supports5dot1 = false;
8395 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008396 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008397 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8398 supports5dot1 = true;
8399 break;
8400 }
8401 }
8402 // If not then add 5.1 support.
8403 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008404 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008405 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008406 }
Phil Burk09bc4612016-02-24 15:58:15 -08008407 }
8408}
8409
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008410void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008411 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008412 const sp<IOProfile>& profile) {
8413 if (!profile->hasDynamicAudioProfile()) {
8414 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008415 }
François Gaffie112b0af2015-11-19 16:13:25 +01008416
jiabin12537fc2023-10-12 17:56:08 +00008417 audio_port_v7 devicePort;
8418 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008419
jiabin12537fc2023-10-12 17:56:08 +00008420 audio_port_v7 mixPort;
8421 profile->toAudioPort(&mixPort);
8422 mixPort.ext.mix.handle = ioHandle;
8423
8424 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8425 if (status != NO_ERROR) {
8426 ALOGE("%s failed to query the attributes of the mix port", __func__);
8427 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008428 }
jiabin12537fc2023-10-12 17:56:08 +00008429
8430 std::set<audio_format_t> supportedFormats;
8431 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8432 supportedFormats.insert(mixPort.audio_profiles[i].format);
8433 }
8434 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8435 mReportedFormatsMap[devDesc] = formats;
8436
8437 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8438 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8439 modifySurroundFormats(devDesc, &formats);
8440 size_t modifiedNumProfiles = 0;
8441 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8442 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8443 formats.end()) {
8444 // Skip the format that is not present after modifying surround formats.
8445 continue;
8446 }
8447 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8448 sizeof(struct audio_profile));
8449 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8450 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8451 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8452 modifySurroundChannelMasks(&channels);
8453 std::copy(channels.begin(), channels.end(),
8454 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8455 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8456 }
8457 mixPort.num_audio_profiles = modifiedNumProfiles;
8458 }
8459 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008460}
Eric Laurentd60560a2015-04-10 11:31:20 -07008461
Mikhail Naganovdc769682018-05-04 15:34:08 -07008462status_t AudioPolicyManager::installPatch(const char *caller,
8463 audio_patch_handle_t *patchHandle,
8464 AudioIODescriptorInterface *ioDescriptor,
8465 const struct audio_patch *patch,
8466 int delayMs)
8467{
8468 ssize_t index = mAudioPatches.indexOfKey(
8469 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8470 *patchHandle : ioDescriptor->getPatchHandle());
8471 sp<AudioPatch> patchDesc;
8472 status_t status = installPatch(
8473 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8474 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008475 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008476 }
8477 return status;
8478}
8479
8480status_t AudioPolicyManager::installPatch(const char *caller,
8481 ssize_t index,
8482 audio_patch_handle_t *patchHandle,
8483 const struct audio_patch *patch,
8484 int delayMs,
8485 uid_t uid,
8486 sp<AudioPatch> *patchDescPtr)
8487{
8488 sp<AudioPatch> patchDesc;
8489 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8490 if (index >= 0) {
8491 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008492 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008493 }
8494
8495 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8496 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8497 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8498 if (status == NO_ERROR) {
8499 if (index < 0) {
8500 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008501 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008502 } else {
8503 patchDesc->mPatch = *patch;
8504 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008505 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008506 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008507 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008508 }
8509 nextAudioPortGeneration();
8510 mpClientInterface->onAudioPatchListUpdate();
8511 }
8512 if (patchDescPtr) *patchDescPtr = patchDesc;
8513 return status;
8514}
8515
jiabinbce0c1d2020-10-05 11:20:18 -07008516bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8517{
8518 const TrackClientVector activeClients = output->getActiveClients();
8519 if (activeClients.empty()) {
8520 return true;
8521 }
8522 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8523 if (index < 0) {
8524 ALOGE("%s, no audio patch found while there are active clients on output %d",
8525 __func__, output->getId());
8526 return false;
8527 }
8528 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8529 DeviceVector routedDevices;
8530 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8531 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8532 patchDesc->mPatch.sinks[i].id);
8533 if (device == nullptr) {
8534 ALOGE("%s, no audio device found with id(%d)",
8535 __func__, patchDesc->mPatch.sinks[i].id);
8536 return false;
8537 }
8538 routedDevices.add(device);
8539 }
8540 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008541 if (client->isInvalid()) {
8542 // No need to take care about invalidated clients.
8543 continue;
8544 }
jiabinbce0c1d2020-10-05 11:20:18 -07008545 sp<DeviceDescriptor> preferredDevice =
8546 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8547 if (mEngine->getOutputDevicesForAttributes(
8548 client->attributes(), preferredDevice, false) == routedDevices) {
8549 return false;
8550 }
8551 }
8552 return true;
8553}
8554
8555sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008556 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008557 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8558 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008559{
8560 for (const auto& device : devices) {
8561 // TODO: This should be checking if the profile supports the device combo.
8562 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008563 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8564 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008565 return nullptr;
8566 }
8567 }
8568 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8569 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008570 status_t status = desc->open(halConfig, mixerConfig, devices,
8571 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008572 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008573 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008574 return nullptr;
8575 }
jiabin14b50cc2023-12-13 19:01:52 +00008576 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8577 auto portConfig = desc->getConfig();
8578 for (const auto& device : devices) {
8579 device->setPreferredConfig(&portConfig);
8580 }
8581 }
jiabinbce0c1d2020-10-05 11:20:18 -07008582
8583 // Here is where the out_set_parameters() for card & device gets called
8584 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8585 const audio_devices_t deviceType = device->type();
8586 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008587 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008588 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8589 mpClientInterface->setParameters(output, String8(param));
8590 free(param);
8591 }
jiabin12537fc2023-10-12 17:56:08 +00008592 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008593 if (!profile->hasValidAudioProfile()) {
8594 ALOGW("%s() missing param", __func__);
8595 desc->close();
8596 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008597 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8598 // Reopen the output with the best audio profile picked by APM when the profile supports
8599 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008600 desc->close();
8601 output = AUDIO_IO_HANDLE_NONE;
8602 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8603 profile->pickAudioProfile(
8604 config.sample_rate, config.channel_mask, config.format);
8605 config.offload_info.sample_rate = config.sample_rate;
8606 config.offload_info.channel_mask = config.channel_mask;
8607 config.offload_info.format = config.format;
8608
jiabina84c3d32022-12-02 18:59:55 +00008609 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008610 if (status != NO_ERROR) {
8611 return nullptr;
8612 }
8613 }
8614
8615 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008616 setOutputDevices(__func__, desc,
8617 devices,
8618 true,
8619 0,
8620 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008621 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8622 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8623
jiabinbce0c1d2020-10-05 11:20:18 -07008624 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8625 sp<AudioPolicyMix> policyMix;
8626 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8627 policyMix->setOutput(desc);
8628 desc->mPolicyMix = policyMix;
8629 } else {
8630 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008631 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008632 }
8633
baek.kim -61c20122022-07-27 10:05:32 +00008634 } else if (hasPrimaryOutput() && speaker != nullptr
8635 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008636 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8637 // no duplicated output for:
8638 // - direct outputs
8639 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008640 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008641 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8642
8643 //TODO: configure audio effect output stage here
8644
8645 // open a duplicating output thread for the new output and the primary output
8646 sp<SwAudioOutputDescriptor> dupOutputDesc =
8647 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8648 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8649 if (status == NO_ERROR) {
8650 // add duplicated output descriptor
8651 addOutput(duplicatedOutput, dupOutputDesc);
8652 } else {
8653 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8654 mPrimaryOutput->mIoHandle, output);
8655 desc->close();
8656 removeOutput(output);
8657 nextAudioPortGeneration();
8658 return nullptr;
8659 }
8660 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008661 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8662 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8663 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008664 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008665 }
jiabinbce0c1d2020-10-05 11:20:18 -07008666 return desc;
8667}
8668
jiabinf1c73972022-04-14 16:28:52 -07008669status_t AudioPolicyManager::getDevicesForAttributes(
8670 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8671 // Devices are determined in the following precedence:
8672 //
8673 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8674 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8675 //
8676 // If no such dynamic policy then
8677 // 2) Devices containing an active client using setPreferredDevice
8678 // with same strategy as the attributes.
8679 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8680 //
8681 // If no corresponding active client with setPreferredDevice then
8682 // 3) Devices associated with the strategy determined by the attributes
8683 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8684 //
8685 // See related getOutputForAttrInt().
8686
8687 // check dynamic policies but only for primary descriptors (secondary not used for audible
8688 // audio routing, only used for duplication for playback capture)
8689 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008690 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008691 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008692 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8693 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8694 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008695 if (status != OK) {
8696 return status;
8697 }
8698
8699 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8700 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8701 // as they are unaffected by device/stream volume
8702 // (per SwAudioOutputDescriptor::isFixedVolume()).
8703 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8704 ) {
8705 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8706 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8707 devices.add(deviceDesc);
8708 } else {
8709 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8710 // which selects setPreferredDevice if active. This means forVolume call
8711 // will take an active setPreferredDevice, if such exists.
8712
8713 devices = mEngine->getOutputDevicesForAttributes(
8714 attr, nullptr /* preferredDevice */, false /* fromCache */);
8715 }
8716
8717 if (forVolume) {
8718 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8719 // for single volume control in AudioService (such relationship should exist if
8720 // SPEAKER_SAFE is present).
8721 //
8722 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8723 DeviceVector speakerSafeDevices =
8724 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8725 if (!speakerSafeDevices.isEmpty()) {
8726 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8727 devices.remove(speakerSafeDevices);
8728 }
8729 }
8730
8731 return NO_ERROR;
8732}
8733
8734status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8735 AudioProfileVector& audioProfiles,
8736 uint32_t flags,
8737 bool isInput) {
8738 for (const auto& hwModule : mHwModules) {
8739 // the MSD module checks for different conditions
8740 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8741 continue;
8742 }
8743 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8744 : hwModule->getOutputProfiles();
8745 for (const auto& profile : ioProfiles) {
8746 if (!profile->areAllDevicesSupported(devices) ||
8747 !profile->isCompatibleProfileForFlags(
8748 flags, false /*exactMatchRequiredForInputFlags*/)) {
8749 continue;
8750 }
8751 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8752 }
8753 }
8754
8755 if (!isInput) {
8756 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8757 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8758 if (msdModule != nullptr) {
8759 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8760 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8761 for (const auto &profile: msdModule->getOutputProfiles()) {
8762 if (!profile->asAudioPort()->isDirectOutput()) {
8763 continue;
8764 }
8765 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8766 }
8767 } else {
8768 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8769 }
8770 }
8771 }
8772
8773 return NO_ERROR;
8774}
8775
jiabin3ff8d7d2022-12-13 06:27:44 +00008776sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8777 const audio_config_t *config,
8778 audio_output_flags_t flags,
8779 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008780 closeOutput(outputDesc->mIoHandle);
8781 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8782 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8783 if (preferredOutput == nullptr) {
8784 ALOGE("%s failed to reopen output device=%d, caller=%s",
8785 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008786 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008787 return preferredOutput;
8788}
8789
8790void AudioPolicyManager::reopenOutputsWithDevices(
8791 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8792 for (const auto& [output, devices] : outputsToReopen) {
8793 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8794 closeOutput(output);
8795 openOutputWithProfileAndDevice(desc->mProfile, devices);
8796 }
jiabina84c3d32022-12-02 18:59:55 +00008797}
8798
jiabinc44b3462022-12-08 12:52:31 -08008799PortHandleVector AudioPolicyManager::getClientsForStream(
8800 audio_stream_type_t streamType) const {
8801 PortHandleVector clients;
8802 for (size_t i = 0; i < mOutputs.size(); ++i) {
8803 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8804 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8805 }
8806 return clients;
8807}
8808
8809void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8810 PortHandleVector clients;
8811 for (auto stream : streams) {
8812 PortHandleVector clientsForStream = getClientsForStream(stream);
8813 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8814 }
8815 mpClientInterface->invalidateTracks(clients);
8816}
8817
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008818} // namespace android