blob: b251843f1e2185c99cc20a4f11ccd46348ae32f7 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
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 Naganov3754b642024-04-17 18:31:04 +0000132 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 Naganov3754b642024-04-17 18:31:04 +0000222
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 Wasilczyk5b054372023-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();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530377 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530393 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (mAvailableInputDevices.add(device) < 0) {
396 return NO_MEMORY;
397 }
398
François Gaffie44481e72016-04-20 07:49:57 +0200399 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
400 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700402 // Propagate device availability to Engine
403 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700406 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
407
Eric Laurent0dd51852019-04-19 18:18:58 -0700408 mAvailableInputDevices.remove(device);
409
jiabinc0048632023-04-27 22:04:31 +0000410 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100411
412 mHwModules.cleanUpForDevice(device);
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 return INVALID_OPERATION;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700418
419 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700421 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100422 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700423 return INVALID_OPERATION;
424 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
François Gaffie11d30102018-11-02 16:09:09 +0100426 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700427
jiabinc0048632023-04-27 22:04:31 +0000428 // Notify the HAL to prepare to disconnect device
429 broadcastDeviceConnectionState(
430 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700431
François Gaffie11d30102018-11-02 16:09:09 +0100432 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700433
434 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100435
jiabinc0048632023-04-27 22:04:31 +0000436 // Set Disconnect to HALs
437 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
438
Kriti Dangef6be8f2020-11-05 11:58:19 +0100439 // remove device from mReportedFormatsMap cache
440 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700441
442 // Propagate device availability to Engine
443 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700444 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700445
446 default:
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449 }
450
Eric Laurent0dd51852019-04-19 18:18:58 -0700451 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700452 // As the input device list can impact the output device selection, update
453 // getDeviceForStrategy() cache
454 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700455
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100456 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200457 // Reconnect Audio Source
458 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
459 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
460 checkAudioSourceForAttributes(attributes);
461 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100463 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700464 }
465
Eric Laurentb52c1522014-05-20 11:27:36 -0700466 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530467 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700469 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700470
François Gaffie11d30102018-11-02 16:09:09 +0100471 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700472 return BAD_VALUE;
473}
474
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100475status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
476 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800477 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000478 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
479 devDescr->setName(device_name);
480 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100481}
482
Eric Laurent736a1022019-03-27 18:28:46 -0700483void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
484 audio_policy_dev_state_t state) {
485
486 // the Engine does not have to know about remote submix devices used by dynamic audio policies
487 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
488 return;
489 }
490 mEngine->setDeviceConnectionState(device, state);
491}
492
493
Eric Laurente0720872014-03-11 09:30:41 -0700494audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100495 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700496{
Eric Laurent634b7142016-04-20 13:48:02 -0700497 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800498 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
499 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700500 (strlen(device_address) != 0)/*matchAddress*/);
501
502 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100503 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700504 device, device_address);
505 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
506 }
François Gaffie53615e22015-03-19 09:24:12 +0100507
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 DeviceVector *deviceVector;
509
Eric Laurente552edb2014-03-10 17:42:56 -0700510 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700511 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700512 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 deviceVector = &mAvailableInputDevices;
514 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100515 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700516 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700517 }
Eric Laurent634b7142016-04-20 13:48:02 -0700518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 return (deviceVector->getDevice(
520 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700521 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800522}
523
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
525 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 const char *device_name,
527 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
530 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800532 // connect/disconnect only 1 device at a time
533 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
534
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700536 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538 // Nothing to do: device is not connected
539 return NO_ERROR;
540 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800542
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 // configure codecs.
545 // Handle two specific cases by sending a set parameter to
546 // configure A2DP codecs. No need to toggle device state.
547 // Case 1: A2DP active device switches from primary to primary
548 // module
549 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700551 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
553 if (availablePrimaryOutputDevices().contains(devDesc) &&
554 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100555 bool isA2dp = audio_is_a2dp_out_device(device);
556 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
557 : String8(AudioParameter::keyReconfigLeSupported);
558 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100560 int isReconfigSupported;
561 repliedParameters.getInt(supportKey, isReconfigSupported);
562 if (isReconfigSupported) {
563 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
564 : String8(AudioParameter::keyReconfigLe);
565 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800566 param.add(key, String8("true"));
567 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
568 devDesc->setEncodedFormat(encodedFormat);
569 return NO_ERROR;
570 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700571 }
572 }
cnx421bd2dcc42020-07-11 14:58:44 +0800573 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
574 for (size_t i = 0; i < mOutputs.size(); i++) {
575 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
576 // mute media strategies and delay device switch by the largest
577 // This avoid sending the music tail into the earpiece or headset.
578 setStrategyMute(musicStrategy, true, desc);
579 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
580 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
581 nullptr, true /*fromCache*/).types());
582 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 // Toggle the device state: UNAVAILABLE -> AVAILABLE
584 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100585 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800586 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800587 device_address, device_name,
588 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800589 if (status != NO_ERROR) {
590 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
591 status);
592 return status;
593 }
594
595 status = setDeviceConnectionState(device,
596 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800597 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800598 if (status != NO_ERROR) {
599 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
600 status);
601 return status;
602 }
603
604 return NO_ERROR;
605}
606
Pattydd807582021-11-04 21:01:03 +0800607status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
608 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800609{
Pattydd807582021-11-04 21:01:03 +0800610 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800611 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800612 std::unordered_set<audio_format_t> formatSet;
613 sp<HwModule> primaryModule =
614 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700615 if (primaryModule == nullptr) {
616 ALOGE("%s() unable to get primary module", __func__);
617 return NO_INIT;
618 }
Pattydd807582021-11-04 21:01:03 +0800619
620 DeviceTypeSet audioDeviceSet;
621
622 switch(device) {
623 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
624 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
625 break;
626 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800627 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
628 break;
629 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
630 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800631 break;
632 default:
633 ALOGE("%s() device type 0x%08x not supported", __func__, device);
634 return BAD_VALUE;
635 }
636
jiabin9a3361e2019-10-01 09:38:30 -0700637 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800638 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800639 for (const auto& device : declaredDevices) {
640 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800641 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800642 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800643 return status;
644}
645
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100646DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
647{
648 DeviceVector rxSinkdevices{};
649 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
650 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
651 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
652 auto rxSinkDevice = rxSinkdevices.itemAt(0);
653 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
654 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
655 // retrieve Rx Source device descriptor
656 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
657 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
658
659 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
660 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
661 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
662 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
663 return DeviceVector(rxSinkDevice);
664 }
665 }
666 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
667 // the device returned is not necessarily reachable via this output
668 // (filter later by setOutputDevices())
669 return getNewOutputDevices(mPrimaryOutput, fromCache);
670}
671
672status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
673{
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
676 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
677 }
678 return INVALID_OPERATION;
679}
680
681status_t AudioPolicyManager::updateCallRoutingInternal(
682 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700683{
684 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100685 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700686 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700688 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100689 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700690 }
François Gaffie11d30102018-11-02 16:09:09 +0100691
Francois Gaffie716e1432019-01-14 16:58:59 +0100692 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100693 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200694
695 disconnectTelephonyAudioSource(mCallRxSourceClient);
696 disconnectTelephonyAudioSource(mCallTxSourceClient);
697
698 if (rxDevices.isEmpty()) {
699 ALOGW("%s() no selected output device", __func__);
700 return INVALID_OPERATION;
701 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000702 if (txSourceDevice == nullptr) {
703 ALOGE("%s() selected input device not available", __func__);
704 return INVALID_OPERATION;
705 }
François Gaffiec005e562018-11-06 15:04:49 +0100706
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100707 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100708 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709
François Gaffie9eb18552018-11-05 10:33:26 +0100710 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700711 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100712 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700713 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100714 // retrieve Rx Source and Tx Sink device descriptors
715 sp<DeviceDescriptor> rxSourceDevice =
716 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
717 String8(),
718 AUDIO_FORMAT_DEFAULT);
719 sp<DeviceDescriptor> txSinkDevice =
720 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
721 String8(),
722 AUDIO_FORMAT_DEFAULT);
723
724 // RX and TX Telephony device are declared by Primary Audio HAL
725 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
726 (telephonyRxModule->getHalVersionMajor() >= 3)) {
727 if (rxSourceDevice == 0 || txSinkDevice == 0) {
728 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100729 ALOGE("%s() no telephony Tx and/or RX device", __func__);
730 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100731 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100732 // createAudioPatchInternal now supports both HW / SW bridging
733 createRxPatch = true;
734 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100735 } else {
736 // If the RX device is on the primary HW module, then use legacy routing method for
737 // voice calls via setOutputDevice() on primary output.
738 // Otherwise, create two audio patches for TX and RX path.
739 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
740 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741 // If the TX device is also on the primary HW module, setOutputDevice() will take care
742 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100743 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
744 (txSinkDevice != 0);
745 }
746 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
747 // Otherwise, create two audio patches for TX and RX path.
748 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200749 if (!hasPrimaryOutput()) {
750 ALOGW("%s() no primary output available", __func__);
751 return INVALID_OPERATION;
752 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530753 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700754 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200755 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800756 // If the TX device is on the primary HW module but RX device is
757 // on other HW module, SinkMetaData of telephony input should handle it
758 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700759 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700760 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100761 // terminate active capture if on the same HW module as the call TX source device
762 // FIXME: would be better to refine to only inputs whose profile connects to the
763 // call TX device but this information is not in the audio patch and logic here must be
764 // symmetric to the one in startInput()
765 for (const auto& activeDesc : mInputs.getActiveInputs()) {
766 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
767 closeActiveClients(activeDesc);
768 }
769 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200770 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800771 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100772 if (waitMs != nullptr) {
773 *waitMs = muteWaitMs;
774 }
775 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800776}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777
Mikhail Naganov100f0122018-11-29 11:22:16 -0800778bool AudioPolicyManager::isDeviceOfModule(
779 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
780 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
781 if (module != 0) {
782 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
783 .indexOf(devDesc) != NAME_NOT_FOUND
784 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
785 .indexOf(devDesc) != NAME_NOT_FOUND;
786 }
787 return false;
788}
789
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200790void AudioPolicyManager::connectTelephonyRxAudioSource()
791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200793 const struct audio_port_config source = {
794 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
795 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
796 };
797 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100798
799 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
800 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
801 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
802 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 ALOGE_IF(mCallRxSourceClient == nullptr,
804 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805}
806
Francois Gaffie601801d2021-06-22 13:27:39 +0200807void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200808{
Francois Gaffie601801d2021-06-22 13:27:39 +0200809 if (clientDesc == nullptr) {
810 return;
811 }
812 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
813 "%s error stopping audio source", __func__);
814 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200815}
816
817void AudioPolicyManager::connectTelephonyTxAudioSource(
818 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
819 uint32_t delayMs)
820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200822 if (srcDevice == nullptr || sinkDevice == nullptr) {
823 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
824 return;
825 }
826 PatchBuilder patchBuilder;
827 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
828 ALOGV("%s between source %s and sink %s", __func__,
829 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200830 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200831 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
832
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200833 struct audio_port_config source = {};
834 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100835 mCallTxSourceClient = new SourceClientDescriptor(
836 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
837 mCommunnicationStrategy, toVolumeSource(aa), true);
838 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
839
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200840 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
841 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
843 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200844 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
845 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200846 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200847 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200848}
849
Eric Laurente0720872014-03-11 09:30:41 -0700850void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700851{
852 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100853 // store previous phone state for management of sonification strategy below
854 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100855 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100856
857 if (mEngine->setPhoneState(state) != NO_ERROR) {
858 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700859 return;
860 }
François Gaffie2110e042015-03-24 08:41:51 +0100861 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700862 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700863 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700864 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800865 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700866 }
867
François Gaffie2110e042015-03-24 08:41:51 +0100868 /**
869 * Switching to or from incall state or switching between telephony and VoIP lead to force
870 * routing command.
871 */
Eric Laurent74b71512019-11-06 17:21:57 -0800872 bool force = ((isStateInCall(oldState) != isStateInCall(state))
873 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700874
875 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700876 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700877
Eric Laurente552edb2014-03-10 17:42:56 -0700878 int delayMs = 0;
879 if (isStateInCall(state)) {
880 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100881 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
882 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700883 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700884 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700885 // mute media and sonification strategies and delay device switch by the largest
886 // latency of any output where either strategy is active.
887 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100888 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
889 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
890 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700891 (delayMs < (int)desc->latency()*2)) {
892 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
François Gaffiec005e562018-11-06 15:04:49 +0100894 setStrategyMute(musicStrategy, true, desc);
895 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
896 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
897 nullptr, true /*fromCache*/).types());
898 setStrategyMute(sonificationStrategy, true, desc);
899 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
900 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
901 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700902 }
903 }
904
François Gaffiedb1755b2023-09-01 11:50:35 +0200905 if (state == AUDIO_MODE_IN_CALL) {
906 (void)updateCallRouting(false /*fromCache*/, delayMs);
907 } else {
908 if (oldState == AUDIO_MODE_IN_CALL) {
909 disconnectTelephonyAudioSource(mCallRxSourceClient);
910 disconnectTelephonyAudioSource(mCallTxSourceClient);
911 }
912 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100913 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
914 // force routing command to audio hardware when ending call
915 // even if no device change is needed
916 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
917 rxDevices = mPrimaryOutput->devices();
918 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530919 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700920 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700921 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700922
jiabin3ff8d7d2022-12-13 06:27:44 +0000923 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700924 // reevaluate routing on all outputs in case tracks have been started during the call
925 for (size_t i = 0; i < mOutputs.size(); i++) {
926 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100927 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200928 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
929 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000930 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
931 // If the device is using preferred mixer attributes, the output need to reopen
932 // with default configuration when the new selected devices are different from
933 // current routing devices.
934 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
935 continue;
936 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530937 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200938 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700939 }
940 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000941 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700942
Eric Laurent96d1dda2022-03-14 17:14:19 +0100943 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
944
Eric Laurente552edb2014-03-10 17:42:56 -0700945 if (isStateInCall(state)) {
946 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700947 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800948 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700949 }
950
951 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100952 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
953 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700954}
955
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700956audio_mode_t AudioPolicyManager::getPhoneState() {
957 return mEngine->getPhoneState();
958}
959
Eric Laurente0720872014-03-11 09:30:41 -0700960void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100961 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700962{
François Gaffie2110e042015-03-24 08:41:51 +0100963 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700964 if (config == mEngine->getForceUse(usage)) {
965 return;
966 }
Eric Laurente552edb2014-03-10 17:42:56 -0700967
François Gaffie2110e042015-03-24 08:41:51 +0100968 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
969 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
970 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700971 }
François Gaffie2110e042015-03-24 08:41:51 +0100972 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
973 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
974 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700977 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800978
Eric Laurent22fcda22019-05-17 16:28:47 -0700979 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
980 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800981 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700982 }
983
Eric Laurentdc462862016-07-19 12:29:53 -0700984 //FIXME: workaround for truncated touch sounds
985 // to be removed when the problem is handled by system UI
986 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700987 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
988 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
989 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700990
991 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100992 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700993}
994
Eric Laurente0720872014-03-11 09:30:41 -0700995void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700996{
997 ALOGV("setSystemProperty() property %s, value %s", property, value);
998}
999
Dorin Drimusecc9f422022-03-09 17:57:40 +01001000// Find an MSD output profile compatible with the parameters passed.
1001// When "directOnly" is set, restrict search to profiles for direct outputs.
1002sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1003 const DeviceVector& devices,
1004 uint32_t samplingRate,
1005 audio_format_t format,
1006 audio_channel_mask_t channelMask,
1007 audio_output_flags_t flags,
1008 bool directOnly)
1009{
1010 flags = getRelevantFlags(flags, directOnly);
1011
1012 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1013 if (msdModule != nullptr) {
1014 // for the msd module check if there are patches to the output devices
1015 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1016 HwModuleCollection modules;
1017 modules.add(msdModule);
1018 return searchCompatibleProfileHwModules(
1019 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1020 flags, directOnly);
1021 }
1022 }
1023 return nullptr;
1024}
1025
Michael Chana94fbb22018-04-24 14:31:19 +10001026// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1027// search to profiles for direct outputs.
1028sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001029 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001030 uint32_t samplingRate,
1031 audio_format_t format,
1032 audio_channel_mask_t channelMask,
1033 audio_output_flags_t flags,
1034 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001035{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 flags = getRelevantFlags(flags, directOnly);
1037
1038 return searchCompatibleProfileHwModules(
1039 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1040}
1041
1042audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1043 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001044 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 // only retain flags that will drive the direct output profile selection
1046 // if explicitly requested
1047 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001048 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001049 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1050 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001051 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001052 return flags;
1053}
Eric Laurent861a6282015-05-18 15:40:16 -07001054
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1056 const HwModuleCollection& hwModules,
1057 const DeviceVector& devices,
1058 uint32_t samplingRate,
1059 audio_format_t format,
1060 audio_channel_mask_t channelMask,
1061 audio_output_flags_t flags,
1062 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001063 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001064 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001065 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001066 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 samplingRate, NULL /*updatedSamplingRate*/,
1068 format, NULL /*updatedFormat*/,
1069 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001070 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 continue;
1072 }
1073 // reject profiles not corresponding to a device currently available
1074 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1075 continue;
1076 }
1077 // reject profiles if connected device does not support codec
1078 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1079 continue;
1080 }
1081 if (!directOnly) {
1082 return curProfile;
1083 }
1084
1085 // when searching for direct outputs, if several profiles are compatible, give priority
1086 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001087 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001088 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001089 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001090 }
1091 profile = curProfile;
1092 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1093 break;
1094 }
Eric Laurente552edb2014-03-10 17:42:56 -07001095 }
1096 }
Eric Laurent861a6282015-05-18 15:40:16 -07001097 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001098}
1099
Eric Laurentfa0f6742021-08-17 18:39:44 +02001100sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001101 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001102{
1103 for (const auto& hwModule : mHwModules) {
1104 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001105 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 continue;
1107 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001108 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001109 // reject profiles not corresponding to a device currently available
1110 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1111 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1112 continue;
1113 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1115 != devices.size()) {
1116 continue;
1117 }
1118 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001119 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1120 return curProfile;
1121 }
1122 }
1123 return nullptr;
1124}
1125
Eric Laurentf4e63452017-11-06 19:31:46 +00001126audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001127{
François Gaffiec005e562018-11-06 15:04:49 +01001128 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001129
1130 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1131 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1132 // format, flags, etc. This may result in some discrepancy for functions that utilize
1133 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1134 // and AudioSystem::getOutputSamplingRate().
1135
François Gaffie11d30102018-11-02 16:09:09 +01001136 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001137 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1138 if (stream == AUDIO_STREAM_MUSIC &&
1139 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1140 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1141 }
1142 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001143
François Gaffie11d30102018-11-02 16:09:09 +01001144 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1145 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001146 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001147}
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1150 const audio_attributes_t *srcAttr,
1151 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001152{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001153 if (srcAttr != NULL) {
1154 if (!isValidAttributes(srcAttr)) {
1155 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1156 __func__,
1157 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1158 srcAttr->tags);
1159 return BAD_VALUE;
1160 }
1161 *dstAttr = *srcAttr;
1162 } else {
1163 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1164 ALOGE("%s: invalid stream type", __func__);
1165 return BAD_VALUE;
1166 }
François Gaffiec005e562018-11-06 15:04:49 +01001167 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001169
1170 // Only honor audibility enforced when required. The client will be
1171 // forced to reconnect if the forced usage changes.
1172 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001173 dstAttr->flags = static_cast<audio_flags_mask_t>(
1174 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001175 }
1176
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001177 return NO_ERROR;
1178}
1179
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180status_t AudioPolicyManager::getOutputForAttrInt(
1181 audio_attributes_t *resultAttr,
1182 audio_io_handle_t *output,
1183 audio_session_t session,
1184 const audio_attributes_t *attr,
1185 audio_stream_type_t *stream,
1186 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001187 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188 audio_output_flags_t *flags,
1189 audio_port_handle_t *selectedDeviceId,
1190 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001191 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001192 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001193 bool *isSpatialized,
1194 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001195{
François Gaffiec005e562018-11-06 15:04:49 +01001196 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001197 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001198 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001199 const sp<DeviceDescriptor> requestedDevice =
1200 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1201
Eric Laurent8a1095a2019-11-08 14:44:16 -08001202 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001203 *isSpatialized = false;
1204
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001205 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1206 if (status != NO_ERROR) {
1207 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001208 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001209 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001210 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001211 }
François Gaffiec005e562018-11-06 15:04:49 +01001212 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001213
François Gaffiec005e562018-11-06 15:04:49 +01001214 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1215 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001216
Oscar Azucena873d10f2023-01-12 18:34:42 -08001217 bool usePrimaryOutputFromPolicyMixes = false;
1218
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1220 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1221 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001223 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1224 .channel_mask = config->channel_mask,
1225 .format = config->format,
1226 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001227 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001228 mAvailableOutputDevices, requestedDevice, primaryMix,
1229 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001230 if (status != OK) {
1231 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001232 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001233
Kevin Rocard153f92d2018-12-18 18:33:28 -08001234 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001235 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1236 && !audio_is_linear_pcm(config->format)) {
1237 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001238 return BAD_VALUE;
1239 }
1240 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001241 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001242 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1243 primaryMix->mDeviceAddress,
1244 AUDIO_FORMAT_DEFAULT);
1245 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001247 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1248 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001249 // if a direct output can be opened to deliver the track's multi-channel content to the
1250 // output rather than being downmixed by the primary output, then use this direct
1251 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1252 // mix.
1253 bool tryDirectForChannelMask = policyDesc != nullptr
1254 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1255 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001256 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001257 audio_io_handle_t newOutput;
1258 status = openDirectOutput(
1259 *stream, session, config,
1260 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001261 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001262 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001263 policyDesc = mOutputs.valueFor(newOutput);
1264 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001265 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001266 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001267 policyDesc = nullptr;
1268 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 }
1270 if (policyDesc != nullptr) {
1271 policyDesc->mPolicyMix = primaryMix;
1272 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001273 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1274 : AUDIO_PORT_HANDLE_NONE;
1275 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1276 // Remove direct flag as it is not on a direct output.
1277 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1278 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001279
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001280 ALOGV("getOutputForAttr() returns output %d", *output);
1281 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1282 *outputType = API_OUT_MIX_PLAYBACK;
1283 } else {
1284 *outputType = API_OUTPUT_LEGACY;
1285 }
1286 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001287 } else {
1288 if (policyMixDevice != nullptr) {
1289 ALOGE("%s, try to use primary mix but no output found", __func__);
1290 return INVALID_OPERATION;
1291 }
1292 // Fallback to default engine selection as the selected primary mix device is not
1293 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001294 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001295 }
François Gaffiec005e562018-11-06 15:04:49 +01001296 // Virtual sources must always be dynamicaly or explicitly routed
1297 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1298 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1299 return BAD_VALUE;
1300 }
1301 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1302 // in order to let the choice of the order to future vendor engine
1303 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001304
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001305 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001306 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001307 }
1308
Nadav Barb2f18162018-07-18 13:01:53 +03001309 // Set incall music only if device was explicitly set, and fallback to the device which is
1310 // chosen by the engine if not.
1311 // FIXME: provide a more generic approach which is not device specific and move this back
1312 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001313 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001314 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001315 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001316 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001317 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001318 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001319 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001320 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001321 }
1322 }
1323
François Gaffiec005e562018-11-06 15:04:49 +01001324 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1325 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1326 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001327
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001328 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001329 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001330 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001331 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001332 ALOGV("%s() Using MSD devices %s instead of devices %s",
1333 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001334 } else {
1335 *output = AUDIO_IO_HANDLE_NONE;
1336 }
1337 }
1338 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001339 sp<PreferredMixerAttributesInfo> info = nullptr;
1340 if (outputDevices.size() == 1) {
1341 info = getPreferredMixerAttributesInfo(
1342 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001343 mEngine->getProductStrategyForAttributes(*resultAttr),
1344 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001345 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1346 // and it is currently active.
1347 if (info != nullptr && info->getUid() != uid &&
1348 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1349 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001350 info = nullptr;
1351 }
1352 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001353 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001354 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001355 // The client will be active if the client is currently preferred mixer owner and the
1356 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001357 *isBitPerfect = (info != nullptr
1358 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001359 && info->getUid() == uid
1360 && *output != AUDIO_IO_HANDLE_NONE
1361 // When bit-perfect output is selected for the preferred mixer attributes owner,
1362 // only need to consider the config matches.
1363 && mOutputs.valueFor(*output)->isConfigurationMatched(
1364 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001366 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001367 AudioProfileVector profiles;
1368 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1369 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001370 const auto channels = profiles[0]->getChannels();
1371 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1372 config->channel_mask = *channels.begin();
1373 }
1374 const auto sampleRates = profiles[0]->getSampleRates();
1375 if (!sampleRates.empty() &&
1376 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1377 config->sample_rate = *sampleRates.begin();
1378 }
jiabinf1c73972022-04-14 16:28:52 -07001379 config->format = profiles[0]->getFormat();
1380 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001381 return INVALID_OPERATION;
1382 }
Paul McLeanaa981192015-03-21 09:55:15 -07001383
François Gaffiec005e562018-11-06 15:04:49 +01001384 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001385 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001386 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001387 *selectedDeviceId = outputDevice->getId();
1388 break;
1389 }
1390 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001391
Eric Laurent8a1095a2019-11-08 14:44:16 -08001392 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1393 *outputType = API_OUTPUT_TELEPHONY_TX;
1394 } else {
1395 *outputType = API_OUTPUT_LEGACY;
1396 }
1397
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001398 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1399
1400 return NO_ERROR;
1401}
1402
1403status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1404 audio_io_handle_t *output,
1405 audio_session_t session,
1406 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001407 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001408 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001409 audio_output_flags_t *flags,
1410 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001411 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001412 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001413 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001414 bool *isSpatialized,
1415 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416{
1417 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1418 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1419 return INVALID_OPERATION;
1420 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001421 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001422 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001423 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001424 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001425 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001426 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001427 const sp<DeviceDescriptor> requestedDevice =
1428 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1429
1430 // Prevent from storing invalid requested device id in clients
1431 const audio_port_handle_t sanitizedRequestedPortId =
1432 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1433 *selectedDeviceId = sanitizedRequestedPortId;
1434
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001435 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001436 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001437 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1438 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001439 if (status != NO_ERROR) {
1440 return status;
1441 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001442 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001443 if (secondaryOutputs != nullptr) {
1444 for (auto &secondaryMix : secondaryMixes) {
1445 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1446 if (outputDesc != nullptr &&
1447 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1448 secondaryOutputs->push_back(outputDesc->mIoHandle);
1449 weakSecondaryOutputDescs.push_back(outputDesc);
1450 }
1451 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001452 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453
Eric Laurent8fc147b2018-07-22 19:13:55 -07001454 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001455 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001456 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001457 };
jiabin4ef93452019-09-10 14:29:54 -07001458 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001459
Eric Laurentc209fe42020-06-05 18:11:23 -07001460 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001461 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001462 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001463 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001464 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001465 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001466 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001467 std::move(weakSecondaryOutputDescs),
1468 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001469 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001470
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001471 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1472 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001473
Eric Laurente83b55d2014-11-14 10:06:21 -08001474 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001475}
1476
Eric Laurentc529cf62020-04-17 18:19:10 -07001477status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1478 audio_session_t session,
1479 const audio_config_t *config,
1480 audio_output_flags_t flags,
1481 const DeviceVector &devices,
1482 audio_io_handle_t *output) {
1483
1484 *output = AUDIO_IO_HANDLE_NONE;
1485
1486 // skip direct output selection if the request can obviously be attached to a mixed output
1487 // and not explicitly requested
1488 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1489 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1490 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1491 return NAME_NOT_FOUND;
1492 }
1493
1494 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1495 // This prevents creating an offloaded track and tearing it down immediately after start
1496 // when audioflinger detects there is an active non offloadable effect.
1497 // FIXME: We should check the audio session here but we do not have it in this context.
1498 // This may prevent offloading in rare situations where effects are left active by apps
1499 // in the background.
1500 sp<IOProfile> profile;
1501 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1502 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1503 profile = getProfileForOutput(
1504 devices, config->sample_rate, config->format, config->channel_mask,
1505 flags, true /* directOnly */);
1506 }
1507
1508 if (profile == nullptr) {
1509 return NAME_NOT_FOUND;
1510 }
1511
1512 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1513 for (size_t i = 0; i < mOutputs.size(); i++) {
1514 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1515 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1516 // reuse direct output if currently open by the same client
1517 // and configured with same parameters
1518 if ((config->sample_rate == desc->getSamplingRate()) &&
1519 (config->format == desc->getFormat()) &&
1520 (config->channel_mask == desc->getChannelMask()) &&
1521 (session == desc->mDirectClientSession)) {
1522 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301523 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001524 mOutputs.keyAt(i), session);
1525 *output = mOutputs.keyAt(i);
1526 return NO_ERROR;
1527 }
1528 }
1529 }
1530
1531 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001532 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301533 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1534 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001535 return NAME_NOT_FOUND;
1536 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1537 // MMAP gracefully handles lack of an exclusive track resource by mixing
1538 // above the audio framework. For AAudio to know that the limit is reached,
1539 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301540 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1541 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001542 return NAME_NOT_FOUND;
1543 } else {
1544 // Close outputs on this profile, if available, to free resources for this request
1545 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1546 const auto desc = mOutputs.valueAt(i);
1547 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301548 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1549 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001550 closeOutput(desc->mIoHandle);
1551 }
1552 }
1553 }
1554 }
1555
1556 // Unable to close streams to find free resources for this request
1557 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301558 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1559 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001560 return NAME_NOT_FOUND;
1561 }
1562
Atneya Nairb16666a2023-12-11 20:18:33 -08001563 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001564
Michael Chan6fb34492020-12-08 15:44:49 +11001565 // An MSD patch may be using the only output stream that can service this request. Release
1566 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001567 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001568
Eric Laurentf1f22e72021-07-13 14:04:14 +02001569 status_t status =
1570 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001571
1572 // only accept an output with the requested parameters
1573 if (status != NO_ERROR ||
1574 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1575 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1576 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1577 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1578 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1579 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1580 config->channel_mask, outputDesc->getChannelMask());
1581 if (*output != AUDIO_IO_HANDLE_NONE) {
1582 outputDesc->close();
1583 }
1584 // fall back to mixer output if possible when the direct output could not be open
1585 if (audio_is_linear_pcm(config->format) &&
1586 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1587 return NAME_NOT_FOUND;
1588 }
1589 *output = AUDIO_IO_HANDLE_NONE;
1590 return BAD_VALUE;
1591 }
1592 outputDesc->mDirectOpenCount = 1;
1593 outputDesc->mDirectClientSession = session;
1594
1595 addOutput(*output, outputDesc);
1596 mPreviousOutputs = mOutputs;
1597 ALOGV("%s returns new direct output %d", __func__, *output);
1598 mpClientInterface->onAudioPortListUpdate();
1599 return NO_ERROR;
1600}
1601
François Gaffie11d30102018-11-02 16:09:09 +01001602audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1603 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001604 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001605 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001606 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001607 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001608 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001609 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001610 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001611{
Andy Hungc88b0642018-04-27 15:42:35 -07001612 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001613
jiabine375d412019-02-26 12:54:53 -08001614 // Discard haptic channel mask when forcing muting haptic channels.
1615 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001616 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1617 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001618
Eric Laurente552edb2014-03-10 17:42:56 -07001619 // open a direct output if required by specified parameters
1620 //force direct flag if offload flag is set: offloading implies a direct output stream
1621 // and all common behaviors are driven by checking only the direct flag
1622 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001623 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1624 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001625 }
Nadav Bar766fb022018-01-07 12:18:03 +02001626 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1627 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001628 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001629
1630 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1631
Eric Laurente83b55d2014-11-14 10:06:21 -08001632 // only allow deep buffering for music stream type
1633 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001634 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001635 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001636 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001637 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1638 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001639 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001640 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001641 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001642 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001643 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001644 audio_is_linear_pcm(config->format) &&
1645 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001646 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001647 AUDIO_OUTPUT_FLAG_DIRECT);
1648 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001649 }
Eric Laurente552edb2014-03-10 17:42:56 -07001650
Carter Hsua3abb402021-10-26 11:11:20 +08001651 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1652 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1653 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1654 }
1655
Eric Laurentf9230d52024-01-26 18:49:09 +01001656 // Use the spatializer output if the content can be spatialized, no preferred mixer
1657 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001658 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001659 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001660 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001661 && prefMixerConfigInfo == nullptr
1662 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001663 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001664 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001665 }
1666
Eric Laurentc529cf62020-04-17 18:19:10 -07001667 audio_config_t directConfig = *config;
1668 directConfig.channel_mask = channelMask;
1669 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1670 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001671 return output;
1672 }
1673
Eric Laurent14cbfca2016-03-17 09:42:16 -07001674 // A request for HW A/V sync cannot fallback to a mixed output because time
1675 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001676 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001677 return AUDIO_IO_HANDLE_NONE;
1678 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001679 // A request for Tuner cannot fallback to a mixed output
1680 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1681 return AUDIO_IO_HANDLE_NONE;
1682 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001683
Eric Laurente552edb2014-03-10 17:42:56 -07001684 // ignoring channel mask due to downmix capability in mixer
1685
1686 // open a non direct output
1687
1688 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001689 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001690 // get which output is suitable for the specified stream. The actual
1691 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001692 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001693 if (prefMixerConfigInfo != nullptr) {
1694 for (audio_io_handle_t outputHandle : outputs) {
1695 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1696 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1697 output = outputHandle;
1698 break;
1699 }
1700 }
1701 if (output == AUDIO_IO_HANDLE_NONE) {
1702 // No output open with the preferred profile. Open a new one.
1703 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1704 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1705 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1706 config.format = prefMixerConfigInfo->getConfigBase().format;
1707 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1708 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1709 &config, prefMixerConfigInfo->getFlags());
1710 if (preferredOutput == nullptr) {
1711 ALOGE("%s failed to open output with preferred mixer config", __func__);
1712 } else {
1713 output = preferredOutput->mIoHandle;
1714 }
1715 }
1716 } else {
1717 // at this stage we should ignore the DIRECT flag as no direct output could be
1718 // found earlier
1719 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1720 output = selectOutput(
1721 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1722 }
Eric Laurente552edb2014-03-10 17:42:56 -07001723 }
François Gaffie11d30102018-11-02 16:09:09 +01001724 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001725 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001726 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001727
Eric Laurente552edb2014-03-10 17:42:56 -07001728 return output;
1729}
1730
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001731sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001732 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1733 mAvailableInputDevices);
1734 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1735}
1736
1737DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1738 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1739 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740}
1741
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001742const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001744 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1745 if (msdModule != 0) {
1746 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1747 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1748 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1749 const struct audio_port_config *source = &patch->mPatch.sources[j];
1750 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1751 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001752 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001753 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001754 }
1755 }
1756 }
1757 return msdPatches;
1758}
1759
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001760bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1761 ssize_t index = mAudioPatches.indexOfKey(handle);
1762 if (index < 0) {
1763 return false;
1764 }
1765 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1766 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1767 if (msdModule == nullptr) {
1768 return false;
1769 }
1770 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1771 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1772 return true;
1773 }
1774 index = getMsdOutputPatches().indexOfKey(handle);
1775 if (index < 0) {
1776 return false;
1777 }
1778 return true;
1779}
1780
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001781status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1782 const InputProfileCollection &inputProfiles,
1783 const OutputProfileCollection &outputProfiles,
1784 const sp<DeviceDescriptor> &sourceDevice,
1785 const sp<DeviceDescriptor> &sinkDevice,
1786 AudioProfileVector& sourceProfiles,
1787 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001789 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 return NO_INIT;
1791 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001792 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001793 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 return NO_INIT;
1795 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001796 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001797 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1798 inProfile->supportsDevice(sourceDevice)) {
1799 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
1801 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001803 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 outProfile->supportsDevice(sinkDevice)) {
1805 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 }
1807 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 return NO_ERROR;
1809}
1810
1811status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1812 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1813 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1814{
Dean Wheatley16809da2022-12-09 14:55:46 +11001815 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1816 static const std::vector<audio_format_t> formatsOrder = {{
1817 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001818 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1819 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001820 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1821 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1822 // preferred).
1823 std::vector<audio_channel_mask_t> masks = {{
1824 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1825 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1826 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1827 // insert index masks (higher counts most preferred) as preferred over position masks
1828 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1829 masks.insert(
1830 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1831 }
1832 return masks;
1833 }();
1834
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001835 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001836 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1837 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1840 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001841 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
1843 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1844 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1845 sinkConfig->format = bestSinkConfig.format;
1846 // For encoded streams force direct flag to prevent downstream mixing.
1847 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1848 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001849 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1850 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001851 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001852 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1853 // raw and IEC61937 framed streams.
1854 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1855 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1856 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001857 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1858 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001859 sourceConfig->channel_mask =
1860 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1861 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1862 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001863 sourceConfig->format = bestSinkConfig.format;
1864 // Copy input stream directly without any processing (e.g. resampling).
1865 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1866 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1867 if (hwAvSync) {
1868 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1869 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1870 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1871 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1872 }
1873 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1874 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1875 sinkConfig->config_mask |= config_mask;
1876 sourceConfig->config_mask |= config_mask;
1877 return NO_ERROR;
1878}
1879
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001880PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1881 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882{
1883 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001884 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1885 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1886 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1887 if (deviceModule == nullptr) {
1888 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1889 return patchBuilder;
1890 }
1891 const InputProfileCollection inputProfiles = msdIsSource ?
1892 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1893 const OutputProfileCollection outputProfiles = msdIsSource ?
1894 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1895
1896 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1897 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1898 device : getMsdAudioOutDevices().itemAt(0);
1899 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1900
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1902 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001903 AudioProfileVector sourceProfiles;
1904 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1906 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001907 for (auto hwAvSync : { true, false }) {
1908 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1909 sourceProfiles, sinkProfiles) != NO_ERROR) {
1910 continue;
1911 }
1912 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1913 &sinkConfig) == NO_ERROR) {
1914 // Found a matching config. Re-create PatchBuilder with this config.
1915 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1916 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001917 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001918 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001919 " supporting PCM format conversion.", __func__);
1920 return patchBuilder;
1921}
1922
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001923status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001924 DeviceVector devices;
1925 if (outputDevices != nullptr && outputDevices->size() > 0) {
1926 devices.add(*outputDevices);
1927 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001928 // Use media strategy for unspecified output device. This should only
1929 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1930 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001931 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001932 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001933 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 }
Michael Chan6fb34492020-12-08 15:44:49 +11001935 std::vector<PatchBuilder> patchesToCreate;
1936 for (auto i = 0u; i < devices.size(); ++i) {
1937 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001938 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001939 }
1940 // Retain only the MSD patches associated with outputDevices request.
1941 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001942 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001943 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1944 auto retainedPatch = false;
1945 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1946 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1947 patchesToRemove.removeItemsAt(i);
1948 retainedPatch = true;
1949 break;
1950 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 }
Michael Chan6fb34492020-12-08 15:44:49 +11001952 if (retainedPatch) {
1953 it = patchesToCreate.erase(it);
1954 continue;
1955 }
1956 ++it;
1957 }
1958 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1959 return NO_ERROR;
1960 }
1961 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1962 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001963 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 }
Michael Chan6fb34492020-12-08 15:44:49 +11001965 status_t status = NO_ERROR;
1966 for (const auto &p : patchesToCreate) {
1967 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1968 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1969 char message[256];
1970 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1971 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1972 currStatus == NO_ERROR ? "Success" : "Error",
1973 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1974 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1975 if (currStatus == NO_ERROR) {
1976 ALOGD("%s", message);
1977 } else {
1978 ALOGE("%s", message);
1979 if (status == NO_ERROR) {
1980 status = currStatus;
1981 }
1982 }
1983 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001984 return status;
1985}
1986
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001987void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1988 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001989 for (size_t i = 0; i < msdPatches.size(); i++) {
1990 const auto& patch = msdPatches[i];
1991 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1992 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1993 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1994 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1995 releaseAudioPatch(patch->getHandle(), mUidCached);
1996 break;
1997 }
1998 }
1999 }
2000}
2001
Dorin Drimus94d94412022-02-02 09:05:02 +01002002bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002003 DeviceVector devicesToCheck =
2004 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002005 AudioPatchCollection msdPatches = getMsdOutputPatches();
2006 for (size_t i = 0; i < msdPatches.size(); i++) {
2007 const auto& patch = msdPatches[i];
2008 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2009 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2010 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2011 const auto& foundDevice = devicesToCheck.getDevice(
2012 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2013 if (foundDevice != nullptr) {
2014 devicesToCheck.remove(foundDevice);
2015 if (devicesToCheck.isEmpty()) {
2016 return true;
2017 }
2018 }
2019 }
2020 }
2021 }
2022 return false;
2023}
2024
Eric Laurente0720872014-03-11 09:30:41 -07002025audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002026 audio_output_flags_t flags,
2027 audio_format_t format,
2028 audio_channel_mask_t channelMask,
2029 uint32_t samplingRate,
2030 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002031{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2033 "%s called with format %#x", __func__, format);
2034
jiabinebb6af42020-06-09 17:31:17 -07002035 // Return the output that haptic-generating attached to when 1) session id is specified,
2036 // 2) haptic-generating effect exists for given session id and 3) the output that
2037 // haptic-generating effect attached to is in given outputs.
2038 if (sessionId != AUDIO_SESSION_NONE) {
2039 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2040 sessionId, FX_IID_HAPTICGENERATOR);
2041 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2042 return hapticGeneratingOutput;
2043 }
2044 }
2045
Eric Laurent16c66dd2019-05-01 17:54:10 -07002046 // Flags disqualifying an output: the match must happen before calling selectOutput()
2047 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2048 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2049
2050 // Flags expressing a functional request: must be honored in priority over
2051 // other criteria
2052 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2053 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002054 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2055 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 // Flags expressing a performance request: have lower priority than serving
2057 // requested sampling rate or channel mask
2058 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2059 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2060 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2061
2062 const audio_output_flags_t functionalFlags =
2063 (audio_output_flags_t)(flags & kFunctionalFlags);
2064 const audio_output_flags_t performanceFlags =
2065 (audio_output_flags_t)(flags & kPerformanceFlags);
2066
2067 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2068
Eric Laurente552edb2014-03-10 17:42:56 -07002069 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002070 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002071 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002072 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002074 // with tiebreak preferring the minimum number of extra functional flags
2075 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 // 3: the output supporting the exact channel mask
2077 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002078 // 5: the output with the highest sampling rate if the requested sample rate is
2079 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002080 // 6: the output with the highest number of requested performance flags
2081 // 7: the output with the bit depth the closest to the requested one
2082 // 8: the primary output
2083 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002084
Eric Laurent16c66dd2019-05-01 17:54:10 -07002085 // matching criteria values in priority order for best matching output so far
2086 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002087
Shunkai Yao808da212024-04-05 22:50:56 +00002088 const bool hasOrphanHaptic =
2089 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002090 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2091 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2092 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002093
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002094 for (audio_io_handle_t output : outputs) {
2095 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002096 // matching criteria values in priority order for current output
2097 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002098
Eric Laurent16c66dd2019-05-01 17:54:10 -07002099 if (outputDesc->isDuplicated()) {
2100 continue;
2101 }
2102 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2103 continue;
2104 }
Eric Laurent8838a382014-09-08 16:44:28 -07002105
Eric Laurent16c66dd2019-05-01 17:54:10 -07002106 // If haptic channel is specified, use the haptic output if present.
2107 // When using haptic output, same audio format and sample rate are required.
2108 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002109 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002110 // skip if haptic channel specified but output does not support it, or output support haptic
2111 // but there is no haptic channel requested AND no orphan haptic effect exist
2112 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2113 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002114 continue;
2115 }
Shunkai Yao808da212024-04-05 22:50:56 +00002116 // In the case of audio-coupled-haptic playback, there is no format conversion and
2117 // resampling in the framework, same format/channel/sampleRate for client and the output
2118 // thread is required. In the case of HapticGenerator effect, do not require format
2119 // matching.
2120 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2121 samplingRate == outputDesc->getSamplingRate()) ||
2122 (hapticChannelCount == 0 && hasOrphanHaptic)) {
2123 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002124 }
2125
2126 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002127 const int matchingFunctionalFlags =
2128 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2129 const int totalFunctionalFlags =
2130 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2131 // Prefer matching functional flags, but subtract unnecessary functional flags.
2132 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002133
2134 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002135 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2136 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002137 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2138 channelCount <= outputChannelCount) {
2139 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002140 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2141 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002142 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002143 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 currentMatchCriteria[3] = outputChannelCount;
2145 }
2146
2147 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002148 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002149 int diff; // avoid unsigned integer overflow.
2150 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2151
2152 // prefer the closest output sampling rate greater than or equal to target
2153 // if none exists, prefer the closest output sampling rate less than target.
2154 //
2155 // criteria is offset to make non-negative.
2156 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002157 }
2158
2159 // performance flags match
2160 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2161
2162 // format match
2163 if (format != AUDIO_FORMAT_INVALID) {
2164 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002165 PolicyAudioPort::kFormatDistanceMax -
2166 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002167 }
2168
2169 // primary output match
2170 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2171
2172 // compare match criteria by priority then value
2173 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2174 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2175 bestMatchCriteria = currentMatchCriteria;
2176 bestOutput = output;
2177
2178 std::stringstream result;
2179 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2180 std::ostream_iterator<int>(result, " "));
2181 ALOGV("%s new bestOutput %d criteria %s",
2182 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002183 }
2184 }
2185
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002187}
2188
Eric Laurent8fc147b2018-07-22 19:13:55 -07002189status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002190{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002191 ALOGV("%s portId %d", __FUNCTION__, portId);
2192
2193 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2194 if (outputDesc == 0) {
2195 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002196 return BAD_VALUE;
2197 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002198 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002199
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002201 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002202
Eric Laurent733ce942017-12-07 12:18:25 -08002203 status_t status = outputDesc->start();
2204 if (status != NO_ERROR) {
2205 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002206 }
2207
Eric Laurent97ac8712018-07-27 18:59:02 -07002208 uint32_t delayMs;
2209 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002210
2211 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002212 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002213 if (status == DEAD_OBJECT) {
2214 sp<SwAudioOutputDescriptor> desc =
2215 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2216 if (desc == nullptr) {
2217 // This is not common, it may indicate something wrong with the HAL.
2218 ALOGE("%s unable to open output with default config", __func__);
2219 return status;
2220 }
2221 desc->mUsePreferredMixerAttributes = true;
2222 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002223 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002224 }
jiabina84c3d32022-12-02 18:59:55 +00002225
2226 // If the client is the first one active on preferred mixer parameters, reopen the output
2227 // if the current mixer parameters doesn't match the preferred one.
2228 if (outputDesc->devices().size() == 1) {
2229 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2230 outputDesc->devices()[0]->getId(), client->strategy());
2231 if (info != nullptr && info->getUid() == client->uid()) {
2232 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2233 info->getConfigBase(), info->getFlags())) {
2234 stopSource(outputDesc, client);
2235 outputDesc->stop();
2236 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2237 config.channel_mask = info->getConfigBase().channel_mask;
2238 config.sample_rate = info->getConfigBase().sample_rate;
2239 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002240 sp<SwAudioOutputDescriptor> desc =
2241 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2242 if (desc == nullptr) {
2243 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002244 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002245 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002246 // Intentionally return error to let the client side resending request for
2247 // creating and starting.
2248 return DEAD_OBJECT;
2249 }
2250 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002251 if (info->getActiveClientCount() == 1 &&
2252 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2253 // If it is first bit-perfect client, reroute all clients that will be routed to
2254 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2255 PortHandleVector clientsToInvalidate;
2256 for (size_t i = 0; i < mOutputs.size(); i++) {
2257 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002258 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002259 continue;
2260 }
2261 for (const auto& c : mOutputs[i]->getClientIterable()) {
2262 clientsToInvalidate.push_back(c->portId());
2263 }
2264 }
2265 if (!clientsToInvalidate.empty()) {
2266 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2267 __func__);
2268 mpClientInterface->invalidateTracks(clientsToInvalidate);
2269 }
2270 }
jiabina84c3d32022-12-02 18:59:55 +00002271 }
2272 }
2273
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002274 if (client->hasPreferredDevice()) {
2275 // playback activity with preferred device impacts routing occurred, inform upper layers
2276 mpClientInterface->onRoutingUpdated();
2277 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002278 if (delayMs != 0) {
2279 usleep(delayMs * 1000);
2280 }
2281
2282 return status;
2283}
2284
Eric Laurent96d1dda2022-03-14 17:14:19 +01002285bool AudioPolicyManager::isLeUnicastActive() const {
2286 if (isInCall()) {
2287 return true;
2288 }
2289 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2290}
2291
2292bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2293 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2294 return false;
2295 }
2296 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2297 ALOGV("%s active %d", __func__, active);
2298 return active;
2299}
2300
Eric Laurent97ac8712018-07-27 18:59:02 -07002301status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2302 const sp<TrackClientDescriptor>& client,
2303 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002304{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002305 // cannot start playback of STREAM_TTS if any other output is being used
2306 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002307
2308 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002310 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002311 auto clientStrategy = client->strategy();
2312 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002313 if (stream == AUDIO_STREAM_TTS) {
2314 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002315 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002316 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002317 return INVALID_OPERATION;
2318 } else {
2319 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2320 }
2321 } else {
2322 // some playback other than beacon starts
2323 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2324 }
2325
Eric Laurent77305a62016-07-25 16:39:22 -07002326 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002327 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002328 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002329
François Gaffie11d30102018-11-02 16:09:09 +01002330 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002331 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002332 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002333 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002334 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002335 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002336 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002337 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002338 } else {
2339 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002340 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002341 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2342 AUDIO_FORMAT_DEFAULT);
2343 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2344 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002345 }
2346
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002347 // requiresMuteCheck is false when we can bypass mute strategy.
2348 // It covers a common case when there is no materially active audio
2349 // and muting would result in unnecessary delay and dropped audio.
2350 const uint32_t outputLatencyMs = outputDesc->latency();
2351 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002352 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002353
Eric Laurente552edb2014-03-10 17:42:56 -07002354 // increment usage count for this stream on the requested output:
2355 // NOTE that the usage count is the same for duplicated output and hardware output which is
2356 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002357 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002358
2359 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002360 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002361 // Preferred device may be exclusive, use only if no other active clients on this output
2362 devices = DeviceVector(
2363 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2364 } else {
2365 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2366 }
François Gaffie11d30102018-11-02 16:09:09 +01002367 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002368 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002369 }
2370 }
Eric Laurente552edb2014-03-10 17:42:56 -07002371
François Gaffiec005e562018-11-06 15:04:49 +01002372 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002373 selectOutputForMusicEffects();
2374 }
2375
François Gaffie1c878552018-11-22 16:53:21 +01002376 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002377 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002378 if (devices.isEmpty()) {
2379 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002380 }
François Gaffiec005e562018-11-06 15:04:49 +01002381 bool shouldWait =
2382 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2383 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2384 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002385 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002386 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002387 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002388 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002389 // An output has a shared device if
2390 // - managed by the same hw module
2391 // - supports the currently selected device
2392 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002393 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002394
Eric Laurent77305a62016-07-25 16:39:22 -07002395 // force a device change if any other output is:
2396 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002397 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002398 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002399 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002400 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002401 // change the device currently selected by the other output.
2402 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002403 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002404 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002405 force = true;
2406 }
2407 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002408 // a notification so that audio focus effect can propagate, or that a mute/unmute
2409 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002410 const uint32_t latencyMs = desc->latency();
2411 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2412
2413 if (shouldWait && isActive && (waitMs < latencyMs)) {
2414 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002415 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002416
2417 // Require mute check if another output is on a shared device
2418 // and currently active to have proper drain and avoid pops.
2419 // Note restoring AudioTracks onto this output needs to invoke
2420 // a volume ramp if there is no mute.
2421 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002422 }
2423 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002424
jiabin3ff8d7d2022-12-13 06:27:44 +00002425 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2426 // If the output is open with preferred mixer attributes, but the routed device is
2427 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2428 // changed.
2429 return DEAD_OBJECT;
2430 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002431 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302432 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2433 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002434
Eric Laurente552edb2014-03-10 17:42:56 -07002435 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002436 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002437 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002438 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002439 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002440 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002441 outputDesc->useHwGain() /*force*/)) {
2442 // request AudioService to reinitialize the volume curves asynchronously
2443 ALOGE("checkAndSetVolume failed, requesting volume range init");
2444 mpClientInterface->onVolumeRangeInitRequest();
2445 };
Eric Laurente552edb2014-03-10 17:42:56 -07002446
2447 // update the outputs if starting an output with a stream that can affect notification
2448 // routing
2449 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002450
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002451 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002452 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002453 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002454 }
Eric Laurentdc462862016-07-19 12:29:53 -07002455
2456 if (waitMs > muteWaitMs) {
2457 *delayMs = waitMs - muteWaitMs;
2458 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002459
2460 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2461 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2462 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2463 // change occurs after the MixerThread starts and causes a stream volume
2464 // glitch.
2465 //
2466 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002467 }
Eric Laurentdc462862016-07-19 12:29:53 -07002468
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002469 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002470 mEngine->getForceUse(
2471 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002472 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002473 }
2474
Eric Laurent97ac8712018-07-27 18:59:02 -07002475 // Automatically enable the remote submix input when output is started on a re routing mix
2476 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002477 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2478 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002479 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2480 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2481 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002482 "remote-submix",
2483 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002484 }
2485
Eric Laurent96d1dda2022-03-14 17:14:19 +01002486 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2487
Eric Laurente552edb2014-03-10 17:42:56 -07002488 return NO_ERROR;
2489}
2490
Eric Laurent96d1dda2022-03-14 17:14:19 +01002491void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2492 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2493 bool isUnicastActive = isLeUnicastActive();
2494
2495 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002496 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002497 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2498 for (size_t i = 0; i < mOutputs.size(); i++) {
2499 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2500 if (desc != ignoredOutput && desc->isActive()
2501 && ((isUnicastActive &&
2502 !desc->devices().
2503 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2504 || (wasUnicastActive &&
2505 !desc->devices().getDevicesFromTypes(
2506 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2507 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2508 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002509 if (desc->mUsePreferredMixerAttributes && force) {
2510 // If the device is using preferred mixer attributes, the output need to reopen
2511 // with default configuration when the new selected devices are different from
2512 // current routing devices.
2513 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2514 continue;
2515 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302516 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002517 // re-apply device specific volume if not done by setOutputDevice()
2518 if (!force) {
2519 applyStreamVolumes(desc, newDevices.types(), delayMs);
2520 }
2521 }
2522 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002523 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002524 }
2525}
2526
Eric Laurent8fc147b2018-07-22 19:13:55 -07002527status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002528{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002529 ALOGV("%s portId %d", __FUNCTION__, portId);
2530
2531 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2532 if (outputDesc == 0) {
2533 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002534 return BAD_VALUE;
2535 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002536 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002537
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002538 if (client->hasPreferredDevice(true)) {
2539 // playback activity with preferred device impacts routing occurred, inform upper layers
2540 mpClientInterface->onRoutingUpdated();
2541 }
2542
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 ALOGV("stopOutput() output %d, stream %d, session %d",
2544 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002545
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002547
Eric Laurent733ce942017-12-07 12:18:25 -08002548 if (status == NO_ERROR ) {
2549 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002550 } else {
2551 return status;
2552 }
2553
2554 if (outputDesc->devices().size() == 1) {
2555 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2556 outputDesc->devices()[0]->getId(), client->strategy());
2557 if (info != nullptr && info->getUid() == client->uid()) {
2558 info->decreaseActiveClient();
2559 if (info->getActiveClientCount() == 0) {
2560 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2561 }
2562 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002563 }
2564 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002565}
2566
Eric Laurent97ac8712018-07-27 18:59:02 -07002567status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2568 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002569{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002570 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002571 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002572 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002573 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002574
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002575 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2576
François Gaffie1c878552018-11-22 16:53:21 +01002577 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2578 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002579 // Automatically disable the remote submix input when output is stopped on a
2580 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002581 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002582 if (isSingleDeviceType(
2583 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002584 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002585 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002586 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2587 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002588 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002589 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002590 }
2591 }
2592 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002593 if (client->hasPreferredDevice(true) &&
2594 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002595 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002596 forceDeviceUpdate = true;
2597 }
2598
Eric Laurente552edb2014-03-10 17:42:56 -07002599 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002600 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002601
Eric Laurente552edb2014-03-10 17:42:56 -07002602 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002603 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002604 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002605 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002606
2607 // If the routing does not change, if an output is routed on a device using HwGain
2608 // (aka setAudioPortConfig) and there are still active clients following different
2609 // volume group(s), force reapply volume
2610 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2611 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2612
Eric Laurente552edb2014-03-10 17:42:56 -07002613 // delay the device switch by twice the latency because stopOutput() is executed when
2614 // the track stop() command is received and at that time the audio track buffer can
2615 // still contain data that needs to be drained. The latency only covers the audio HAL
2616 // and kernel buffers. Also the latency does not always include additional delay in the
2617 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302618 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002619 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002620
2621 // force restoring the device selection on other active outputs if it differs from the
2622 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002623 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002624 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002625 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002626 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002627 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002628 desc->isActive() &&
2629 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002630 (newDevices != desc->devices())) {
2631 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2632 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002633
jiabin3ff8d7d2022-12-13 06:27:44 +00002634 if (desc->mUsePreferredMixerAttributes && force) {
2635 // If the device is using preferred mixer attributes, the output need to
2636 // reopen with default configuration when the new selected devices are
2637 // different from current routing devices.
2638 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2639 continue;
2640 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302641 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002642
Eric Laurent57de36c2016-09-28 16:59:11 -07002643 // re-apply device specific volume if not done by setOutputDevice()
2644 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002645 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002646 }
Eric Laurente552edb2014-03-10 17:42:56 -07002647 }
2648 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002649 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002650 // update the outputs if stopping one with a stream that can affect notification routing
2651 handleNotificationRoutingForStream(stream);
2652 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002653
2654 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2655 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002656 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002657 }
2658
François Gaffiec005e562018-11-06 15:04:49 +01002659 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002660 selectOutputForMusicEffects();
2661 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002662
2663 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2664
Eric Laurente552edb2014-03-10 17:42:56 -07002665 return NO_ERROR;
2666 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002667 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002668 return INVALID_OPERATION;
2669 }
2670}
2671
jiabinbce0c1d2020-10-05 11:20:18 -07002672bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002673{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002674 ALOGV("%s portId %d", __FUNCTION__, portId);
2675
2676 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2677 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002678 // If an output descriptor is closed due to a device routing change,
2679 // then there are race conditions with releaseOutput from tracks
2680 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2681 // destroyed shortly thereafter.
2682 //
2683 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002684 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002685 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002686 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002687
2688 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002689
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302690 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2691 if (outputDesc->isClientActive(client)) {
2692 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2693 stopOutput(portId);
2694 }
2695
Eric Laurent8fc147b2018-07-22 19:13:55 -07002696 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2697 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002698 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002699 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002700 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002701 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002702 if (--outputDesc->mDirectOpenCount == 0) {
2703 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002704 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002705 }
2706 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302707
Andy Hung39efb7a2018-09-26 15:39:28 -07002708 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002709 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2710 // The output is pending reopened to query dynamic profiles and
2711 // there is no active clients
2712 closeOutput(outputDesc->mIoHandle);
2713 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2714 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2715 if (newOutputDesc == nullptr) {
2716 ALOGE("%s failed to open output", __func__);
2717 }
2718 return true;
2719 }
2720 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002721}
2722
Eric Laurentcaf7f482014-11-25 17:50:47 -08002723status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2724 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002725 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002726 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002727 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002728 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002729 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002730 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002731 input_type_t *inputType,
2732 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002733{
François Gaffiec005e562018-11-06 15:04:49 +01002734 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002735 "flags %#x attributes=%s requested device ID %d",
2736 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2737 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002738
Eric Laurentad2e7b92017-09-14 20:06:42 -07002739 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002740 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002741 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002742 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002743 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002744 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002745 sp<RecordClientDescriptor> clientDesc;
2746 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002747 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749
2750 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2751 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2752 return INVALID_OPERATION;
2753 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002754
Francois Gaffie716e1432019-01-14 16:58:59 +01002755 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2756 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002757 }
2758
Paul McLean466dc8e2015-04-17 13:15:36 -06002759 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002760 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002761 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002762
Eric Laurentad2e7b92017-09-14 20:06:42 -07002763 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2764 // possible
2765 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2766 *input != AUDIO_IO_HANDLE_NONE) {
2767 ssize_t index = mInputs.indexOfKey(*input);
2768 if (index < 0) {
2769 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2770 status = BAD_VALUE;
2771 goto error;
2772 }
2773 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002774 RecordClientVector clients = inputDesc->getClientsForSession(session);
2775 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002776 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2777 status = BAD_VALUE;
2778 goto error;
2779 }
2780 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2781 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002782 // corresponds to a new client and is only permitted from the same UID.
2783 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002784 if (clients.size() > 1) {
2785 for (const auto& client : clients) {
2786 // The client map is ordered by key values (portId) and portIds are allocated
2787 // incrementaly. So the first client in this list is the one opened by audio flinger
2788 // when the mmap stream is created and should be ignored as it does not correspond
2789 // to an actual client
2790 if (client == *clients.cbegin()) {
2791 continue;
2792 }
2793 if (uid != client->uid() && !client->isSilenced()) {
2794 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2795 uid, client->portId(), client->uid());
2796 status = INVALID_OPERATION;
2797 goto error;
2798 }
Eric Laurent331679c2018-04-16 17:03:16 -07002799 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002800 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002801 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002802 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002803
Eric Laurentfecbceb2021-02-09 14:46:43 +01002804 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002805 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002806 }
2807
2808 *input = AUDIO_IO_HANDLE_NONE;
2809 *inputType = API_INPUT_INVALID;
2810
Francois Gaffie716e1432019-01-14 16:58:59 +01002811 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002812 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002813 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002814 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002815 ALOGW("%s could not find input mix for attr %s",
2816 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002817 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002818 }
jiabinc1de2df2019-05-07 14:26:40 -07002819 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2820 String8(attr->tags + strlen("addr=")),
2821 AUDIO_FORMAT_DEFAULT);
2822 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002823 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002824 __func__, attributes.source, attributes.tags);
2825 status = BAD_VALUE;
2826 goto error;
2827 }
2828
Kevin Rocard25f9b052019-02-27 15:08:54 -08002829 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2830 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2831 } else {
2832 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2833 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002834 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002835 if (explicitRoutingDevice != nullptr) {
2836 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002837 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002838 // Prevent from storing invalid requested device id in clients
2839 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002840 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002841 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2842 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002843 }
François Gaffie11d30102018-11-02 16:09:09 +01002844 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002845 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002846 status = BAD_VALUE;
2847 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002848 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002849 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2850 *inputType = API_INPUT_MIX_CAPTURE;
2851 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002852 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2853 // there is an external policy, but this input is attached to a mix of recorders,
2854 // meaning it receives audio injected into the framework, so the recorder doesn't
2855 // know about it and is therefore considered "legacy"
2856 *inputType = API_INPUT_LEGACY;
2857 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002858 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002859 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002860 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002861 } else {
2862 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002863 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002864
Eric Laurent599c7582015-12-07 18:05:55 -08002865 }
2866
François Gaffiec005e562018-11-06 15:04:49 +01002867 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002868 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002869 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002870 AudioProfileVector profiles;
2871 status_t ret = getProfilesForDevices(
2872 DeviceVector(device), profiles, flags, true /*isInput*/);
2873 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002874 const auto channels = profiles[0]->getChannels();
2875 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2876 config->channel_mask = *channels.begin();
2877 }
2878 const auto sampleRates = profiles[0]->getSampleRates();
2879 if (!sampleRates.empty() &&
2880 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2881 config->sample_rate = *sampleRates.begin();
2882 }
jiabinf1c73972022-04-14 16:28:52 -07002883 config->format = profiles[0]->getFormat();
2884 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002885 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002886 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002887
Eric Laurent8f42ea12018-08-08 09:08:25 -07002888exit:
2889
François Gaffiec005e562018-11-06 15:04:49 +01002890 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2891 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002892
Francois Gaffie716e1432019-01-14 16:58:59 +01002893 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002894 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002895 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002896
Mikhail Naganov2996f672019-04-18 12:29:59 -07002897 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002898 requestedDeviceId, attributes.source, flags,
2899 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002900 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002901 // Move (if found) effect for the client session to its input
2902 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002903 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904
2905 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2906 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002907
Eric Laurent599c7582015-12-07 18:05:55 -08002908 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002909
2910error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002911 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002912}
2913
2914
François Gaffie11d30102018-11-02 16:09:09 +01002915audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002916 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002917 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002918 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002919 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002920 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002921{
2922 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002923 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002924 bool isSoundTrigger = false;
2925
François Gaffiec005e562018-11-06 15:04:49 +01002926 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002927 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2928 if (index >= 0) {
2929 input = mSoundTriggerSessions.valueFor(session);
2930 isSoundTrigger = true;
2931 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2932 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2933 } else {
2934 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002935 }
François Gaffiec005e562018-11-06 15:04:49 +01002936 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002937 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002938 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002939 }
2940
Carter Hsua3abb402021-10-26 11:11:20 +08002941 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2942 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2943 }
2944
Eric Laurentfe231122017-11-17 17:48:06 -08002945 // sampling rate and flags may be updated by getInputProfile
2946 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2947 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002948 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002949 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002950 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002951 // find a compatible input profile (not necessarily identical in parameters)
2952 sp<IOProfile> profile = getInputProfile(
2953 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2954 if (profile == nullptr) {
2955 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002956 }
jiabin2fd710d2022-05-02 23:20:22 +00002957
Glenn Kasten05ddca52016-02-11 08:17:12 -08002958 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002959 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002960 if (samplingRate == 0) {
2961 samplingRate = profileSamplingRate;
2962 }
Eric Laurente552edb2014-03-10 17:42:56 -07002963
Eric Laurent322b4d22015-04-03 15:57:54 -07002964 if (profile->getModuleHandle() == 0) {
2965 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002966 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002967 }
2968
Eric Laurentec376dc2021-04-08 20:41:22 +02002969 // Reuse an already opened input if a client with the same session ID already exists
2970 // on that input
2971 for (size_t i = 0; i < mInputs.size(); i++) {
2972 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2973 if (desc->mProfile != profile) {
2974 continue;
2975 }
2976 RecordClientVector clients = desc->clientsList();
2977 for (const auto &client : clients) {
2978 if (session == client->session()) {
2979 return desc->mIoHandle;
2980 }
2981 }
2982 }
2983
Eric Laurent3974e3b2017-12-07 17:58:43 -08002984 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002985 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002986 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002987 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002988 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002989 continue;
2990 }
2991 // if sound trigger, reuse input if used by other sound trigger on same session
2992 // else
2993 // reuse input if active client app is not in IDLE state
2994 //
2995 RecordClientVector clients = desc->clientsList();
2996 bool doClose = false;
2997 for (const auto& client : clients) {
2998 if (isSoundTrigger != client->isSoundTrigger()) {
2999 continue;
3000 }
3001 if (client->isSoundTrigger()) {
3002 if (session == client->session()) {
3003 return desc->mIoHandle;
3004 }
3005 continue;
3006 }
3007 if (client->active() && client->appState() != APP_STATE_IDLE) {
3008 return desc->mIoHandle;
3009 }
3010 doClose = true;
3011 }
3012 if (doClose) {
3013 closeInput(desc->mIoHandle);
3014 } else {
3015 i++;
3016 }
3017 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003018 }
3019
Eric Laurentfe231122017-11-17 17:48:06 -08003020 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003021
Eric Laurentfe231122017-11-17 17:48:06 -08003022 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3023 lConfig.sample_rate = profileSamplingRate;
3024 lConfig.channel_mask = profileChannelMask;
3025 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003026
François Gaffie11d30102018-11-02 16:09:09 +01003027 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003028
3029 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003030 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003031 (profileSamplingRate != lConfig.sample_rate) ||
3032 !audio_formats_match(profileFormat, lConfig.format) ||
3033 (profileChannelMask != lConfig.channel_mask)) {
3034 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003035 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003036 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003037 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003038 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003039 }
Eric Laurent599c7582015-12-07 18:05:55 -08003040 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003041 }
3042
Eric Laurentc722f302014-12-10 11:21:49 -08003043 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003044
Eric Laurent599c7582015-12-07 18:05:55 -08003045 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003046 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003047
Eric Laurent599c7582015-12-07 18:05:55 -08003048 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003049}
3050
Eric Laurent4eb58f12018-12-07 16:41:02 -08003051status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003052{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003053 ALOGV("%s portId %d", __FUNCTION__, portId);
3054
3055 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3056 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003057 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003058 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003059 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003060 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003061 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 if (client->active()) {
3063 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3064 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003065 }
3066
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 audio_session_t session = client->session();
3068
Eric Laurent4eb58f12018-12-07 16:41:02 -08003069 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070
Eric Laurent4eb58f12018-12-07 16:41:02 -08003071 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003072
Eric Laurent4eb58f12018-12-07 16:41:02 -08003073 status_t status = inputDesc->start();
3074 if (status != NO_ERROR) {
3075 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003076 }
Eric Laurente552edb2014-03-10 17:42:56 -07003077
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003078 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003079 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003081
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 // indicate active capture to sound trigger service if starting capture from a mic on
3083 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003084 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003085 if (device != nullptr) {
3086 status = setInputDevice(input, device, true /* force */);
3087 } else {
3088 ALOGW("%s no new input device can be found for descriptor %d",
3089 __FUNCTION__, inputDesc->getId());
3090 status = BAD_VALUE;
3091 }
Eric Laurente552edb2014-03-10 17:42:56 -07003092
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003093 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003094 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003095 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003096 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003097 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3098 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003100 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003101
François Gaffie11d30102018-11-02 16:09:09 +01003102 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3103 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003104 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003105 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003107
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 // automatically enable the remote submix output when input is started if not
3109 // used by a policy mix of type MIX_TYPE_RECORDERS
3110 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003111 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003112 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003113 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003115 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3116 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003117 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 if (address != "") {
3119 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3120 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003121 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003122 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003123 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003124 } else if (status != NO_ERROR) {
3125 // Restore client activity state.
3126 inputDesc->setClientActive(client, false);
3127 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003128 }
3129
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003130 ALOGV("%s input %d source = %d status = %d exit",
3131 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003132
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003133 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003134}
3135
Eric Laurent8fc147b2018-07-22 19:13:55 -07003136status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003137{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003138 ALOGV("%s portId %d", __FUNCTION__, portId);
3139
3140 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3141 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003142 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003143 return BAD_VALUE;
3144 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003145 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003146 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003147 if (!client->active()) {
3148 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003149 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003150 }
Carter Hsue6139d52021-07-08 10:30:20 +08003151 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003153
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 inputDesc->stop();
3155 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003156 auto current_source = inputDesc->source();
3157 setInputDevice(input, getNewInputDevice(inputDesc),
3158 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003159 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003160 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003161 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003162 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003163 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3164 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003165 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003166 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003167
3168 // automatically disable the remote submix output when input is stopped if not
3169 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003170 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003171 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003172 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003173 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003174 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3175 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176 }
3177 if (address != "") {
3178 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3179 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003180 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181 }
3182 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 resetInputDevice(input);
3184
3185 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3186 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003187 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3188 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003189 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003190 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191 }
3192 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003193 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003194 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003195}
3196
Eric Laurent8fc147b2018-07-22 19:13:55 -07003197void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003198{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003199 ALOGV("%s portId %d", __FUNCTION__, portId);
3200
3201 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3202 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003203 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003204 return;
3205 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003206 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003207 audio_io_handle_t input = inputDesc->mIoHandle;
3208
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003210
Andy Hung39efb7a2018-09-26 15:39:28 -07003211 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003212 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003213 if (inputDesc->getClientCount() > 0) {
3214 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003215 return;
3216 }
3217
Eric Laurent05b90f82014-08-27 15:32:29 -07003218 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003219 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003220 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003221}
3222
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003224{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003225 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003226
3227 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003228 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003229 }
3230}
3231
Eric Laurent8f42ea12018-08-08 09:08:25 -07003232void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3233{
3234 stopInput(portId);
3235 releaseInput(portId);
3236}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003237
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003238bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3239 if (input->clientsList().size() == 0
3240 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3241 return true;
3242 }
3243 for (const auto& client : input->clientsList()) {
3244 sp<DeviceDescriptor> device =
3245 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3246 client->session());
3247 if (!input->supportedDevices().contains(device)) {
3248 return true;
3249 }
3250 }
3251 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3252 return false;
3253}
3254
Eric Laurent0dd51852019-04-19 18:18:58 -07003255void AudioPolicyManager::checkCloseInputs() {
3256 // After connecting or disconnecting an input device, close input if:
3257 // - it has no client (was just opened to check profile) OR
3258 // - none of its supported devices are connected anymore OR
3259 // - one of its clients cannot be routed to one of its supported
3260 // devices anymore. Otherwise update device selection
3261 std::vector<audio_io_handle_t> inputsToClose;
3262 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003263 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003264 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003265 }
3266 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003267 for (const audio_io_handle_t handle : inputsToClose) {
3268 ALOGV("%s closing input %d", __func__, handle);
3269 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003270 }
Eric Laurentd4692962014-05-05 18:13:44 -07003271}
3272
François Gaffie251c7f02018-11-07 10:41:08 +01003273void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003274{
3275 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003276 if (indexMin < 0 || indexMax < 0) {
3277 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3278 return;
3279 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003280 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003281
3282 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003283 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3284 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003285 continue;
3286 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003287 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003288 }
Eric Laurente552edb2014-03-10 17:42:56 -07003289}
3290
Eric Laurente0720872014-03-11 09:30:41 -07003291status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003292 int index,
3293 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003294{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003296 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3297 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3298 return NO_ERROR;
3299 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303300 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3301 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003302 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003303}
3304
Eric Laurente0720872014-03-11 09:30:41 -07003305status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003306 int *index,
3307 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003308{
François Gaffiec005e562018-11-06 15:04:49 +01003309 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3310 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003311 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003312 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003313 deviceTypes = mEngine->getOutputDevicesForStream(
3314 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003315 }
jiabin9a3361e2019-10-01 09:38:30 -07003316 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003317}
3318
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003319status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003320 int index,
3321 audio_devices_t device)
3322{
3323 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003324 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3325 if (group == VOLUME_GROUP_NONE) {
3326 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003327 return BAD_VALUE;
3328 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003329 ALOGV("%s: group %d matching with %s index %d",
3330 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003331 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003332 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003333 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003334 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3335 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3336 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3337 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003338 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3339
3340 status = setVolumeCurveIndex(index, device, curves);
3341 if (status != NO_ERROR) {
3342 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3343 return status;
3344 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003345
jiabin9a3361e2019-10-01 09:38:30 -07003346 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003347 auto curCurvAttrs = curves.getAttributes();
3348 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3349 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003350 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003351 } else if (!curves.getStreamTypes().empty()) {
3352 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003353 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003354 } else {
3355 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3356 return BAD_VALUE;
3357 }
jiabin9a3361e2019-10-01 09:38:30 -07003358 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3359 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003360
François Gaffiecfe17322018-11-07 13:41:29 +01003361 // update volume on all outputs and streams matching the following:
3362 // - The requested stream (or a stream matching for volume control) is active on the output
3363 // - The device (or devices) selected by the engine for this stream includes
3364 // the requested device
3365 // - For non default requested device, currently selected device on the output is either the
3366 // requested device or one of the devices selected by the engine for this stream
3367 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3368 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003369 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003370 for (size_t i = 0; i < mOutputs.size(); i++) {
3371 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003372 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003373
jiabin9a3361e2019-10-01 09:38:30 -07003374 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3375 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003376 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003377
3378 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003379 continue;
3380 }
3381 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3382 curDevices.find(device) == curDevices.end()) {
3383 continue;
3384 }
3385 bool applyVolume = false;
3386 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3387 curSrcDevices.insert(device);
3388 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003389 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3390 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003391 } else {
3392 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3393 }
3394 if (!applyVolume) {
3395 continue; // next output
3396 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003397 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3398 // If a higher priority strategy is active, and the output is routed to a device with a
3399 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003400 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003401 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003402 // If the volume source is active with higher priority source, ensure at least Sw Muted
3403 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003404 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3405 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3406 false /*preferredDevice*/);
3407 if (activeClients.empty()) {
3408 continue;
3409 }
3410 bool isPreempted = false;
3411 bool isHigherPriority = productStrategy < strategy;
3412 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003413 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003414 ALOGV("%s: Strategy=%d (\nrequester:\n"
3415 " group %d, volumeGroup=%d attributes=%s)\n"
3416 " higher priority source active:\n"
3417 " volumeGroup=%d attributes=%s) \n"
3418 " on output %zu, bailing out", __func__, productStrategy,
3419 group, group, toString(attributes).c_str(),
3420 client->volumeSource(), toString(client->attributes()).c_str(), i);
3421 applyVolume = false;
3422 isPreempted = true;
3423 break;
3424 }
3425 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003426 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003427 applyVolume = true;
3428 }
3429 }
3430 if (isPreempted || applyVolume) {
3431 break;
3432 }
3433 }
3434 if (!applyVolume) {
3435 continue; // next output
3436 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003437 }
François Gaffieed91f582020-01-31 10:35:37 +01003438 //FIXME: workaround for truncated touch sounds
3439 // delayed volume change for system stream to be removed when the problem is
3440 // handled by system UI
3441 status_t volStatus = checkAndSetVolume(
3442 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003443 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003444 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3445 if (volStatus != NO_ERROR) {
3446 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003447 }
3448 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003449
3450 // update voice volume if the an active call route exists
3451 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3452 && (curSrcDevices.find(
3453 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3454 != curSrcDevices.end())) {
3455 bool isVoiceVolSrc;
3456 bool isBtScoVolSrc;
3457 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3458 isVoiceVolSrc, isBtScoVolSrc, __func__)
3459 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003460 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3461 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3462 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003463 }
3464 }
3465
François Gaffiecfe17322018-11-07 13:41:29 +01003466 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3467 return status;
3468}
3469
François Gaffieaaac0fd2018-11-22 17:56:39 +01003470status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003471 audio_devices_t device,
3472 IVolumeCurves &volumeCurves)
3473{
3474 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3475 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003476 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3477 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003478 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303479 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3480 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003481 return BAD_VALUE;
3482 }
3483 if (!audio_is_output_device(device)) {
3484 return BAD_VALUE;
3485 }
3486
3487 // Force max volume if stream cannot be muted
3488 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3489
François Gaffieaaac0fd2018-11-22 17:56:39 +01003490 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003491 volumeCurves.addCurrentVolumeIndex(device, index);
3492 return NO_ERROR;
3493}
3494
3495status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3496 int &index,
3497 audio_devices_t device)
3498{
3499 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3500 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003501 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003502 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003503 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003504 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003505 }
jiabin9a3361e2019-10-01 09:38:30 -07003506 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003507}
3508
3509status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3510 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003511 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003512{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003513 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003514 return BAD_VALUE;
3515 }
jiabin9a3361e2019-10-01 09:38:30 -07003516 index = curves.getVolumeIndex(deviceTypes);
3517 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003518 return NO_ERROR;
3519}
3520
3521status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3522 int &index)
3523{
3524 index = getVolumeCurves(attr).getVolumeIndexMin();
3525 return NO_ERROR;
3526}
3527
3528status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3529 int &index)
3530{
3531 index = getVolumeCurves(attr).getVolumeIndexMax();
3532 return NO_ERROR;
3533}
3534
Eric Laurent36829f92017-04-07 19:04:42 -07003535audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003536{
3537 // select one output among several suitable for global effects.
3538 // The priority is as follows:
3539 // 1: An offloaded output. If the effect ends up not being offloadable,
3540 // AudioFlinger will invalidate the track and the offloaded output
3541 // will be closed causing the effect to be moved to a PCM output.
3542 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003543 // 3: The primary output
3544 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003545
François Gaffiec005e562018-11-06 15:04:49 +01003546 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3547 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003548 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003549
Eric Laurent36829f92017-04-07 19:04:42 -07003550 if (outputs.size() == 0) {
3551 return AUDIO_IO_HANDLE_NONE;
3552 }
Eric Laurente552edb2014-03-10 17:42:56 -07003553
Eric Laurent36829f92017-04-07 19:04:42 -07003554 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3555 bool activeOnly = true;
3556
3557 while (output == AUDIO_IO_HANDLE_NONE) {
3558 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3559 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3560 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3561
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003562 for (audio_io_handle_t output : outputs) {
3563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003564 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003565 continue;
3566 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003567 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3568 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003569 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003570 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003571 }
3572 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003573 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003574 }
3575 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003576 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003577 }
3578 }
3579 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3580 output = outputOffloaded;
3581 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3582 output = outputDeepBuffer;
3583 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3584 output = outputPrimary;
3585 } else {
3586 output = outputs[0];
3587 }
3588 activeOnly = false;
3589 }
3590
3591 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003592 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3593 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003594 mMusicEffectOutput = output;
3595 }
3596
3597 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003598 return output;
3599}
3600
Eric Laurent36829f92017-04-07 19:04:42 -07003601audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3602{
3603 return selectOutputForMusicEffects();
3604}
3605
Eric Laurente0720872014-03-11 09:30:41 -07003606status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003607 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003608 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003609 int session,
3610 int id)
3611{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003612 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003613 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003614 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003615 index = mInputs.indexOfKey(io);
3616 if (index < 0) {
3617 ALOGW("registerEffect() unknown io %d", io);
3618 return INVALID_OPERATION;
3619 }
Eric Laurente552edb2014-03-10 17:42:56 -07003620 }
3621 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003622 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3623 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3624 || strategy == PRODUCT_STRATEGY_NONE));
3625 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003626}
3627
Eric Laurentc241b0d2018-11-28 09:08:49 -08003628status_t AudioPolicyManager::unregisterEffect(int id)
3629{
3630 if (mEffects.getEffect(id) == nullptr) {
3631 return INVALID_OPERATION;
3632 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003633 if (mEffects.isEffectEnabled(id)) {
3634 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3635 setEffectEnabled(id, false);
3636 }
3637 return mEffects.unregisterEffect(id);
3638}
3639
3640status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3641{
3642 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3643 if (effect == nullptr) {
3644 return INVALID_OPERATION;
3645 }
3646
3647 status_t status = mEffects.setEffectEnabled(id, enabled);
3648 if (status == NO_ERROR) {
3649 mInputs.trackEffectEnabled(effect, enabled);
3650 }
3651 return status;
3652}
3653
Eric Laurent6c796322019-04-09 14:13:17 -07003654
3655status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3656{
3657 mEffects.moveEffects(ids, io);
3658 return NO_ERROR;
3659}
3660
Eric Laurentc75307b2015-03-17 15:29:32 -07003661bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3662{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003663 auto vs = toVolumeSource(stream, false);
3664 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003665}
3666
3667bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3668{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003669 auto vs = toVolumeSource(stream, false);
3670 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003671}
3672
Eric Laurente0720872014-03-11 09:30:41 -07003673bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003674{
3675 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003676 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003677 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003678 return true;
3679 }
3680 }
3681 return false;
3682}
3683
Eric Laurent275e8e92014-11-30 15:14:47 -08003684// Register a list of custom mixes with their attributes and format.
3685// When a mix is registered, corresponding input and output profiles are
3686// added to the remote submix hw module. The profile contains only the
3687// parameters (sampling rate, format...) specified by the mix.
3688// The corresponding input remote submix device is also connected.
3689//
3690// When a remote submix device is connected, the address is checked to select the
3691// appropriate profile and the corresponding input or output stream is opened.
3692//
3693// When capture starts, getInputForAttr() will:
3694// - 1 look for a mix matching the address passed in attribtutes tags if any
3695// - 2 if none found, getDeviceForInputSource() will:
3696// - 2.1 look for a mix matching the attributes source
3697// - 2.2 if none found, default to device selection by policy rules
3698// At this time, the corresponding output remote submix device is also connected
3699// and active playback use cases can be transferred to this mix if needed when reconnecting
3700// after AudioTracks are invalidated
3701//
3702// When playback starts, getOutputForAttr() will:
3703// - 1 look for a mix matching the address passed in attribtutes tags if any
3704// - 2 if none found, look for a mix matching the attributes usage
3705// - 3 if none found, default to device and output selection by policy rules.
3706
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003707status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003708{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003709 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3710 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003711 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003712 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003713 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 // examine each mix's route type
3715 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003716 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003717 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3718 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3719 ALOGE("Unsupported Policy Mix %zu of %zu: "
3720 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3721 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003723 break;
3724 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003725 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3726 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003727 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003728 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3729 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003730 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003731 rSubmixModule = mHwModules.getModuleFromName(
3732 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3733 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003734 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003735 i);
3736 res = INVALID_OPERATION;
3737 break;
3738 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003740
Eric Laurent97ac8712018-07-27 18:59:02 -07003741 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003742 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003743 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003744 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003745 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3746 } else {
3747 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3748 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003749 }
François Gaffie036e1e92015-03-19 10:16:24 +01003750
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003751 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003752 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003753 res = INVALID_OPERATION;
3754 break;
3755 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003756 audio_config_t outputConfig = mix.mFormat;
3757 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003758 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3759 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003760 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3761 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003762 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003763 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3764 audio_is_linear_pcm(outputConfig.format)
3765 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003766 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003767 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3768 audio_is_linear_pcm(inputConfig.format)
3769 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003770
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003771 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003773 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003774 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003775 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003776 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003777 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003778 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3779 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003780 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003781 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003782 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003783
3784 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3785 mix.mDeviceType, mix.mDeviceAddress,
3786 String8(), AUDIO_FORMAT_DEFAULT);
3787 if (device == nullptr) {
3788 res = INVALID_OPERATION;
3789 break;
3790 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003792 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003793 // First try to find an already opened output supporting the device
3794 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003795 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003796
Eric Laurentc529cf62020-04-17 18:19:10 -07003797 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003798 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003799 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003800 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003801 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003802 } else {
3803 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003804 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 }
3806 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003807 // If no output found, try to find a direct output profile supporting the device
3808 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3809 sp<HwModule> module = mHwModules[i];
3810 for (size_t j = 0;
3811 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3812 j++) {
3813 sp<IOProfile> profile = module->getOutputProfiles()[j];
3814 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3815 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3816 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003817 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003818 res = INVALID_OPERATION;
3819 } else {
3820 foundOutput = true;
3821 }
3822 }
3823 }
3824 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003825 if (res != NO_ERROR) {
3826 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003827 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003828 res = INVALID_OPERATION;
3829 break;
3830 } else if (!foundOutput) {
3831 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003832 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003833 res = INVALID_OPERATION;
3834 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003835 } else {
3836 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003837 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003838 }
Eric Laurentc722f302014-12-10 11:21:49 -08003839 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003840 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003841 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003842 if (audio_flags::audio_mix_ownership()) {
3843 // Only unregister mixes that were actually registered to not accidentally unregister
3844 // mixes that already existed previously.
3845 unregisterPolicyMixes(registeredMixes);
3846 registeredMixes.clear();
3847 } else {
3848 unregisterPolicyMixes(mixes);
3849 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003850 } else if (checkOutputs) {
3851 checkForDeviceAndOutputChanges();
3852 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003853 }
3854 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003855}
3856
3857status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3858{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003859 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Marvin Raminabd9b892023-11-17 16:36:27 +01003860 status_t endResult = NO_ERROR;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003861 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003862 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 sp<HwModule> rSubmixModule;
3864 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003865 for (const auto& mix : mixes) {
3866 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003867
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003868 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003869 rSubmixModule = mHwModules.getModuleFromName(
3870 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3871 if (rSubmixModule == 0) {
3872 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003873 endResult = INVALID_OPERATION;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003874 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003875 }
3876 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003877
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003878 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003879
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003880 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003881 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003882 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 continue;
3884 }
3885
Kevin Rocard04ed0462019-05-02 17:53:24 -07003886 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003887 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003888 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3889 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003890 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003891 AUDIO_FORMAT_DEFAULT);
3892 if (res != OK) {
3893 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003894 "with type %d, address %s", device, address.c_str());
Marvin Raminabd9b892023-11-17 16:36:27 +01003895 endResult = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003896 }
3897 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003898 }
jiabin5740f082019-08-19 15:08:30 -07003899 rSubmixModule->removeOutputProfile(address.c_str());
3900 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003901
Kevin Rocard153f92d2018-12-18 18:33:28 -08003902 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003903 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003904 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003905 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003906 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003907 } else {
3908 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003909 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003910 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003911 }
Marvin Raminabd9b892023-11-17 16:36:27 +01003912 if (audio_flags::audio_mix_ownership()) {
3913 res = endResult;
3914 if (res == NO_ERROR && checkOutputs) {
3915 checkForDeviceAndOutputChanges();
3916 updateCallAndOutputRouting();
3917 }
3918 } else {
3919 if (res == NO_ERROR && checkOutputs) {
3920 checkForDeviceAndOutputChanges();
3921 updateCallAndOutputRouting();
3922 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003923 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003924 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003925}
3926
Marvin Raminbdefaf02023-11-01 09:10:32 +01003927status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3928 if (!audio_flags::audio_mix_test_api()) {
3929 return INVALID_OPERATION;
3930 }
3931
3932 _aidl_return.clear();
3933 _aidl_return.reserve(mPolicyMixes.size());
3934 for (const auto &policyMix: mPolicyMixes) {
3935 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3936 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3937 policyMix->mCbFlags);
3938 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003939 _aidl_return.back().mToken = policyMix->mToken;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003940 }
3941
3942 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3943 return OK;
3944}
3945
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003946status_t AudioPolicyManager::updatePolicyMix(
3947 const AudioMix& mix,
3948 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3949 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3950 if (res == NO_ERROR) {
3951 checkForDeviceAndOutputChanges();
3952 updateCallAndOutputRouting();
3953 }
3954 return res;
3955}
3956
Mikhail Naganov100f0122018-11-29 11:22:16 -08003957void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3958{
3959 size_t i = 0;
3960 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3961 for (const auto& fmt : mManualSurroundFormats) {
3962 if (i++ != 0) dst->append(", ");
3963 std::string sfmt;
3964 FormatConverter::toString(fmt, sfmt);
3965 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3966 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3967 }
3968}
3969
Eric Laurentc529cf62020-04-17 18:19:10 -07003970// Returns true if all devices types match the predicate and are supported by one HW module
3971bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003972 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003973 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003974 const char *context,
3975 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003976 for (size_t i = 0; i < devices.size(); i++) {
3977 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003978 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003979 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003980 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003981 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003982 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003983 return false;
3984 }
3985 }
3986 return true;
3987}
3988
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003989void AudioPolicyManager::changeOutputDevicesMuteState(
3990 const AudioDeviceTypeAddrVector& devices) {
3991 ALOGVV("%s() num devices %zu", __func__, devices.size());
3992
3993 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3994 getSoftwareOutputsForDevices(devices);
3995
3996 for (size_t i = 0; i < outputs.size(); i++) {
3997 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3998 DeviceVector prevDevices = outputDesc->devices();
3999 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4000 }
4001}
4002
4003std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4004 const AudioDeviceTypeAddrVector& devices) const
4005{
4006 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4007 DeviceVector deviceDescriptors;
4008 for (size_t j = 0; j < devices.size(); j++) {
4009 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4010 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4011 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4012 ALOGE("%s: device type %#x address %s not supported or not an output device",
4013 __func__, devices[j].mType, devices[j].getAddress());
4014 continue;
4015 }
4016 deviceDescriptors.add(desc);
4017 }
4018 for (size_t i = 0; i < mOutputs.size(); i++) {
4019 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4020 continue;
4021 }
4022 outputs.push_back(mOutputs.valueAt(i));
4023 }
4024 return outputs;
4025}
4026
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004027status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004028 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004029 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004030 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4031 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004032 }
4033 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004034 if (res != NO_ERROR) {
4035 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4036 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004037 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004038
4039 checkForDeviceAndOutputChanges();
4040 updateCallAndOutputRouting();
4041
4042 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004043}
4044
4045status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4046 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004047 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4048 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004049 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004050 __FUNCTION__, uid);
4051 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004052 }
4053
Eric Laurentc529cf62020-04-17 18:19:10 -07004054 checkForDeviceAndOutputChanges();
4055 updateCallAndOutputRouting();
4056
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004057 return res;
4058}
4059
Eric Laurent2517af32020-11-25 15:31:27 +01004060
jiabin0a488932020-08-07 17:32:40 -07004061status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4062 device_role_t role,
4063 const AudioDeviceTypeAddrVector &devices) {
4064 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4065 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004066
Eric Laurentc529cf62020-04-17 18:19:10 -07004067 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004068 return BAD_VALUE;
4069 }
jiabin0a488932020-08-07 17:32:40 -07004070 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004071 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004072 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4073 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004074 return status;
4075 }
4076
4077 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004078
4079 bool forceVolumeReeval = false;
4080 // FIXME: workaround for truncated touch sounds
4081 // to be removed when the problem is handled by system UI
4082 uint32_t delayMs = 0;
4083 if (strategy == mCommunnicationStrategy) {
4084 forceVolumeReeval = true;
4085 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4086 updateInputRouting();
4087 }
4088 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004089
4090 return NO_ERROR;
4091}
4092
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004093void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4094 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004095{
4096 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004097 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004098 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004099 // Only apply special touch sound delay once
4100 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004101 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004102 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004103 for (size_t i = 0; i < mOutputs.size(); i++) {
4104 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4105 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004106 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4107 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004108 // As done in setDeviceConnectionState, we could also fix default device issue by
4109 // preventing the force re-routing in case of default dev that distinguishes on address.
4110 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004111 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004112 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4113 // If the device is using preferred mixer attributes, the output need to reopen
4114 // with default configuration when the new selected devices are different from
4115 // current routing devices.
4116 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4117 continue;
4118 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304119
4120 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4121 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004122 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004123 // Only apply special touch sound delay once
4124 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004125 }
4126 if (forceVolumeReeval && !newDevices.isEmpty()) {
4127 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4128 }
4129 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004130 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004131 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004132}
4133
Eric Laurent2517af32020-11-25 15:31:27 +01004134void AudioPolicyManager::updateInputRouting() {
4135 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304136 // Skip for hotword recording as the input device switch
4137 // is handled within sound trigger HAL
4138 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4139 continue;
4140 }
Eric Laurent2517af32020-11-25 15:31:27 +01004141 auto newDevice = getNewInputDevice(activeDesc);
4142 // Force new input selection if the new device can not be reached via current input
4143 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4144 setInputDevice(activeDesc->mIoHandle, newDevice);
4145 } else {
4146 closeInput(activeDesc->mIoHandle);
4147 }
4148 }
4149}
4150
Paul Wang5d7cdb52022-11-22 09:45:06 +00004151status_t
4152AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4153 device_role_t role,
4154 const AudioDeviceTypeAddrVector &devices) {
4155 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4156 dumpAudioDeviceTypeAddrVector(devices).c_str());
4157
Eric Laurent78fedbf2023-03-09 14:40:44 +01004158 if (!areAllDevicesSupported(
4159 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004160 return BAD_VALUE;
4161 }
4162 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4163 if (status != NO_ERROR) {
4164 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4165 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4166 return status;
4167 }
4168
4169 checkForDeviceAndOutputChanges();
4170
4171 bool forceVolumeReeval = false;
4172 // TODO(b/263479999): workaround for truncated touch sounds
4173 // to be removed when the problem is handled by system UI
4174 uint32_t delayMs = 0;
4175 if (strategy == mCommunnicationStrategy) {
4176 forceVolumeReeval = true;
4177 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4178 updateInputRouting();
4179 }
4180 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4181
4182 return NO_ERROR;
4183}
4184
4185status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4186 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004187{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004188 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004189
Paul Wang5d7cdb52022-11-22 09:45:06 +00004190 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004191 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004192 ALOGW_IF(status != NAME_NOT_FOUND,
4193 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004194 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004195 return status;
4196 }
4197
4198 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004199
4200 bool forceVolumeReeval = false;
4201 // FIXME: workaround for truncated touch sounds
4202 // to be removed when the problem is handled by system UI
4203 uint32_t delayMs = 0;
4204 if (strategy == mCommunnicationStrategy) {
4205 forceVolumeReeval = true;
4206 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4207 updateInputRouting();
4208 }
4209 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004210
4211 return NO_ERROR;
4212}
4213
jiabin0a488932020-08-07 17:32:40 -07004214status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4215 device_role_t role,
4216 AudioDeviceTypeAddrVector &devices) {
4217 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004218}
4219
Jiabin Huang3b98d322020-09-03 17:54:16 +00004220status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4221 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4222 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4223 dumpAudioDeviceTypeAddrVector(devices).c_str());
4224
Mikhail Naganov55773032020-10-01 15:08:13 -07004225 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004226 return BAD_VALUE;
4227 }
4228 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4229 ALOGW_IF(status != NO_ERROR,
4230 "Engine could not set preferred devices %s for audio source %d role %d",
4231 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4232
4233 return status;
4234}
4235
4236status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4237 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4238 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4239 dumpAudioDeviceTypeAddrVector(devices).c_str());
4240
Mikhail Naganov55773032020-10-01 15:08:13 -07004241 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004242 return BAD_VALUE;
4243 }
4244 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4245 ALOGW_IF(status != NO_ERROR,
4246 "Engine could not add preferred devices %s for audio source %d role %d",
4247 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4248
Eric Laurent2517af32020-11-25 15:31:27 +01004249 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004250 return status;
4251}
4252
4253status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4254 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4255{
4256 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4257 dumpAudioDeviceTypeAddrVector(devices).c_str());
4258
Eric Laurent78fedbf2023-03-09 14:40:44 +01004259 if (!areAllDevicesSupported(
4260 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004261 return BAD_VALUE;
4262 }
4263
4264 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4265 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004266 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004267 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004268 if (status == NO_ERROR) {
4269 updateInputRouting();
4270 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004271 return status;
4272}
4273
4274status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4275 device_role_t role) {
4276 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4277
4278 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004279 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004280 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004281 if (status == NO_ERROR) {
4282 updateInputRouting();
4283 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004284 return status;
4285}
4286
4287status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4288 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4289 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4290}
4291
Oscar Azucena90e77632019-11-27 17:12:28 -08004292status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004293 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004294 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004295 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4296 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004297 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004298 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4299 if (status != NO_ERROR) {
4300 ALOGE("%s() could not set device affinity for userId %d",
4301 __FUNCTION__, userId);
4302 return status;
4303 }
4304
4305 // reevaluate outputs for all devices
4306 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004307 changeOutputDevicesMuteState(devices);
4308 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4309 true /* skipDelays */);
4310 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004311
4312 return NO_ERROR;
4313}
4314
4315status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004316 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004317 AudioDeviceTypeAddrVector devices;
4318 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004319 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4320 if (status != NO_ERROR) {
4321 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4322 __FUNCTION__, userId);
4323 return status;
4324 }
4325
4326 // reevaluate outputs for all devices
4327 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004328 changeOutputDevicesMuteState(devices);
4329 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4330 true /* skipDelays */);
4331 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004332
4333 return NO_ERROR;
4334}
4335
Andy Hungc29d82b2018-10-05 12:23:17 -07004336void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004337{
Andy Hungc29d82b2018-10-05 12:23:17 -07004338 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004339 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004340 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004341 std::string stateLiteral;
4342 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004343 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004344 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4345 "communications", "media", "record", "dock", "system",
4346 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4347 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4348 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004349 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4350 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4351 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4352 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4353 dst->append(" (MANUAL: ");
4354 dumpManualSurroundFormats(dst);
4355 dst->append(")");
4356 }
4357 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004358 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004359 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4360 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004361 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004362 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004363
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004364 dst->append("\n");
4365 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4366 dst->append("\n");
4367 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004368 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004369 mOutputs.dump(dst);
4370 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004371 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004372 mAudioPatches.dump(dst);
4373 mPolicyMixes.dump(dst);
4374 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004375
Kevin Rocardb99cc752019-03-21 20:52:24 -07004376 dst->appendFormat(" AllowedCapturePolicies:\n");
4377 for (auto& policy : mAllowedCapturePolicies) {
4378 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4379 }
4380
jiabina84c3d32022-12-02 18:59:55 +00004381 dst->appendFormat(" Preferred mixer audio configuration:\n");
4382 for (const auto it : mPreferredMixerAttrInfos) {
4383 dst->appendFormat(" - device port id: %d\n", it.first);
4384 for (const auto preferredMixerInfoIt : it.second) {
4385 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4386 preferredMixerInfoIt.second->dump(dst);
4387 }
4388 }
4389
François Gaffiec005e562018-11-06 15:04:49 +01004390 dst->appendFormat("\nPolicy Engine dump:\n");
4391 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004392}
4393
4394status_t AudioPolicyManager::dump(int fd)
4395{
4396 String8 result;
4397 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004398 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004399 return NO_ERROR;
4400}
4401
Kevin Rocardb99cc752019-03-21 20:52:24 -07004402status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4403{
4404 mAllowedCapturePolicies[uid] = capturePolicy;
4405 return NO_ERROR;
4406}
4407
Eric Laurente552edb2014-03-10 17:42:56 -07004408// This function checks for the parameters which can be offloaded.
4409// This can be enhanced depending on the capability of the DSP and policy
4410// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004411audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004412{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004413 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004414 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004415 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004416 offloadInfo.format,
4417 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4418 offloadInfo.has_video);
4419
jiabin2b9d5a12021-12-10 01:06:29 +00004420 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004421 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004422 }
4423
4424 // See if there is a profile to support this.
4425 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004426 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004427 offloadInfo.sample_rate,
4428 offloadInfo.format,
4429 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004430 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4431 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004432 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4433 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4434 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004435 if (profile == nullptr) {
4436 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4437 }
4438 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4439 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4440 }
4441 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004442}
4443
Michael Chana94fbb22018-04-24 14:31:19 +10004444bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4445 const audio_attributes_t& attributes) {
4446 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004447 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004448 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4449 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004450 config.sample_rate,
4451 config.format,
4452 config.channel_mask,
4453 output_flags,
4454 true /* directOnly */);
4455 ALOGV("%s() profile %sfound with name: %s, "
4456 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4457 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004458 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004459 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004460
4461 // also try the MSD module if compatible profile not found
4462 if (profile == nullptr) {
4463 profile = getMsdProfileForOutput(outputDevices,
4464 config.sample_rate,
4465 config.format,
4466 config.channel_mask,
4467 output_flags,
4468 true /* directOnly */);
4469 ALOGV("%s() MSD profile %sfound with name: %s, "
4470 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4471 __FUNCTION__, profile != 0 ? "" : "NOT ",
4472 (profile != 0 ? profile->getTagName().c_str() : "null"),
4473 config.sample_rate, config.format, config.channel_mask, output_flags);
4474 }
4475 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004476}
4477
jiabin2b9d5a12021-12-10 01:06:29 +00004478bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4479 bool durationIgnored) {
4480 if (mMasterMono) {
4481 return false; // no offloading if mono is set.
4482 }
4483
4484 // Check if offload has been disabled
4485 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4486 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4487 return false;
4488 }
4489
4490 // Check if stream type is music, then only allow offload as of now.
4491 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4492 {
4493 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4494 return false;
4495 }
4496
4497 //TODO: enable audio offloading with video when ready
4498 const bool allowOffloadWithVideo =
4499 property_get_bool("audio.offload.video", false /* default_value */);
4500 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4501 ALOGV("%s: has_video == true, returning false", __func__);
4502 return false;
4503 }
4504
4505 //If duration is less than minimum value defined in property, return false
4506 const int min_duration_secs = property_get_int32(
4507 "audio.offload.min.duration.secs", -1 /* default_value */);
4508 if (!durationIgnored) {
4509 if (min_duration_secs >= 0) {
4510 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4511 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4512 __func__, min_duration_secs);
4513 return false;
4514 }
4515 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4516 ALOGV("%s: Offload denied by duration < default min(=%u)",
4517 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4518 return false;
4519 }
4520 }
4521
4522 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4523 // creating an offloaded track and tearing it down immediately after start when audioflinger
4524 // detects there is an active non offloadable effect.
4525 // FIXME: We should check the audio session here but we do not have it in this context.
4526 // This may prevent offloading in rare situations where effects are left active by apps
4527 // in the background.
4528 if (mEffects.isNonOffloadableEffectEnabled()) {
4529 return false;
4530 }
4531
4532 return true;
4533}
4534
4535audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4536 const audio_config_t *config) {
4537 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4538 offloadInfo.format = config->format;
4539 offloadInfo.sample_rate = config->sample_rate;
4540 offloadInfo.channel_mask = config->channel_mask;
4541 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4542 offloadInfo.has_video = false;
4543 offloadInfo.is_streaming = false;
4544 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4545
4546 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4547 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4548 audio_flags_to_audio_output_flags(attr->flags, &flags);
4549 // only retain flags that will drive compressed offload or passthrough
4550 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4551 if (offloadPossible) {
4552 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4553 }
4554 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4555
Dorin Drimusfae3c642022-03-17 18:36:30 +01004556 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004557 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004558 DeviceVector outputDevices = engineOutputDevices;
4559 // the MSD module checks for different conditions and output devices
4560 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4561 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4562 continue;
4563 }
4564 outputDevices = getMsdAudioOutDevices();
4565 }
jiabin2b9d5a12021-12-10 01:06:29 +00004566 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004567 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004568 config->sample_rate, nullptr /*updatedSamplingRate*/,
4569 config->format, nullptr /*updatedFormat*/,
4570 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004571 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004572 continue;
4573 }
4574 // reject profiles not corresponding to a device currently available
4575 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4576 continue;
4577 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004578 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4579 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004580 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004581 != AUDIO_DIRECT_NOT_SUPPORTED) {
4582 // Already reports offload gapless supported. No need to report offload support.
4583 continue;
4584 }
4585 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4586 != AUDIO_OUTPUT_FLAG_NONE) {
4587 // If offload gapless is reported, no need to report offload support.
4588 directMode = (audio_direct_mode_t) ((directMode &
4589 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4590 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4591 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004592 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004593 }
4594 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004595 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004596 }
4597 }
4598 }
4599 return directMode;
4600}
4601
Dorin Drimusf2196d82022-01-03 12:11:18 +01004602status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4603 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004604 if (mEffects.isNonOffloadableEffectEnabled()) {
4605 return OK;
4606 }
jiabinf1c73972022-04-14 16:28:52 -07004607 DeviceVector devices;
4608 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004609 if (status != OK) {
4610 return status;
4611 }
4612 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4613 if (devices.empty()) {
4614 return OK; // no output devices for the attributes
4615 }
jiabinf1c73972022-04-14 16:28:52 -07004616 return getProfilesForDevices(devices, audioProfilesVector,
4617 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004618}
4619
jiabina84c3d32022-12-02 18:59:55 +00004620status_t AudioPolicyManager::getSupportedMixerAttributes(
4621 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4622 ALOGV("%s, portId=%d", __func__, portId);
4623 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4624 if (deviceDescriptor == nullptr) {
4625 ALOGE("%s the requested device is currently unavailable", __func__);
4626 return BAD_VALUE;
4627 }
jiabin96daffc2023-05-11 17:51:55 +00004628 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4629 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4630 deviceDescriptor->type());
4631 return BAD_VALUE;
4632 }
jiabina84c3d32022-12-02 18:59:55 +00004633 for (const auto& hwModule : mHwModules) {
4634 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4635 if (curProfile->supportsDevice(deviceDescriptor)) {
4636 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4637 }
4638 }
4639 }
4640 return NO_ERROR;
4641}
4642
4643status_t AudioPolicyManager::setPreferredMixerAttributes(
4644 const audio_attributes_t *attr,
4645 audio_port_handle_t portId,
4646 uid_t uid,
4647 const audio_mixer_attributes_t *mixerAttributes) {
4648 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4649 "mixerBehavior=%d}, uid=%d, portId=%u",
4650 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4651 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4652 mixerAttributes->mixer_behavior, uid, portId);
4653 if (attr->usage != AUDIO_USAGE_MEDIA) {
4654 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4655 return BAD_VALUE;
4656 }
4657 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4658 if (deviceDescriptor == nullptr) {
4659 ALOGE("%s the requested device is currently unavailable", __func__);
4660 return BAD_VALUE;
4661 }
4662 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4663 ALOGE("%s(%d), type=%d, is not a usb output device",
4664 __func__, portId, deviceDescriptor->type());
4665 return BAD_VALUE;
4666 }
4667
4668 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4669 audio_flags_to_audio_output_flags(attr->flags, &flags);
4670 flags = (audio_output_flags_t) (flags |
4671 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4672 sp<IOProfile> profile = nullptr;
4673 DeviceVector devices(deviceDescriptor);
4674 for (const auto& hwModule : mHwModules) {
4675 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4676 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004677 && curProfile->getCompatibilityScore(
4678 devices,
4679 mixerAttributes->config.sample_rate,
4680 nullptr /*updatedSamplingRate*/,
4681 mixerAttributes->config.format,
4682 nullptr /*updatedFormat*/,
4683 mixerAttributes->config.channel_mask,
4684 nullptr /*updatedChannelMask*/,
4685 flags,
4686 false /*exactMatchRequiredForInputFlags*/)
4687 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004688 profile = curProfile;
4689 break;
4690 }
4691 }
4692 }
4693 if (profile == nullptr) {
4694 ALOGE("%s, there is no compatible profile found", __func__);
4695 return BAD_VALUE;
4696 }
4697
4698 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4699 sp<PreferredMixerAttributesInfo>::make(
4700 uid, portId, profile, flags, *mixerAttributes);
4701 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4702 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4703
4704 // If 1) there is any client from the preferred mixer configuration owner that is currently
4705 // active and matches the strategy and 2) current output is on the preferred device and the
4706 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4707 // configuration.
4708 std::vector<audio_io_handle_t> outputsToReopen;
4709 for (size_t i = 0; i < mOutputs.size(); i++) {
4710 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004711 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4712 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4713 output->mUsePreferredMixerAttributes = true;
4714 } else {
4715 for (const auto &client: output->getActiveClients()) {
4716 if (client->uid() == uid && client->strategy() == strategy) {
4717 client->setIsInvalid();
4718 outputsToReopen.push_back(output->mIoHandle);
4719 }
jiabina84c3d32022-12-02 18:59:55 +00004720 }
4721 }
4722 }
4723 }
4724 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4725 config.sample_rate = mixerAttributes->config.sample_rate;
4726 config.channel_mask = mixerAttributes->config.channel_mask;
4727 config.format = mixerAttributes->config.format;
4728 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004729 sp<SwAudioOutputDescriptor> desc =
4730 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4731 if (desc == nullptr) {
4732 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4733 continue;
4734 }
4735 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004736 }
4737
4738 return NO_ERROR;
4739}
4740
4741sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004742 audio_port_handle_t devicePortId,
4743 product_strategy_t strategy,
4744 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004745 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4746 if (it == mPreferredMixerAttrInfos.end()) {
4747 return nullptr;
4748 }
jiabind9a58d32023-06-01 17:57:30 +00004749 if (activeBitPerfectPreferred) {
4750 for (auto [strategy, info] : it->second) {
4751 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4752 && info->getActiveClientCount() != 0) {
4753 return info;
4754 }
4755 }
jiabina84c3d32022-12-02 18:59:55 +00004756 }
jiabind9a58d32023-06-01 17:57:30 +00004757 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4758 return strategyMatchedMixerAttrInfoIt == it->second.end()
4759 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004760}
4761
4762status_t AudioPolicyManager::getPreferredMixerAttributes(
4763 const audio_attributes_t *attr,
4764 audio_port_handle_t portId,
4765 audio_mixer_attributes_t* mixerAttributes) {
4766 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4767 portId, mEngine->getProductStrategyForAttributes(*attr));
4768 if (info == nullptr) {
4769 return NAME_NOT_FOUND;
4770 }
4771 *mixerAttributes = info->getMixerAttributes();
4772 return NO_ERROR;
4773}
4774
4775status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4776 audio_port_handle_t portId,
4777 uid_t uid) {
4778 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4779 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4780 if (preferredMixerAttrInfo == nullptr) {
4781 return NAME_NOT_FOUND;
4782 }
4783 if (preferredMixerAttrInfo->getUid() != uid) {
4784 ALOGE("%s, requested uid=%d, owned uid=%d",
4785 __func__, uid, preferredMixerAttrInfo->getUid());
4786 return PERMISSION_DENIED;
4787 }
4788 mPreferredMixerAttrInfos[portId].erase(strategy);
4789 if (mPreferredMixerAttrInfos[portId].empty()) {
4790 mPreferredMixerAttrInfos.erase(portId);
4791 }
4792
4793 // Reconfig existing output
4794 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4795 for (size_t i = 0; i < mOutputs.size(); i++) {
4796 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4797 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4798 }
4799 }
4800 for (const auto output : potentialOutputsToReopen) {
4801 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4802 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4803 preferredMixerAttrInfo->getFlags())) {
4804 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4805 }
4806 }
4807 return NO_ERROR;
4808}
4809
Eric Laurent6a94d692014-05-20 11:18:06 -07004810status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4811 audio_port_type_t type,
4812 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004813 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 unsigned int *generation)
4815{
jiabin19cdba52020-11-24 11:28:58 -08004816 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4817 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 return BAD_VALUE;
4819 }
4820 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004821 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004822 *num_ports = 0;
4823 }
4824
4825 size_t portsWritten = 0;
4826 size_t portsMax = *num_ports;
4827 *num_ports = 0;
4828 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004829 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4830 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004832 for (const auto& dev : mAvailableOutputDevices) {
4833 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004834 continue;
4835 }
4836 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004837 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004838 }
4839 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 }
4842 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004843 for (const auto& dev : mAvailableInputDevices) {
4844 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004845 continue;
4846 }
4847 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004848 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004849 }
4850 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004852 }
4853 }
4854 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4855 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4856 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4857 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4858 }
4859 *num_ports += mInputs.size();
4860 }
4861 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004862 size_t numOutputs = 0;
4863 for (size_t i = 0; i < mOutputs.size(); i++) {
4864 if (!mOutputs[i]->isDuplicated()) {
4865 numOutputs++;
4866 if (portsWritten < portsMax) {
4867 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4868 }
4869 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004870 }
Eric Laurent84c70242014-06-23 08:46:27 -07004871 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 }
4873 }
jiabina84c3d32022-12-02 18:59:55 +00004874
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004876 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 return NO_ERROR;
4878}
4879
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004880status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4881 std::vector<media::AudioPortFw>* _aidl_return) {
4882 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4883 audio_port_v7 port;
4884 dev->toAudioPort(&port);
4885 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4886 _aidl_return->push_back(std::move(aidlPort));
4887 return OK;
4888 };
4889
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004890 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004891 for (const auto& dev : module->getDeclaredDevices()) {
4892 if (role == media::AudioPortRole::NONE ||
4893 ((role == media::AudioPortRole::SOURCE)
4894 == audio_is_input_device(dev->type()))) {
4895 RETURN_STATUS_IF_ERROR(pushPort(dev));
4896 }
4897 }
4898 }
4899 return OK;
4900}
4901
jiabin19cdba52020-11-24 11:28:58 -08004902status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004903{
Eric Laurent99fcae42018-05-17 16:59:18 -07004904 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4905 return BAD_VALUE;
4906 }
4907 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4908 if (dev != 0) {
4909 dev->toAudioPort(port);
4910 return NO_ERROR;
4911 }
4912 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4913 if (dev != 0) {
4914 dev->toAudioPort(port);
4915 return NO_ERROR;
4916 }
4917 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4918 if (out != 0) {
4919 out->toAudioPort(port);
4920 return NO_ERROR;
4921 }
4922 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4923 if (in != 0) {
4924 in->toAudioPort(port);
4925 return NO_ERROR;
4926 }
4927 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004928}
4929
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004930status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4931 audio_patch_handle_t *handle,
4932 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004933{
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 if (handle == NULL || patch == NULL) {
4936 return BAD_VALUE;
4937 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004938 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004939 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004940 return BAD_VALUE;
4941 }
4942 // only one source per audio patch supported for now
4943 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004944 return INVALID_OPERATION;
4945 }
Eric Laurent874c42872014-08-08 15:13:39 -07004946 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 return INVALID_OPERATION;
4948 }
Eric Laurent874c42872014-08-08 15:13:39 -07004949 for (size_t i = 0; i < patch->num_sinks; i++) {
4950 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4951 return INVALID_OPERATION;
4952 }
4953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004954
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004955 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4956 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4957 if (srcDevice == nullptr || sinkDevice == nullptr) {
4958 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4959 return BAD_VALUE;
4960 }
4961 ALOGV("%s between source %s and sink %s", __func__,
4962 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4963 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4964 // Default attributes, default volume priority, not to infer with non raw audio patches.
4965 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4966 const struct audio_port_config *source = &patch->sources[0];
4967 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004968 new SourceClientDescriptor(
4969 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4970 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4971 true);
4972 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004973
4974 status_t status =
4975 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4976
4977 if (status != NO_ERROR) {
4978 return INVALID_OPERATION;
4979 }
4980 mAudioSources.add(portId, sourceDesc);
4981 return NO_ERROR;
4982}
4983
4984status_t AudioPolicyManager::connectAudioSourceToSink(
4985 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4986 const struct audio_patch *patch,
4987 audio_patch_handle_t &handle,
4988 uid_t uid, uint32_t delayMs)
4989{
4990 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4991 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4992 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4993 return INVALID_OPERATION;
4994 }
4995 sourceDesc->connect(handle, sinkDevice);
4996 if (isMsdPatch(handle)) {
4997 return NO_ERROR;
4998 }
4999 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5000 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5001 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5002 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5003 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5004 goto FailurePatchAdded;
5005 }
5006 status = swOutput->start();
5007 if (status != NO_ERROR) {
5008 goto FailureSourceAdded;
5009 }
5010 swOutput->addClient(sourceDesc);
5011 status = startSource(swOutput, sourceDesc, &delayMs);
5012 if (status != NO_ERROR) {
5013 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5014 goto FailureSourceActive;
5015 }
5016 if (delayMs != 0) {
5017 usleep(delayMs * 1000);
5018 }
5019 return NO_ERROR;
5020
5021FailureSourceActive:
5022 swOutput->stop();
5023 releaseOutput(sourceDesc->portId());
5024FailureSourceAdded:
5025 sourceDesc->setSwOutput(nullptr);
5026FailurePatchAdded:
5027 releaseAudioPatchInternal(handle);
5028 return INVALID_OPERATION;
5029}
5030
5031status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5032 audio_patch_handle_t *handle,
5033 uid_t uid, uint32_t delayMs,
5034 const sp<SourceClientDescriptor>& sourceDesc)
5035{
5036 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 sp<AudioPatch> patchDesc;
5038 ssize_t index = mAudioPatches.indexOfKey(*handle);
5039
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5041 patch->sources[0].role,
5042 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005043#if LOG_NDEBUG == 0
5044 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5046 patch->sinks[i].role,
5047 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005048 }
5049#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005050
5051 if (index >= 0) {
5052 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005053 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5054 __func__, mUidCached, patchDesc->getUid(), uid);
5055 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 return INVALID_OPERATION;
5057 }
5058 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005059 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 }
5061
5062 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005063 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 return BAD_VALUE;
5067 }
Eric Laurent84c70242014-06-23 08:46:27 -07005068 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5069 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 if (patchDesc != 0) {
5071 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005072 ALOGV("%s source id differs for patch current id %d new id %d",
5073 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 return BAD_VALUE;
5075 }
5076 }
Eric Laurent874c42872014-08-08 15:13:39 -07005077 DeviceVector devices;
5078 for (size_t i = 0; i < patch->num_sinks; i++) {
5079 // Only support mix to devices connection
5080 // TODO add support for mix to mix connection
5081 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005082 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005083 return INVALID_OPERATION;
5084 }
5085 sp<DeviceDescriptor> devDesc =
5086 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5087 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005088 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005089 return BAD_VALUE;
5090 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005091
jiabin66acc432024-02-06 00:57:36 +00005092 if (outputDesc->mProfile->getCompatibilityScore(
5093 DeviceVector(devDesc),
5094 patch->sources[0].sample_rate,
5095 nullptr, // updatedSamplingRate
5096 patch->sources[0].format,
5097 nullptr, // updatedFormat
5098 patch->sources[0].channel_mask,
5099 nullptr, // updatedChannelMask
5100 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005101 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005102 return INVALID_OPERATION;
5103 }
5104 devices.add(devDesc);
5105 }
5106 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 return INVALID_OPERATION;
5108 }
Eric Laurent874c42872014-08-08 15:13:39 -07005109
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005111 ALOGV("%s setting device %s on output %d",
5112 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305113 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 index = mAudioPatches.indexOfKey(*handle);
5115 if (index >= 0) {
5116 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005117 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005118 }
5119 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005120 patchDesc->setUid(uid);
5121 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005122 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005123 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 return INVALID_OPERATION;
5125 }
5126 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5127 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5128 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005129 // only one sink supported when connecting an input device to a mix
5130 if (patch->num_sinks > 1) {
5131 return INVALID_OPERATION;
5132 }
François Gaffie53615e22015-03-19 09:24:12 +01005133 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 if (inputDesc == NULL) {
5135 return BAD_VALUE;
5136 }
5137 if (patchDesc != 0) {
5138 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5139 return BAD_VALUE;
5140 }
5141 }
François Gaffie11d30102018-11-02 16:09:09 +01005142 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005144 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 return BAD_VALUE;
5146 }
5147
jiabin66acc432024-02-06 00:57:36 +00005148 if (inputDesc->mProfile->getCompatibilityScore(
5149 DeviceVector(device),
5150 patch->sinks[0].sample_rate,
5151 nullptr, /*updatedSampleRate*/
5152 patch->sinks[0].format,
5153 nullptr, /*updatedFormat*/
5154 patch->sinks[0].channel_mask,
5155 nullptr, /*updatedChannelMask*/
5156 // FIXME for the parameter type,
5157 // and the NONE
5158 (audio_output_flags_t)
5159 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005160 return INVALID_OPERATION;
5161 }
5162 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005163 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005164 device->toString().c_str(), inputDesc->mIoHandle);
5165 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005166 index = mAudioPatches.indexOfKey(*handle);
5167 if (index >= 0) {
5168 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005169 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 }
5171 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005172 patchDesc->setUid(uid);
5173 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005174 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005175 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 return INVALID_OPERATION;
5177 }
5178 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5179 // device to device connection
5180 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005181 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 return BAD_VALUE;
5183 }
5184 }
François Gaffie11d30102018-11-02 16:09:09 +01005185 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005186 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005187 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005188 return BAD_VALUE;
5189 }
Eric Laurent874c42872014-08-08 15:13:39 -07005190
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 //update source and sink with our own data as the data passed in the patch may
5192 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005193 PatchBuilder patchBuilder;
5194 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005195
5196 // if first sink is to MSD, establish single MSD patch
5197 if (getMsdAudioOutDevices().contains(
5198 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5199 ALOGV("%s patching to MSD", __FUNCTION__);
5200 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5201 goto installPatch;
5202 }
5203
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5205 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005206
Eric Laurent874c42872014-08-08 15:13:39 -07005207 for (size_t i = 0; i < patch->num_sinks; i++) {
5208 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005209 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005210 return INVALID_OPERATION;
5211 }
François Gaffie11d30102018-11-02 16:09:09 +01005212 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005213 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005214 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005215 return BAD_VALUE;
5216 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 audio_port_config sinkPortConfig = {};
5218 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5219 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005220
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005221 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5222 // volume management purpose (tracking activity)
5223 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5224 // in config XML to reach the sink so that is can be declared as available.
5225 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005226 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005227 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005228 // take care of dynamic routing for SwOutput selection,
5229 audio_attributes_t attributes = sourceDesc->attributes();
5230 audio_stream_type_t stream = sourceDesc->stream();
5231 audio_attributes_t resultAttr;
5232 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5233 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005234 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5235 config.channel_mask =
5236 (audio_channel_mask_get_representation(sourceMask)
5237 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5238 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005239 config.format = sourceDesc->config().format;
5240 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5241 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5242 bool isRequestedDeviceForExclusiveUse = false;
5243 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005244 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005245 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005246 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5247 &stream, sourceDesc->uid(), &config, &flags,
5248 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005249 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005250 if (output == AUDIO_IO_HANDLE_NONE) {
5251 ALOGV("%s no output for device %s",
5252 __FUNCTION__, sinkDevice->toString().c_str());
5253 return INVALID_OPERATION;
5254 }
5255 outputDesc = mOutputs.valueFor(output);
5256 if (outputDesc->isDuplicated()) {
5257 ALOGE("%s output is duplicated", __func__);
5258 return INVALID_OPERATION;
5259 }
François Gaffie7e39df22022-04-26 12:48:49 +02005260 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5261 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005262 } else {
5263 // Same for "raw patches" aka created from createAudioPatch API
5264 SortedVector<audio_io_handle_t> outputs =
5265 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5266 // if the sink device is reachable via an opened output stream, request to
5267 // go via this output stream by adding a second source to the patch
5268 // description
5269 output = selectOutput(outputs);
5270 if (output == AUDIO_IO_HANDLE_NONE) {
5271 ALOGE("%s no output available for internal patch sink", __func__);
5272 return INVALID_OPERATION;
5273 }
5274 outputDesc = mOutputs.valueFor(output);
5275 if (outputDesc->isDuplicated()) {
5276 ALOGV("%s output for device %s is duplicated",
5277 __func__, sinkDevice->toString().c_str());
5278 return INVALID_OPERATION;
5279 }
François Gaffie7e39df22022-04-26 12:48:49 +02005280 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005281 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005282 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005283 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005284 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005285 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005286 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5287 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005288 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5289 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005291 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005293 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005294 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005295 return INVALID_OPERATION;
5296 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005297 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005298 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005299 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005300 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005302 srcMixPortConfig.ext.mix.usecase.stream =
5303 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005304 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5305 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005306 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005307 }
Eric Laurent83b88082014-06-20 18:31:16 -07005308 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 }
5310 // TODO: check from routing capabilities in config file and other conflicting patches
5311
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005312installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005313 status_t status = installPatch(
5314 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005315 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 return INVALID_OPERATION;
5318 }
5319 } else {
5320 return BAD_VALUE;
5321 }
5322 } else {
5323 return BAD_VALUE;
5324 }
5325 return NO_ERROR;
5326}
5327
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005328status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005329{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005330 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 ssize_t index = mAudioPatches.indexOfKey(handle);
5332
5333 if (index < 0) {
5334 return BAD_VALUE;
5335 }
5336 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005337 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5338 __func__, mUidCached, patchDesc->getUid(), uid);
5339 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 return INVALID_OPERATION;
5341 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005342 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5343 for (size_t i = 0; i < mAudioSources.size(); i++) {
5344 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5345 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5346 portId = sourceDesc->portId();
5347 break;
5348 }
5349 }
5350 return portId != AUDIO_PORT_HANDLE_NONE ?
5351 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005352}
Eric Laurent6a94d692014-05-20 11:18:06 -07005353
François Gaffieafd4cea2019-11-18 15:50:22 +01005354status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005355 uint32_t delayMs,
5356 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005357{
5358 ALOGV("%s patch %d", __func__, handle);
5359 if (mAudioPatches.indexOfKey(handle) < 0) {
5360 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5361 return BAD_VALUE;
5362 }
5363 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005365 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005367 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005369 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 return BAD_VALUE;
5371 }
5372
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305373 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005374 getNewOutputDevices(outputDesc, true /*fromCache*/),
5375 true,
5376 0,
5377 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5379 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005380 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005381 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005382 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 return BAD_VALUE;
5384 }
5385 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005386 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 true,
5388 NULL);
5389 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005390 status_t status =
5391 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5392 ALOGV("%s patch panel returned %d patchHandle %d",
5393 __func__, status, patchDesc->getAfHandle());
5394 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005396 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005397 // SW or HW Bridge
5398 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5399 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005400 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005401 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5402 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5403 outputDesc = sourceDesc->swOutput().promote();
5404 }
5405 if (outputDesc == nullptr) {
5406 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5407 // releaseOutput has already called closeOutput in case of direct output
5408 return NO_ERROR;
5409 }
François Gaffie7e39df22022-04-26 12:48:49 +02005410 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005411 // While using a HwBridge, force reconsidering device only if not reusing an existing
5412 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005413 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005414 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5415 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5416 // Reconsider device only for cases:
5417 // 1 / Active Output
5418 // 2 / Inactive Output previously hosting HwBridge
5419 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5420 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5421 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305422 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005423 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5424 outputDesc->devices(),
5425 force,
5426 0,
5427 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 } else {
5429 return BAD_VALUE;
5430 }
5431 } else {
5432 return BAD_VALUE;
5433 }
5434 return NO_ERROR;
5435}
5436
5437status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5438 struct audio_patch *patches,
5439 unsigned int *generation)
5440{
François Gaffie53615e22015-03-19 09:24:12 +01005441 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 return BAD_VALUE;
5443 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005445 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005446}
5447
Eric Laurente1715a42014-05-20 11:30:42 -07005448status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005449{
Eric Laurente1715a42014-05-20 11:30:42 -07005450 ALOGV("setAudioPortConfig()");
5451
5452 if (config == NULL) {
5453 return BAD_VALUE;
5454 }
5455 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5456 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005457 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5458 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005459 }
5460
Eric Laurenta121f902014-06-03 13:32:54 -07005461 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005462 if (config->type == AUDIO_PORT_TYPE_MIX) {
5463 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005464 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005465 if (outputDesc == NULL) {
5466 return BAD_VALUE;
5467 }
Eric Laurent84c70242014-06-23 08:46:27 -07005468 ALOG_ASSERT(!outputDesc->isDuplicated(),
5469 "setAudioPortConfig() called on duplicated output %d",
5470 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005471 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005472 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005473 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005474 if (inputDesc == NULL) {
5475 return BAD_VALUE;
5476 }
Eric Laurenta121f902014-06-03 13:32:54 -07005477 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005478 } else {
5479 return BAD_VALUE;
5480 }
5481 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5482 sp<DeviceDescriptor> deviceDesc;
5483 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5484 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5485 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5486 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5487 } else {
5488 return BAD_VALUE;
5489 }
5490 if (deviceDesc == NULL) {
5491 return BAD_VALUE;
5492 }
Eric Laurenta121f902014-06-03 13:32:54 -07005493 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005494 } else {
5495 return BAD_VALUE;
5496 }
5497
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005498 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005499 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5500 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005501 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005502 audioPortConfig->toAudioPortConfig(&newConfig, config);
5503 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005504 }
Eric Laurenta121f902014-06-03 13:32:54 -07005505 if (status != NO_ERROR) {
5506 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005507 }
Eric Laurente1715a42014-05-20 11:30:42 -07005508
5509 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005510}
5511
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005512void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5513{
Eric Laurentd60560a2015-04-10 11:31:20 -07005514 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005515 clearAudioPatches(uid);
5516 clearSessionRoutes(uid);
5517}
5518
Eric Laurent6a94d692014-05-20 11:18:06 -07005519void AudioPolicyManager::clearAudioPatches(uid_t uid)
5520{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005521 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005522 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005523 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005524 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 }
5526 }
5527}
5528
François Gaffiec005e562018-11-06 15:04:49 +01005529void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005530{
François Gaffiec005e562018-11-06 15:04:49 +01005531 // Take the first attributes following the product strategy as it is used to retrieve the routed
5532 // device. All attributes wihin a strategy follows the same "routing strategy"
5533 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5534 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005535 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005536 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005537 for (size_t j = 0; j < mOutputs.size(); j++) {
5538 if (mOutputs.keyAt(j) == ouptutToSkip) {
5539 continue;
5540 }
5541 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005542 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005543 continue;
5544 }
5545 // If the default device for this strategy is on another output mix,
5546 // invalidate all tracks in this strategy to force re connection.
5547 // Otherwise select new device on the output mix.
5548 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005549 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005550 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005551 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5552 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5553 // If the device is using preferred mixer attributes, the output need to reopen
5554 // with default configuration when the new selected devices are different from
5555 // current routing devices.
5556 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5557 continue;
5558 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305559 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005560 }
5561 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005562 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005563}
5564
5565void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5566{
5567 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005568 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005569 for (size_t i = 0; i < mOutputs.size(); i++) {
5570 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005571 for (const auto& client : outputDesc->getClientIterable()) {
5572 if (client->hasPreferredDevice() && client->uid() == uid) {
5573 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005574 auto clientStrategy = client->strategy();
5575 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5576 end(affectedStrategies)) {
5577 continue;
5578 }
5579 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005580 }
5581 }
5582 }
5583 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005584 for (const auto& strategy : affectedStrategies) {
5585 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005586 }
5587
5588 // remove input routes associated with this uid
5589 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005590 for (size_t i = 0; i < mInputs.size(); i++) {
5591 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005592 for (const auto& client : inputDesc->getClientIterable()) {
5593 if (client->hasPreferredDevice() && client->uid() == uid) {
5594 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5595 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005596 }
5597 }
5598 }
5599 // reroute inputs if necessary
5600 SortedVector<audio_io_handle_t> inputsToClose;
5601 for (size_t i = 0; i < mInputs.size(); i++) {
5602 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005603 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005604 inputsToClose.add(inputDesc->mIoHandle);
5605 }
5606 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005607 for (const auto& input : inputsToClose) {
5608 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005609 }
5610}
5611
Eric Laurentd60560a2015-04-10 11:31:20 -07005612void AudioPolicyManager::clearAudioSources(uid_t uid)
5613{
5614 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005615 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5616 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005617 stopAudioSource(mAudioSources.keyAt(i));
5618 }
5619 }
5620}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005621
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005622status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5623 audio_io_handle_t *ioHandle,
5624 audio_devices_t *device)
5625{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005626 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5627 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005628 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005629 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5630 if (deviceDesc == nullptr) {
5631 return INVALID_OPERATION;
5632 }
5633 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005634
François Gaffiedf372692015-03-19 10:43:27 +01005635 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005636}
5637
Eric Laurentd60560a2015-04-10 11:31:20 -07005638status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005639 const audio_attributes_t *attributes,
5640 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005641 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005642{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005643 ALOGV("%s", __FUNCTION__);
5644 *portId = AUDIO_PORT_HANDLE_NONE;
5645
5646 if (source == NULL || attributes == NULL || portId == NULL) {
5647 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5648 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005649 return BAD_VALUE;
5650 }
5651
Eric Laurentd60560a2015-04-10 11:31:20 -07005652 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5653 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005654 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5655 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005656 return INVALID_OPERATION;
5657 }
5658
François Gaffie11d30102018-11-02 16:09:09 +01005659 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005660 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005661 String8(source->ext.device.address),
5662 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005663 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005664 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005665 return BAD_VALUE;
5666 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005667
jiabin4ef93452019-09-10 14:29:54 -07005668 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005669
François Gaffieaaac0fd2018-11-22 17:56:39 +01005670 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005671 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005672 mEngine->getStreamTypeForAttributes(*attributes),
5673 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005674 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005675
5676 status_t status = connectAudioSource(sourceDesc);
5677 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005678 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005679 }
5680 return status;
5681}
5682
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005683status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005684{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005685 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005686
5687 // make sure we only have one patch per source.
5688 disconnectAudioSource(sourceDesc);
5689
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005690 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005691 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5692 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5693 sourceDesc->srcDevice()->type(),
5694 String8(sourceDesc->srcDevice()->address().c_str()),
5695 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005696 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005697 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005698 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005699 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005700 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5701 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5702 return INVALID_OPERATION;
5703 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005704 PatchBuilder patchBuilder;
5705 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5706 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005707
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005708 return connectAudioSourceToSink(
5709 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005710}
5711
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005712status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005713{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005714 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5715 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005716 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005717 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005718 return BAD_VALUE;
5719 }
5720 status_t status = disconnectAudioSource(sourceDesc);
5721
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005722 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005723 return status;
5724}
5725
Andy Hung2ddee192015-12-18 17:34:44 -08005726status_t AudioPolicyManager::setMasterMono(bool mono)
5727{
5728 if (mMasterMono == mono) {
5729 return NO_ERROR;
5730 }
5731 mMasterMono = mono;
5732 // if enabling mono we close all offloaded devices, which will invalidate the
5733 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5734 // for recreating the new AudioTrack as non-offloaded PCM.
5735 //
5736 // If disabling mono, we leave all tracks as is: we don't know which clients
5737 // and tracks are able to be recreated as offloaded. The next "song" should
5738 // play back offloaded.
5739 if (mMasterMono) {
5740 Vector<audio_io_handle_t> offloaded;
5741 for (size_t i = 0; i < mOutputs.size(); ++i) {
5742 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5743 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5744 offloaded.push(desc->mIoHandle);
5745 }
5746 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005747 for (const auto& handle : offloaded) {
5748 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005749 }
5750 }
5751 // update master mono for all remaining outputs
5752 for (size_t i = 0; i < mOutputs.size(); ++i) {
5753 updateMono(mOutputs.keyAt(i));
5754 }
5755 return NO_ERROR;
5756}
5757
5758status_t AudioPolicyManager::getMasterMono(bool *mono)
5759{
5760 *mono = mMasterMono;
5761 return NO_ERROR;
5762}
5763
Eric Laurentac9cef52017-06-09 15:46:26 -07005764float AudioPolicyManager::getStreamVolumeDB(
5765 audio_stream_type_t stream, int index, audio_devices_t device)
5766{
jiabin9a3361e2019-10-01 09:38:30 -07005767 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005768}
5769
jiabin81772902018-04-02 17:52:27 -07005770status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5771 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005772 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005773{
Kriti Dang6537def2021-03-02 13:46:59 +01005774 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5775 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005776 return BAD_VALUE;
5777 }
Kriti Dang6537def2021-03-02 13:46:59 +01005778 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5779 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005780
5781 size_t formatsWritten = 0;
5782 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005783
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005784 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005785 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5786 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005787 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005788 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005789 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005790 bool formatEnabled = true;
5791 switch (forceUse) {
5792 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005793 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005794 break;
5795 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5796 formatEnabled = false;
5797 break;
5798 default: // AUTO or ALWAYS => true
5799 break;
jiabin81772902018-04-02 17:52:27 -07005800 }
5801 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5802 }
jiabin81772902018-04-02 17:52:27 -07005803 }
5804 return NO_ERROR;
5805}
5806
Kriti Dang6537def2021-03-02 13:46:59 +01005807status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5808 audio_format_t *surroundFormats) {
5809 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5810 return BAD_VALUE;
5811 }
5812 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5813 __func__, *numSurroundFormats, surroundFormats);
5814
5815 size_t formatsWritten = 0;
5816 size_t formatsMax = *numSurroundFormats;
5817 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5818
5819 // Return formats from all device profiles that have already been resolved by
5820 // checkOutputsForDevice().
5821 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5822 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5823 audio_devices_t deviceType = device->type();
5824 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5825 // returns formats reported by HDMI devices.
5826 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5827 continue;
5828 }
5829 // Formats reported by sink devices
5830 std::unordered_set<audio_format_t> formatset;
5831 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5832 formatset.insert(it->second.begin(), it->second.end());
5833 }
5834
5835 // Formats hard-coded in the in policy configuration file (if any).
5836 FormatVector encodedFormats = device->encodedFormats();
5837 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5838 // Filter the formats which are supported by the vendor hardware.
5839 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005840 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005841 formats.insert(*it);
5842 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005843 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005844 if (pair.second.count(*it) != 0) {
5845 formats.insert(pair.first);
5846 break;
5847 }
5848 }
5849 }
5850 }
5851 }
5852 *numSurroundFormats = formats.size();
5853 for (const auto& format: formats) {
5854 if (formatsWritten < formatsMax) {
5855 surroundFormats[formatsWritten++] = format;
5856 }
5857 }
5858 return NO_ERROR;
5859}
5860
jiabin81772902018-04-02 17:52:27 -07005861status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5862{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005863 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005864 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5865 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005866 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005867 return BAD_VALUE;
5868 }
5869
Mikhail Naganov100f0122018-11-29 11:22:16 -08005870 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5871 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005872 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005873 return INVALID_OPERATION;
5874 }
5875
Mikhail Naganov100f0122018-11-29 11:22:16 -08005876 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005877 return NO_ERROR;
5878 }
5879
Mikhail Naganov100f0122018-11-29 11:22:16 -08005880 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005881 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005882 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005883 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005884 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005885 }
5886 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005887 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005888 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005889 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005890 }
5891 }
5892
5893 sp<SwAudioOutputDescriptor> outputDesc;
5894 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005895 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5896 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005897 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5898 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005899 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005900 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005901 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5902 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5903 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005904 name.c_str(),
5905 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005906 if (status != NO_ERROR) {
5907 continue;
5908 }
5909 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5910 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5911 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005912 name.c_str(),
5913 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005914 profileUpdated |= (status == NO_ERROR);
5915 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005916 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005917 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005918 AUDIO_DEVICE_IN_HDMI);
5919 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5920 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005921 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005922 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005923 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5924 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5925 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005926 name.c_str(),
5927 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005928 if (status != NO_ERROR) {
5929 continue;
5930 }
5931 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5932 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5933 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005934 name.c_str(),
5935 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005936 profileUpdated |= (status == NO_ERROR);
5937 }
5938
jiabin81772902018-04-02 17:52:27 -07005939 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005940 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005941 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005942 }
5943
5944 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5945}
5946
Eric Laurent5ada82e2019-08-29 17:53:54 -07005947void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005948{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005949 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005950 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005951 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005952 }
5953}
5954
jiabin6012f912018-11-02 17:06:30 -07005955bool AudioPolicyManager::isHapticPlaybackSupported()
5956{
5957 for (const auto& hwModule : mHwModules) {
5958 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5959 for (const auto &outProfile : outputProfiles) {
5960 struct audio_port audioPort;
5961 outProfile->toAudioPort(&audioPort);
5962 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5963 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5964 return true;
5965 }
5966 }
5967 }
5968 }
5969 return false;
5970}
5971
Carter Hsu325a8eb2022-01-19 19:56:51 +08005972bool AudioPolicyManager::isUltrasoundSupported()
5973{
5974 bool hasUltrasoundOutput = false;
5975 bool hasUltrasoundInput = false;
5976 for (const auto& hwModule : mHwModules) {
5977 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5978 if (!hasUltrasoundOutput) {
5979 for (const auto &outProfile : outputProfiles) {
5980 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5981 hasUltrasoundOutput = true;
5982 break;
5983 }
5984 }
5985 }
5986
5987 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5988 if (!hasUltrasoundInput) {
5989 for (const auto &inputProfile : inputProfiles) {
5990 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5991 hasUltrasoundInput = true;
5992 break;
5993 }
5994 }
5995 }
5996
5997 if (hasUltrasoundOutput && hasUltrasoundInput)
5998 return true;
5999 }
6000 return false;
6001}
6002
Atneya Nair698f5ef2022-12-15 16:15:09 -08006003bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6004{
6005 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6006 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6007 for (const auto& hwModule : mHwModules) {
6008 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6009 for (const auto &inputProfile : inputProfiles) {
6010 if ((inputProfile->getFlags() & mask) == mask) {
6011 return true;
6012 }
6013 }
6014 }
6015 return false;
6016}
6017
Eric Laurent8340e672019-11-06 11:01:08 -08006018bool AudioPolicyManager::isCallScreenModeSupported()
6019{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006020 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006021}
6022
6023
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006024status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006025{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006026 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006027 if (!sourceDesc->isConnected()) {
6028 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6029 return NO_ERROR;
6030 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006031 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6032 if (swOutput != 0) {
6033 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006034 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006035 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006036 }
jiabinbce0c1d2020-10-05 11:20:18 -07006037 if (releaseOutput(sourceDesc->portId())) {
6038 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6039 // no need to release audio patch here but just return NO_ERROR.
6040 return NO_ERROR;
6041 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006042 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006043 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006044 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006045 // close Hwoutput and remove from mHwOutputs
6046 } else {
6047 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6048 }
6049 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006050 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006051 sourceDesc->disconnect();
6052 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006053}
6054
François Gaffiec005e562018-11-06 15:04:49 +01006055sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6056 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006057{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006058 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006059 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006061 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006062 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6063 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006064 source = sourceDesc;
6065 break;
6066 }
6067 }
6068 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006069}
6070
Eric Laurentb4f42a92022-01-17 17:37:31 +01006071bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006072 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006073 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074{
6075 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6076 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006077 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006078 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006079 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6080 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6081 return false;
6082 }
6083 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6084 return false;
6085 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006086 }
6087
Eric Laurentd332bc82023-08-04 11:45:23 +02006088 // The caller can have the audio config criteria ignored by either passing a null ptr or
6089 // the AUDIO_CONFIG_INITIALIZER value.
6090 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006091 // some positional channel masks and PCM format and for stereo if low latency performance
6092 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006093
6094 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006095 static const bool stereo_spatialization_enabled =
6096 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006097 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006098 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006099 ? audio_channel_mask_contains_stereo(config->channel_mask)
6100 : audio_is_channel_mask_spatialized(config->channel_mask);
6101 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006102 return false;
6103 }
6104 if (!audio_is_linear_pcm(config->format)) {
6105 return false;
6106 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006107 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6108 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6109 return false;
6110 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006111 }
6112
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006113 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006114 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006115 if (profile == nullptr) {
6116 return false;
6117 }
6118
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006119 return true;
6120}
6121
6122void AudioPolicyManager::checkVirtualizerClientRoutes() {
6123 std::set<audio_stream_type_t> streamsToInvalidate;
6124 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006125 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6126 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006127 audio_attributes_t attr = client->attributes();
6128 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6129 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6130 audio_config_base_t clientConfig = client->config();
6131 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006132 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006133 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006134 streamsToInvalidate.insert(client->stream());
6135 }
6136 }
6137 }
6138
jiabinc44b3462022-12-08 12:52:31 -08006139 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006140}
6141
Eric Laurente191d1b2022-04-15 11:59:25 +02006142
6143bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6144 const sp<SwAudioOutputDescriptor>& outputDesc) {
6145 if (outputDesc->isDuplicated()) {
6146 return false;
6147 }
6148 DeviceVector devices = outputDesc->supportedDevices();
6149 for (size_t i = 0; i < mOutputs.size(); i++) {
6150 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6151 if (desc == outputDesc || desc->isDuplicated()) {
6152 continue;
6153 }
6154 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6155 if (!sharedDevices.isEmpty()
6156 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6157 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6158 return false;
6159 }
6160 }
6161 return true;
6162}
6163
6164
Eric Laurentfa0f6742021-08-17 18:39:44 +02006165status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006166 const audio_attributes_t *attr,
6167 audio_io_handle_t *output) {
6168 *output = AUDIO_IO_HANDLE_NONE;
6169
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006170 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6171 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6172 audio_config_t *configPtr = nullptr;
6173 audio_config_t config;
6174 if (mixerConfig != nullptr) {
6175 config = audio_config_initializer(mixerConfig);
6176 configPtr = &config;
6177 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006178 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006179 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006180 return BAD_VALUE;
6181 }
6182
6183 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006184 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006185 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006186 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006187 return BAD_VALUE;
6188 }
6189
Eric Laurente191d1b2022-04-15 11:59:25 +02006190 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006191 for (size_t i = 0; i < mOutputs.size(); i++) {
6192 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006193 if (!desc->isDuplicated()
6194 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6195 spatializerOutputs.push_back(desc);
6196 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006197 }
6198 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006199 mSpatializerOutput.clear();
6200 bool outputsChanged = false;
6201 for (const auto& desc : spatializerOutputs) {
6202 if (desc->mProfile == profile
6203 && (configPtr == nullptr
6204 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6205 mSpatializerOutput = desc;
6206 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6207 } else {
6208 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6209 " and devices %s", __func__, desc->mIoHandle,
6210 configPtr != nullptr ? configPtr->channel_mask : 0,
6211 devices.toString().c_str());
6212 closeOutput(desc->mIoHandle);
6213 outputsChanged = true;
6214 }
Eric Laurent39095982021-08-24 18:29:27 +02006215 }
6216
Eric Laurente191d1b2022-04-15 11:59:25 +02006217 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006218 sp<SwAudioOutputDescriptor> desc =
6219 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006220 if (desc != nullptr) {
6221 mSpatializerOutput = desc;
6222 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006223 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006224 }
6225
6226 checkVirtualizerClientRoutes();
6227
Eric Laurente191d1b2022-04-15 11:59:25 +02006228 if (outputsChanged) {
6229 mPreviousOutputs = mOutputs;
6230 mpClientInterface->onAudioPortListUpdate();
6231 }
6232
6233 if (mSpatializerOutput == nullptr) {
6234 ALOGV("%s could not open spatializer output with requested config", __func__);
6235 return BAD_VALUE;
6236 }
Eric Laurent39095982021-08-24 18:29:27 +02006237 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006238 ALOGV("%s returning new spatializer output %d", __func__, *output);
6239 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006240}
6241
Eric Laurentfa0f6742021-08-17 18:39:44 +02006242status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6243 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006244 return INVALID_OPERATION;
6245 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006246 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006247 return BAD_VALUE;
6248 }
Eric Laurent39095982021-08-24 18:29:27 +02006249
Eric Laurente191d1b2022-04-15 11:59:25 +02006250 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6251 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6252 closeOutput(mSpatializerOutput->mIoHandle);
6253 //from now on mSpatializerOutput is null
6254 checkVirtualizerClientRoutes();
6255 }
Eric Laurent39095982021-08-24 18:29:27 +02006256
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006257 return NO_ERROR;
6258}
6259
Eric Laurente552edb2014-03-10 17:42:56 -07006260// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006261// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006262// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006263uint32_t AudioPolicyManager::nextAudioPortGeneration()
6264{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006265 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006266}
6267
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006268AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006269 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006270 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006271 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006272 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006273 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006274 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006275 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006276 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006277 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006278 mAudioPortGeneration(1),
6279 mBeaconMuteRefCount(0),
6280 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006281 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006282 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006283 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006284 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006285{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006286}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006287
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006288status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006289 if (mEngine == nullptr) {
6290 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006291 }
6292 mEngine->setObserver(this);
6293 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006294 if (status != NO_ERROR) {
6295 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6296 return status;
6297 }
François Gaffie2110e042015-03-24 08:41:51 +01006298
jiabin29230182023-04-04 21:02:36 +00006299 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6300 // at the end of this function.
6301 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006302 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6303 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6304
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006305 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006306 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006307 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006308
Eric Laurent3a4311c2014-03-17 12:00:47 -07006309 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006310 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6311 defaultOutputDevice == nullptr ||
6312 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6313 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6314 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006315 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006316 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006317 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006318
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006319 // Silence ALOGV statements
6320 property_set("log.tag." LOG_TAG, "D");
6321
Eric Laurente552edb2014-03-10 17:42:56 -07006322 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006323 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006324}
6325
Eric Laurente0720872014-03-11 09:30:41 -07006326AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006327{
Eric Laurente552edb2014-03-10 17:42:56 -07006328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006329 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006330 }
6331 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006332 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006333 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006334 mAvailableOutputDevices.clear();
6335 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006336 mOutputs.clear();
6337 mInputs.clear();
6338 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006339 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006340 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006341}
6342
Eric Laurente0720872014-03-11 09:30:41 -07006343status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006344{
Eric Laurent87ffa392015-05-22 10:32:38 -07006345 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006346}
6347
Eric Laurente552edb2014-03-10 17:42:56 -07006348// ---
6349
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006350void AudioPolicyManager::onNewAudioModulesAvailable()
6351{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006352 DeviceVector newDevices;
6353 onNewAudioModulesAvailableInt(&newDevices);
6354 if (!newDevices.empty()) {
6355 nextAudioPortGeneration();
6356 mpClientInterface->onAudioPortListUpdate();
6357 }
6358}
6359
6360void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6361{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006362 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006363 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6364 continue;
6365 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006366 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006367 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6368 handle != AUDIO_MODULE_HANDLE_NONE) {
6369 hwModule->setHandle(handle);
6370 } else {
6371 ALOGW("could not load HW module %s", hwModule->getName());
6372 continue;
6373 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006374 }
6375 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006376 // open all output streams needed to access attached devices.
6377 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006378 // This also validates mAvailableOutputDevices list
6379 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6380 if (!outProfile->canOpenNewIo()) {
6381 ALOGE("Invalid Output profile max open count %u for profile %s",
6382 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6383 continue;
6384 }
6385 if (!outProfile->hasSupportedDevices()) {
6386 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6387 continue;
6388 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006389 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6390 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006391 mTtsOutputAvailable = true;
6392 }
6393
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006394 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006395 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006396 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006397 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6398 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006399 } else {
6400 // choose first device present in profile's SupportedDevices also part of
6401 // mAvailableOutputDevices.
6402 if (availProfileDevices.isEmpty()) {
6403 continue;
6404 }
6405 supportedDevice = availProfileDevices.itemAt(0);
6406 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006407 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006408 continue;
6409 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306410
6411 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6412 && availProfileDevices.areAllDevicesAttached()) {
6413 ALOGV("%s skip opening output for mmap profile %s", __func__,
6414 outProfile->getTagName().c_str());
6415 continue;
6416 }
6417
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006418 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6419 mpClientInterface);
6420 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006421 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6422 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006423 AUDIO_STREAM_DEFAULT,
6424 AUDIO_OUTPUT_FLAG_NONE, &output);
6425 if (status != NO_ERROR) {
6426 ALOGW("Cannot open output stream for devices %s on hw module %s",
6427 supportedDevice->toString().c_str(), hwModule->getName());
6428 continue;
6429 }
6430 for (const auto &device : availProfileDevices) {
6431 // give a valid ID to an attached device once confirmed it is reachable
6432 if (!device->isAttached()) {
6433 device->attach(hwModule);
6434 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006435 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006436 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006437 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6438 }
6439 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006440 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006441 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6442 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006443 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006444 }
Eric Laurent39095982021-08-24 18:29:27 +02006445 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006446 outputDesc->close();
6447 } else {
6448 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306449 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006450 DeviceVector(supportedDevice),
6451 true,
6452 0,
6453 NULL);
6454 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006455 }
6456 // open input streams needed to access attached devices to validate
6457 // mAvailableInputDevices list
6458 for (const auto& inProfile : hwModule->getInputProfiles()) {
6459 if (!inProfile->canOpenNewIo()) {
6460 ALOGE("Invalid Input profile max open count %u for profile %s",
6461 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6462 continue;
6463 }
6464 if (!inProfile->hasSupportedDevices()) {
6465 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6466 continue;
6467 }
6468 // chose first device present in profile's SupportedDevices also part of
6469 // available input devices
6470 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006471 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006472 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006473 ALOGV("%s: Input device list is empty! for profile %s",
6474 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006475 continue;
6476 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306477
6478 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6479 && availProfileDevices.areAllDevicesAttached()) {
6480 ALOGV("%s skip opening input for mmap profile %s", __func__,
6481 inProfile->getTagName().c_str());
6482 continue;
6483 }
6484
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006485 sp<AudioInputDescriptor> inputDesc =
6486 new AudioInputDescriptor(inProfile, mpClientInterface);
6487
6488 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6489 status_t status = inputDesc->open(nullptr,
6490 availProfileDevices.itemAt(0),
6491 AUDIO_SOURCE_MIC,
Liana Kazanovaa31591a2024-07-11 20:09:39 +00006492 AUDIO_INPUT_FLAG_NONE,
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006493 &input);
6494 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306495 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6496 __func__, availProfileDevices.toString().c_str(),
6497 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006498 continue;
6499 }
6500 for (const auto &device : availProfileDevices) {
6501 // give a valid ID to an attached device once confirmed it is reachable
6502 if (!device->isAttached()) {
6503 device->attach(hwModule);
6504 device->importAudioPortAndPickAudioProfile(inProfile, true);
6505 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006506 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006507 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6508 }
6509 }
6510 inputDesc->close();
6511 }
6512 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006513
6514 // Check if spatializer outputs can be closed until used.
6515 // mOutputs vector never contains duplicated outputs at this point.
6516 std::vector<audio_io_handle_t> outputsClosed;
6517 for (size_t i = 0; i < mOutputs.size(); i++) {
6518 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6519 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6520 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6521 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006522 nextAudioPortGeneration();
6523 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6524 if (index >= 0) {
6525 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6526 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6527 patchDesc->getAfHandle(), 0);
6528 mAudioPatches.removeItemsAt(index);
6529 mpClientInterface->onAudioPatchListUpdate();
6530 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006531 desc->close();
6532 }
6533 }
6534 for (auto output : outputsClosed) {
6535 removeOutput(output);
6536 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006537}
6538
Eric Laurent98e38192018-02-15 18:31:53 -08006539void AudioPolicyManager::addOutput(audio_io_handle_t output,
6540 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006541{
Eric Laurent1c333e22014-05-20 10:48:17 -07006542 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006543 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006544 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006545 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006546 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006547}
6548
François Gaffie53615e22015-03-19 09:24:12 +01006549void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6550{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006551 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6552 ALOGV("%s: removing primary output", __func__);
6553 mPrimaryOutput = nullptr;
6554 }
François Gaffie53615e22015-03-19 09:24:12 +01006555 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006556 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006557}
6558
Eric Laurent98e38192018-02-15 18:31:53 -08006559void AudioPolicyManager::addInput(audio_io_handle_t input,
6560 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006561{
Eric Laurent1c333e22014-05-20 10:48:17 -07006562 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006563 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006564}
Eric Laurente552edb2014-03-10 17:42:56 -07006565
François Gaffie11d30102018-11-02 16:09:09 +01006566status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006567 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006568 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006569{
François Gaffie11d30102018-11-02 16:09:09 +01006570 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006571 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006572 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006573
François Gaffie11d30102018-11-02 16:09:09 +01006574 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006575 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006576 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006577 }
Eric Laurente552edb2014-03-10 17:42:56 -07006578
Eric Laurent3b73df72014-03-11 09:06:29 -07006579 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006580 // first call getAudioPort to get the supported attributes from the HAL
6581 struct audio_port_v7 port = {};
6582 device->toAudioPort(&port);
6583 status_t status = mpClientInterface->getAudioPort(&port);
6584 if (status == NO_ERROR) {
6585 device->importAudioPort(port);
6586 }
6587
6588 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006589 for (size_t i = 0; i < mOutputs.size(); i++) {
6590 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006591 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006592 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006593 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6594 mOutputs.keyAt(i), device->toString().c_str());
6595 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006596 }
6597 }
6598 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006599 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006600 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006601 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6602 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006603 if (profile->supportsDevice(device)) {
6604 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306605 ALOGV("%s(): adding profile %s from module %s",
6606 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006607 }
6608 }
6609 }
6610
Eric Laurent7b279bb2015-12-14 10:18:23 -08006611 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006612
Eric Laurente552edb2014-03-10 17:42:56 -07006613 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006614 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006615 return BAD_VALUE;
6616 }
6617
6618 // open outputs for matching profiles if needed. Direct outputs are also opened to
6619 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6620 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006621 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006622
6623 // nothing to do if one output is already opened for this profile
6624 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006625 for (j = 0; j < outputs.size(); j++) {
6626 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006627 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006628 // matching profile: save the sample rates, format and channel masks supported
6629 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006630 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006631 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006632 }
Eric Laurente552edb2014-03-10 17:42:56 -07006633 break;
6634 }
6635 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006636 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006637 continue;
6638 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306639 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6640 ALOGV("%s skip opening output for mmap profile %s",
6641 __func__, profile->getTagName().c_str());
6642 continue;
6643 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006644 if (!profile->canOpenNewIo()) {
6645 ALOGW("Max Output number %u already opened for this profile %s",
6646 profile->maxOpenCount, profile->getTagName().c_str());
6647 continue;
6648 }
6649
Eric Laurent83efe1c2017-07-09 16:51:08 -07006650 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006651 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006652 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6653 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006654 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006655 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006656 profiles.removeAt(profile_index);
6657 profile_index--;
6658 } else {
6659 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006660 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006661 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006662 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6663 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006664 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006665 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006666
François Gaffie11d30102018-11-02 16:09:09 +01006667 if (device_distinguishes_on_address(deviceType)) {
6668 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6669 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306670 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6671 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006672 }
Eric Laurente552edb2014-03-10 17:42:56 -07006673 ALOGV("checkOutputsForDevice(): adding output %d", output);
6674 }
6675 }
6676
6677 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006678 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006679 return BAD_VALUE;
6680 }
Eric Laurentd4692962014-05-05 18:13:44 -07006681 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006682 // check if one opened output is not needed any more after disconnecting one device
6683 for (size_t i = 0; i < mOutputs.size(); i++) {
6684 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006685 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006686 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006687 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006688 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006689 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006690 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006691 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6692 mOutputs.keyAt(i));
6693 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006694 }
Eric Laurente552edb2014-03-10 17:42:56 -07006695 }
6696 }
Eric Laurentd4692962014-05-05 18:13:44 -07006697 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006698 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006699 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6700 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006701 if (!profile->supportsDevice(device)) {
6702 continue;
6703 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306704 ALOGV("%s(): clearing direct output profile %s on module %s",
6705 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006706 profile->clearAudioProfiles();
6707 if (!profile->hasDynamicAudioProfile()) {
6708 continue;
6709 }
6710 // When a device is disconnected, if there is an IOProfile that contains dynamic
6711 // profiles and supports the disconnected device, call getAudioPort to repopulate
6712 // the capabilities of the devices that is supported by the IOProfile.
6713 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6714 if (supportedDevice == device ||
6715 !mAvailableOutputDevices.contains(supportedDevice)) {
6716 continue;
6717 }
6718 struct audio_port_v7 port;
6719 supportedDevice->toAudioPort(&port);
6720 status_t status = mpClientInterface->getAudioPort(&port);
6721 if (status == NO_ERROR) {
6722 supportedDevice->importAudioPort(port);
6723 }
Eric Laurente552edb2014-03-10 17:42:56 -07006724 }
6725 }
6726 }
6727 }
6728 return NO_ERROR;
6729}
6730
François Gaffie11d30102018-11-02 16:09:09 +01006731status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006732 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006733{
François Gaffie11d30102018-11-02 16:09:09 +01006734 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006735 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006736 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006737 }
6738
Eric Laurentd4692962014-05-05 18:13:44 -07006739 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006740 sp<AudioInputDescriptor> desc;
6741
jiabinbf5f4262023-04-12 21:48:34 +00006742 // first call getAudioPort to get the supported attributes from the HAL
6743 struct audio_port_v7 port = {};
6744 device->toAudioPort(&port);
6745 status_t status = mpClientInterface->getAudioPort(&port);
6746 if (status == NO_ERROR) {
6747 device->importAudioPort(port);
6748 }
6749
Eric Laurent0dd51852019-04-19 18:18:58 -07006750 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006751 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006752 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006753 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006754 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006755 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006756 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006757
François Gaffie11d30102018-11-02 16:09:09 +01006758 if (profile->supportsDevice(device)) {
6759 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306760 ALOGV("%s : adding profile %s from module %s", __func__,
6761 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006762 }
6763 }
6764 }
6765
Eric Laurent0dd51852019-04-19 18:18:58 -07006766 if (profiles.isEmpty()) {
6767 ALOGW("%s: No input profile available for device %s",
6768 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006769 return BAD_VALUE;
6770 }
6771
6772 // open inputs for matching profiles if needed. Direct inputs are also opened to
6773 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6774 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6775
Eric Laurent1c333e22014-05-20 10:48:17 -07006776 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006777
Eric Laurentd4692962014-05-05 18:13:44 -07006778 // nothing to do if one input is already opened for this profile
6779 size_t input_index;
6780 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6781 desc = mInputs.valueAt(input_index);
6782 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006783 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006784 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006785 }
Eric Laurentd4692962014-05-05 18:13:44 -07006786 break;
6787 }
6788 }
6789 if (input_index != mInputs.size()) {
6790 continue;
6791 }
6792
Jaideep Sharma44824a22024-06-18 16:32:34 +05306793 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6794 ALOGV("%s skip opening input for mmap profile %s",
6795 __func__, profile->getTagName().c_str());
6796 continue;
6797 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006798 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306799 ALOGW("%s Max Input number %u already opened for this profile %s",
6800 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006801 continue;
6802 }
6803
Eric Laurentfe231122017-11-17 17:48:06 -08006804 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006805 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306806 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Liana Kazanovaa31591a2024-07-11 20:09:39 +00006807 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006808
Eric Laurentcf2c0212014-07-25 16:20:43 -07006809 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006810 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006811 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006812 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006813 mpClientInterface->setParameters(input, String8(param));
6814 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006815 }
jiabin12537fc2023-10-12 17:56:08 +00006816 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006817 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306818 ALOGW("%s direct input missing param for profile %s", __func__,
6819 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08006820 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006821 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006822 }
6823
Eric Laurent0dd51852019-04-19 18:18:58 -07006824 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006825 addInput(input, desc);
6826 }
6827 } // endif input != 0
6828
Eric Laurentcf2c0212014-07-25 16:20:43 -07006829 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306830 ALOGW("%s could not open input for device %s on profile %s", __func__,
6831 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006832 profiles.removeAt(profile_index);
6833 profile_index--;
6834 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006835 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006836 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006837 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306838 ALOGV("%s: adding input %d for profile %s", __func__,
6839 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006840
6841 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306842 ALOGV("%s: closing input %d for profile %s", __func__,
6843 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006844 closeInput(input);
6845 }
Eric Laurentd4692962014-05-05 18:13:44 -07006846 }
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)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306862 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
6863 profile->getTagName().c_str(), 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,
jiabin9a3361e2019-10-01 09:38:30 -07007897 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007898{
jiabin9a3361e2019-10-01 09:38:30 -07007899 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007900
7901 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7902 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7903 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7904 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007905 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7906 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7907 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7908 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7909 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007910 // Verify that the current volume source is not the ringer volume to prevent recursively
7911 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7912 // to the same volume group.
7913 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007914 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7915 mOutputs.isActive(ringVolumeSrc, 0)) {
7916 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007917 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007918 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007919 }
7920
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007921 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007922 if ((volumeSource != callVolumeSrc && (isInCall() ||
7923 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007924 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007925 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7926 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007927 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7928 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7929 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007930 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007931 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007932 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007933 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007934 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007935 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007936 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7937 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7938 // programmatically muted.
7939 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7940 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7941 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007942 bool exemptFromCapping =
7943 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7944 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007945 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7946 volumeSource, volumeDb);
7947 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007948 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7949 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7950 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007951 }
7952 }
Eric Laurente552edb2014-03-10 17:42:56 -07007953 // if a headset is connected, apply the following rules to ring tones and notifications
7954 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007955 // - always attenuate notifications volume by 6dB
7956 // - attenuate ring tones volume by 6dB unless music is not playing and
7957 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007958 // - if music is playing, always limit the volume to current music volume,
7959 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007960 if (!Intersection(deviceTypes,
7961 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7962 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007963 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7964 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007965 ((volumeSource == alarmVolumeSrc ||
7966 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007967 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7968 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7969 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007970 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7971 curves.canBeMuted()) {
7972
Eric Laurente552edb2014-03-10 17:42:56 -07007973 // when the phone is ringing we must consider that music could have been paused just before
7974 // by the music application and behave as if music was active if the last music track was
7975 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07007976 // Verify that the current volume source is not the music volume to prevent recursively
7977 // calling to compute volume. This could happen in cases where music and
7978 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7979 if (volumeSource != musicVolumeSrc &&
7980 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7981 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007982 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007983 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007984 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7985 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007986 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007987 float musicVolDb = computeVolume(musicCurves,
7988 musicVolumeSrc,
7989 musicCurves.getVolumeIndex(musicDevice),
7990 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007991 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7992 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7993 if (volumeDb > minVolDb) {
7994 volumeDb = minVolDb;
7995 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007996 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007997 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7998 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08007999 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8000 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8001 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8002 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008003 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008004 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008005 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8006 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008007 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8008 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008009 }
8010 }
jiabin9a3361e2019-10-01 09:38:30 -07008011 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008012 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008013 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008014 }
8015 }
8016
François Gaffie43c73442018-11-08 08:21:55 +01008017 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008018}
8019
Eric Laurent3839bc02018-07-10 18:33:34 -07008020int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008021 VolumeSource fromVolumeSource,
8022 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008023{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008024 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008025 return srcIndex;
8026 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008027 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8028 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008029 float minSrc = (float)srcCurves.getVolumeIndexMin();
8030 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8031 float minDst = (float)dstCurves.getVolumeIndexMin();
8032 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008033
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008034 // preserve mute request or correct range
8035 if (srcIndex < minSrc) {
8036 if (srcIndex == 0) {
8037 return 0;
8038 }
8039 srcIndex = minSrc;
8040 } else if (srcIndex > maxSrc) {
8041 srcIndex = maxSrc;
8042 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008043 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8044}
8045
François Gaffieaaac0fd2018-11-22 17:56:39 +01008046status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8047 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008048 int index,
8049 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008050 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008051 int delayMs,
8052 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008053{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008054 // do not change actual attributes volume if the attributes is muted
8055 if (outputDesc->isMuted(volumeSource)) {
8056 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8057 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008058 return NO_ERROR;
8059 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008060
Eric Laurent5baf07c2024-01-11 16:57:27 +00008061 bool isVoiceVolSrc;
8062 bool isBtScoVolSrc;
8063 if (!isVolumeConsistentForCalls(
8064 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008065 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008066 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008067 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008068 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008069
jiabin9a3361e2019-10-01 09:38:30 -07008070 if (deviceTypes.empty()) {
8071 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008072 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008073 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008074 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008075 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008076
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008077 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8078 ALOGE("invalid volume index range");
8079 return BAD_VALUE;
8080 }
8081
jiabin9a3361e2019-10-01 09:38:30 -07008082 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8083 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008084 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008085 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008086 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8087 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008088 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008089 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008090 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008091 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8092 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008093
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008094 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008095 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8096 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8097 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008098 }
Eric Laurente552edb2014-03-10 17:42:56 -07008099 return NO_ERROR;
8100}
8101
Eric Laurent5baf07c2024-01-11 16:57:27 +00008102void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008103 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008104 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008105 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008106 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008107 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008108 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8109 } else {
8110 voiceVolume = index == 0 ? 0.0 : 1.0;
8111 }
8112 if (voiceVolume != mLastVoiceVolume) {
8113 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8114 mLastVoiceVolume = voiceVolume;
8115 }
8116}
8117
8118bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8119 const DeviceTypeSet& deviceTypes,
8120 bool& isVoiceVolSrc,
8121 bool& isBtScoVolSrc,
8122 const char* caller) {
8123 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8124 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8125 const bool isScoRequested = isScoRequestedForComm();
8126 const bool isHAUsed = isHearingAidUsedForComm();
8127
8128 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8129 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8130
8131 if ((callVolSrc != btScoVolSrc) &&
8132 ((isVoiceVolSrc && isScoRequested) ||
8133 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8134 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8135 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8136 volumeSource, isScoRequested ? " " : " not ");
8137 return false;
8138 }
8139 return true;
8140}
8141
Eric Laurentc75307b2015-03-17 15:29:32 -07008142void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008143 const DeviceTypeSet& deviceTypes,
8144 int delayMs,
8145 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008146{
jiabincd510522020-01-22 09:40:55 -08008147 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008148 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8149 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8150 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008151 curves.getVolumeIndex(deviceTypes),
8152 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008153 }
8154}
8155
François Gaffiec005e562018-11-06 15:04:49 +01008156void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8157 bool on,
8158 const sp<AudioOutputDescriptor>& outputDesc,
8159 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008160 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008161{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008162 std::vector<VolumeSource> sourcesToMute;
8163 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8164 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8165 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008166 VolumeSource source = toVolumeSource(attributes, false);
8167 if ((source != VOLUME_SOURCE_NONE) &&
8168 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8169 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008170 sourcesToMute.push_back(source);
8171 }
Eric Laurente552edb2014-03-10 17:42:56 -07008172 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008173 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008174 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008175 }
8176
Eric Laurente552edb2014-03-10 17:42:56 -07008177}
8178
François Gaffieaaac0fd2018-11-22 17:56:39 +01008179void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8180 bool on,
8181 const sp<AudioOutputDescriptor>& outputDesc,
8182 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008183 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008184{
jiabin9a3361e2019-10-01 09:38:30 -07008185 if (deviceTypes.empty()) {
8186 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008187 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008188 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008189 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008190 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008191 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008192 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008193 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8194 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008195 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008196 }
8197 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008198 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8199 // ignored
8200 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008201 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008202 if (!outputDesc->isMuted(volumeSource)) {
8203 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008204 return;
8205 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008206 if (outputDesc->decMuteCount(volumeSource) == 0) {
8207 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008208 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008209 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008210 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008211 delayMs);
8212 }
8213 }
8214}
8215
François Gaffie53615e22015-03-19 09:24:12 +01008216bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8217{
François Gaffiec005e562018-11-06 15:04:49 +01008218 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008219 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8220 return true;
8221 }
8222
8223 // has known usage?
8224 switch (paa->usage) {
8225 case AUDIO_USAGE_UNKNOWN:
8226 case AUDIO_USAGE_MEDIA:
8227 case AUDIO_USAGE_VOICE_COMMUNICATION:
8228 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8229 case AUDIO_USAGE_ALARM:
8230 case AUDIO_USAGE_NOTIFICATION:
8231 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8232 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8233 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8234 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8235 case AUDIO_USAGE_NOTIFICATION_EVENT:
8236 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8237 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8238 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8239 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008240 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008241 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008242 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008243 case AUDIO_USAGE_EMERGENCY:
8244 case AUDIO_USAGE_SAFETY:
8245 case AUDIO_USAGE_VEHICLE_STATUS:
8246 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008247 break;
8248 default:
8249 return false;
8250 }
8251 return true;
8252}
8253
François Gaffie2110e042015-03-24 08:41:51 +01008254audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8255{
8256 return mEngine->getForceUse(usage);
8257}
8258
Eric Laurent96d1dda2022-03-14 17:14:19 +01008259bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008260 return isStateInCall(mEngine->getPhoneState());
8261}
8262
Eric Laurent96d1dda2022-03-14 17:14:19 +01008263bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008264 return is_state_in_call(state);
8265}
8266
Eric Laurentf9cccec2022-11-16 19:12:00 +01008267bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008268 audio_mode_t mode = mEngine->getPhoneState();
8269 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008270 || (mode == AUDIO_MODE_CALL_SCREEN)
8271 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008272}
8273
Eric Laurentf9cccec2022-11-16 19:12:00 +01008274bool AudioPolicyManager::isInCallOrScreening() const {
8275 audio_mode_t mode = mEngine->getPhoneState();
8276 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8277}
8278
Eric Laurentd60560a2015-04-10 11:31:20 -07008279void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8280{
8281 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008282 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008283 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008284 sourceDesc->sinkDevice()->equals(deviceDesc))
8285 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008286 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008287 }
8288 }
8289
8290 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8291 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8292 bool release = false;
8293 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8294 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8295 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8296 source->ext.device.type == deviceDesc->type()) {
8297 release = true;
8298 }
8299 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008300 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008301 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8302 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8303 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008304 sink->ext.device.type == deviceDesc->type() &&
8305 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8306 || strncmp(sink->ext.device.address, address,
8307 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008308 release = true;
8309 }
8310 }
8311 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008312 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8313 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008314 }
8315 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008316
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008317 mInputs.clearSessionRoutesForDevice(deviceDesc);
8318
Francois Gaffie716e1432019-01-14 16:58:59 +01008319 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008320}
8321
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008322void AudioPolicyManager::modifySurroundFormats(
8323 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008324 std::unordered_set<audio_format_t> enforcedSurround(
8325 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008326 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008327 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008328 allSurround.insert(pair.first);
8329 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8330 }
Phil Burk09bc4612016-02-24 15:58:15 -08008331
8332 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8333 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008334 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008335 // This is the resulting set of formats depending on the surround mode:
8336 // 'all surround' = allSurround
8337 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8338 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8339 // 'manual surround' = mManualSurroundFormats
8340 // AUTO: formats v 'enforced surround'
8341 // ALWAYS: formats v 'all surround' v 'enforced surround'
8342 // NEVER: formats ^ 'non-surround'
8343 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008344
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008345 std::unordered_set<audio_format_t> formatSet;
8346 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8347 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008348 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008349 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008350 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008351 formatSet.insert(*formatIter);
8352 }
8353 }
8354 } else {
8355 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8356 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008357 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008358
jiabin81772902018-04-02 17:52:27 -07008359 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008360 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008361 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8362 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8363 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008364 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008365 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8366 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8367 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008368 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008369 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008370 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008371 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008372 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008373 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008374}
8375
jiabin06e4bab2019-07-29 10:13:34 -07008376void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8377 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008378 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8379 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8380
8381 // If NEVER, then remove support for channelMasks > stereo.
8382 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008383 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8384 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008385 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008386 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008387 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008388 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008389 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008390 }
8391 }
jiabin81772902018-04-02 17:52:27 -07008392 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8393 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8394 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008395 bool supports5dot1 = false;
8396 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008397 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008398 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8399 supports5dot1 = true;
8400 break;
8401 }
8402 }
8403 // If not then add 5.1 support.
8404 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008405 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008406 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008407 }
Phil Burk09bc4612016-02-24 15:58:15 -08008408 }
8409}
8410
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008411void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008412 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008413 const sp<IOProfile>& profile) {
8414 if (!profile->hasDynamicAudioProfile()) {
8415 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008416 }
François Gaffie112b0af2015-11-19 16:13:25 +01008417
jiabin12537fc2023-10-12 17:56:08 +00008418 audio_port_v7 devicePort;
8419 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008420
jiabin12537fc2023-10-12 17:56:08 +00008421 audio_port_v7 mixPort;
8422 profile->toAudioPort(&mixPort);
8423 mixPort.ext.mix.handle = ioHandle;
8424
8425 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8426 if (status != NO_ERROR) {
8427 ALOGE("%s failed to query the attributes of the mix port", __func__);
8428 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008429 }
jiabin12537fc2023-10-12 17:56:08 +00008430
8431 std::set<audio_format_t> supportedFormats;
8432 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8433 supportedFormats.insert(mixPort.audio_profiles[i].format);
8434 }
8435 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8436 mReportedFormatsMap[devDesc] = formats;
8437
8438 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8439 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8440 modifySurroundFormats(devDesc, &formats);
8441 size_t modifiedNumProfiles = 0;
8442 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8443 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8444 formats.end()) {
8445 // Skip the format that is not present after modifying surround formats.
8446 continue;
8447 }
8448 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8449 sizeof(struct audio_profile));
8450 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8451 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8452 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8453 modifySurroundChannelMasks(&channels);
8454 std::copy(channels.begin(), channels.end(),
8455 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8456 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8457 }
8458 mixPort.num_audio_profiles = modifiedNumProfiles;
8459 }
8460 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008461}
Eric Laurentd60560a2015-04-10 11:31:20 -07008462
Mikhail Naganovdc769682018-05-04 15:34:08 -07008463status_t AudioPolicyManager::installPatch(const char *caller,
8464 audio_patch_handle_t *patchHandle,
8465 AudioIODescriptorInterface *ioDescriptor,
8466 const struct audio_patch *patch,
8467 int delayMs)
8468{
8469 ssize_t index = mAudioPatches.indexOfKey(
8470 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8471 *patchHandle : ioDescriptor->getPatchHandle());
8472 sp<AudioPatch> patchDesc;
8473 status_t status = installPatch(
8474 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8475 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008476 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008477 }
8478 return status;
8479}
8480
8481status_t AudioPolicyManager::installPatch(const char *caller,
8482 ssize_t index,
8483 audio_patch_handle_t *patchHandle,
8484 const struct audio_patch *patch,
8485 int delayMs,
8486 uid_t uid,
8487 sp<AudioPatch> *patchDescPtr)
8488{
8489 sp<AudioPatch> patchDesc;
8490 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8491 if (index >= 0) {
8492 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008493 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008494 }
8495
8496 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8497 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8498 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8499 if (status == NO_ERROR) {
8500 if (index < 0) {
8501 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008502 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008503 } else {
8504 patchDesc->mPatch = *patch;
8505 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008506 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008507 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008508 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008509 }
8510 nextAudioPortGeneration();
8511 mpClientInterface->onAudioPatchListUpdate();
8512 }
8513 if (patchDescPtr) *patchDescPtr = patchDesc;
8514 return status;
8515}
8516
jiabinbce0c1d2020-10-05 11:20:18 -07008517bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8518{
8519 const TrackClientVector activeClients = output->getActiveClients();
8520 if (activeClients.empty()) {
8521 return true;
8522 }
8523 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8524 if (index < 0) {
8525 ALOGE("%s, no audio patch found while there are active clients on output %d",
8526 __func__, output->getId());
8527 return false;
8528 }
8529 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8530 DeviceVector routedDevices;
8531 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8532 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8533 patchDesc->mPatch.sinks[i].id);
8534 if (device == nullptr) {
8535 ALOGE("%s, no audio device found with id(%d)",
8536 __func__, patchDesc->mPatch.sinks[i].id);
8537 return false;
8538 }
8539 routedDevices.add(device);
8540 }
8541 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008542 if (client->isInvalid()) {
8543 // No need to take care about invalidated clients.
8544 continue;
8545 }
jiabinbce0c1d2020-10-05 11:20:18 -07008546 sp<DeviceDescriptor> preferredDevice =
8547 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8548 if (mEngine->getOutputDevicesForAttributes(
8549 client->attributes(), preferredDevice, false) == routedDevices) {
8550 return false;
8551 }
8552 }
8553 return true;
8554}
8555
8556sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008557 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008558 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8559 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008560{
8561 for (const auto& device : devices) {
8562 // TODO: This should be checking if the profile supports the device combo.
8563 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008564 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8565 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008566 return nullptr;
8567 }
8568 }
8569 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8570 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008571 status_t status = desc->open(halConfig, mixerConfig, devices,
8572 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008573 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008574 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008575 return nullptr;
8576 }
jiabin14b50cc2023-12-13 19:01:52 +00008577 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8578 auto portConfig = desc->getConfig();
8579 for (const auto& device : devices) {
8580 device->setPreferredConfig(&portConfig);
8581 }
8582 }
jiabinbce0c1d2020-10-05 11:20:18 -07008583
8584 // Here is where the out_set_parameters() for card & device gets called
8585 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8586 const audio_devices_t deviceType = device->type();
8587 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008588 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008589 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8590 mpClientInterface->setParameters(output, String8(param));
8591 free(param);
8592 }
jiabin12537fc2023-10-12 17:56:08 +00008593 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008594 if (!profile->hasValidAudioProfile()) {
8595 ALOGW("%s() missing param", __func__);
8596 desc->close();
8597 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008598 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8599 // Reopen the output with the best audio profile picked by APM when the profile supports
8600 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008601 desc->close();
8602 output = AUDIO_IO_HANDLE_NONE;
8603 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8604 profile->pickAudioProfile(
8605 config.sample_rate, config.channel_mask, config.format);
8606 config.offload_info.sample_rate = config.sample_rate;
8607 config.offload_info.channel_mask = config.channel_mask;
8608 config.offload_info.format = config.format;
8609
jiabina84c3d32022-12-02 18:59:55 +00008610 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008611 if (status != NO_ERROR) {
8612 return nullptr;
8613 }
8614 }
8615
8616 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008617
baek.kim -61c20122022-07-27 10:05:32 +00008618 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8619 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8620
jiabinbce0c1d2020-10-05 11:20:18 -07008621 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8622 sp<AudioPolicyMix> policyMix;
8623 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8624 policyMix->setOutput(desc);
8625 desc->mPolicyMix = policyMix;
8626 } else {
8627 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008628 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008629 }
8630
baek.kim -61c20122022-07-27 10:05:32 +00008631 } else if (hasPrimaryOutput() && speaker != nullptr
8632 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008633 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8634 // no duplicated output for:
8635 // - direct outputs
8636 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008637 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008638 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8639
8640 //TODO: configure audio effect output stage here
8641
8642 // open a duplicating output thread for the new output and the primary output
8643 sp<SwAudioOutputDescriptor> dupOutputDesc =
8644 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8645 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8646 if (status == NO_ERROR) {
8647 // add duplicated output descriptor
8648 addOutput(duplicatedOutput, dupOutputDesc);
8649 } else {
8650 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8651 mPrimaryOutput->mIoHandle, output);
8652 desc->close();
8653 removeOutput(output);
8654 nextAudioPortGeneration();
8655 return nullptr;
8656 }
8657 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008658 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8659 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8660 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008661 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008662 }
jiabinbce0c1d2020-10-05 11:20:18 -07008663 return desc;
8664}
8665
jiabinf1c73972022-04-14 16:28:52 -07008666status_t AudioPolicyManager::getDevicesForAttributes(
8667 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8668 // Devices are determined in the following precedence:
8669 //
8670 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8671 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8672 //
8673 // If no such dynamic policy then
8674 // 2) Devices containing an active client using setPreferredDevice
8675 // with same strategy as the attributes.
8676 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8677 //
8678 // If no corresponding active client with setPreferredDevice then
8679 // 3) Devices associated with the strategy determined by the attributes
8680 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8681 //
8682 // See related getOutputForAttrInt().
8683
8684 // check dynamic policies but only for primary descriptors (secondary not used for audible
8685 // audio routing, only used for duplication for playback capture)
8686 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008687 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008688 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008689 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8690 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8691 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008692 if (status != OK) {
8693 return status;
8694 }
8695
8696 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8697 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8698 // as they are unaffected by device/stream volume
8699 // (per SwAudioOutputDescriptor::isFixedVolume()).
8700 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8701 ) {
8702 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8703 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8704 devices.add(deviceDesc);
8705 } else {
8706 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8707 // which selects setPreferredDevice if active. This means forVolume call
8708 // will take an active setPreferredDevice, if such exists.
8709
8710 devices = mEngine->getOutputDevicesForAttributes(
8711 attr, nullptr /* preferredDevice */, false /* fromCache */);
8712 }
8713
8714 if (forVolume) {
8715 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8716 // for single volume control in AudioService (such relationship should exist if
8717 // SPEAKER_SAFE is present).
8718 //
8719 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8720 DeviceVector speakerSafeDevices =
8721 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8722 if (!speakerSafeDevices.isEmpty()) {
8723 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8724 devices.remove(speakerSafeDevices);
8725 }
8726 }
8727
8728 return NO_ERROR;
8729}
8730
8731status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8732 AudioProfileVector& audioProfiles,
8733 uint32_t flags,
8734 bool isInput) {
8735 for (const auto& hwModule : mHwModules) {
8736 // the MSD module checks for different conditions
8737 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8738 continue;
8739 }
8740 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8741 : hwModule->getOutputProfiles();
8742 for (const auto& profile : ioProfiles) {
8743 if (!profile->areAllDevicesSupported(devices) ||
8744 !profile->isCompatibleProfileForFlags(
8745 flags, false /*exactMatchRequiredForInputFlags*/)) {
8746 continue;
8747 }
8748 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8749 }
8750 }
8751
8752 if (!isInput) {
8753 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8754 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8755 if (msdModule != nullptr) {
8756 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8757 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8758 for (const auto &profile: msdModule->getOutputProfiles()) {
8759 if (!profile->asAudioPort()->isDirectOutput()) {
8760 continue;
8761 }
8762 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8763 }
8764 } else {
8765 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8766 }
8767 }
8768 }
8769
8770 return NO_ERROR;
8771}
8772
jiabin3ff8d7d2022-12-13 06:27:44 +00008773sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8774 const audio_config_t *config,
8775 audio_output_flags_t flags,
8776 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008777 closeOutput(outputDesc->mIoHandle);
8778 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8779 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8780 if (preferredOutput == nullptr) {
8781 ALOGE("%s failed to reopen output device=%d, caller=%s",
8782 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008783 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008784 return preferredOutput;
8785}
8786
8787void AudioPolicyManager::reopenOutputsWithDevices(
8788 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8789 for (const auto& [output, devices] : outputsToReopen) {
8790 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8791 closeOutput(output);
8792 openOutputWithProfileAndDevice(desc->mProfile, devices);
8793 }
jiabina84c3d32022-12-02 18:59:55 +00008794}
8795
jiabinc44b3462022-12-08 12:52:31 -08008796PortHandleVector AudioPolicyManager::getClientsForStream(
8797 audio_stream_type_t streamType) const {
8798 PortHandleVector clients;
8799 for (size_t i = 0; i < mOutputs.size(); ++i) {
8800 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8801 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8802 }
8803 return clients;
8804}
8805
8806void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8807 PortHandleVector clients;
8808 for (auto stream : streams) {
8809 PortHandleVector clientsForStream = getClientsForStream(stream);
8810 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8811 }
8812 mpClientInterface->invalidateTracks(clients);
8813}
8814
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008815} // namespace android