blob: 3e693ecaf71890610aafd5b119c0a46dab13512e [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200399
Eric Laurent0dd51852019-04-19 18:18:58 -0700400 if (checkInputsForDevice(device, state) != NO_ERROR) {
401 mAvailableInputDevices.remove(device);
402
jiabinc0048632023-04-27 22:04:31 +0000403 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100404
405 mHwModules.cleanUpForDevice(device);
406
Eric Laurentd4692962014-05-05 18:13:44 -0700407 return INVALID_OPERATION;
408 }
409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700414 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return INVALID_OPERATION;
417 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
jiabinc0048632023-04-27 22:04:31 +0000421 // Notify the HAL to prepare to disconnect device
422 broadcastDeviceConnectionState(
423 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
François Gaffie11d30102018-11-02 16:09:09 +0100425 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700426
427 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428
jiabinc0048632023-04-27 22:04:31 +0000429 // Set Disconnect to HALs
430 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
431
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432 // remove device from mReportedFormatsMap cache
433 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700435
436 default:
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return BAD_VALUE;
439 }
440
Eric Laurent736a1022019-03-27 18:28:46 -0700441 // Propagate device availability to Engine
442 setEngineDeviceConnectionState(device, state);
443
Eric Laurent0dd51852019-04-19 18:18:58 -0700444 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700445 // As the input device list can impact the output device selection, update
446 // getDeviceForStrategy() cache
447 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700448
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100449 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200450 // Reconnect Audio Source
451 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
452 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
453 checkAudioSourceForAttributes(attributes);
454 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100456 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700457 }
458
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700461 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700462
François Gaffie11d30102018-11-02 16:09:09 +0100463 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return BAD_VALUE;
465}
466
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
468 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800469 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700470 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
471 devDescr->setName(device_name);
472 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100473}
474
Eric Laurent736a1022019-03-27 18:28:46 -0700475void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
476 audio_policy_dev_state_t state) {
477
478 // the Engine does not have to know about remote submix devices used by dynamic audio policies
479 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
480 return;
481 }
482 mEngine->setDeviceConnectionState(device, state);
483}
484
485
Eric Laurente0720872014-03-11 09:30:41 -0700486audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100487 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700488{
Eric Laurent634b7142016-04-20 13:48:02 -0700489 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
491 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700492 (strlen(device_address) != 0)/*matchAddress*/);
493
494 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100495 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700496 device, device_address);
497 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
498 }
François Gaffie53615e22015-03-19 09:24:12 +0100499
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 DeviceVector *deviceVector;
501
Eric Laurente552edb2014-03-10 17:42:56 -0700502 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 deviceVector = &mAvailableInputDevices;
506 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100507 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 }
Eric Laurent634b7142016-04-20 13:48:02 -0700510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 return (deviceVector->getDevice(
512 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800514}
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
517 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 const char *device_name,
519 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
522 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800524 // connect/disconnect only 1 device at a time
525 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
526
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700528 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530 // Nothing to do: device is not connected
531 return NO_ERROR;
532 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700535 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800536 // configure codecs.
537 // Handle two specific cases by sending a set parameter to
538 // configure A2DP codecs. No need to toggle device state.
539 // Case 1: A2DP active device switches from primary to primary
540 // module
541 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700543 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
545 if (availablePrimaryOutputDevices().contains(devDesc) &&
546 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 bool isA2dp = audio_is_a2dp_out_device(device);
548 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
549 : String8(AudioParameter::keyReconfigLeSupported);
550 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 int isReconfigSupported;
553 repliedParameters.getInt(supportKey, isReconfigSupported);
554 if (isReconfigSupported) {
555 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
556 : String8(AudioParameter::keyReconfigLe);
557 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 param.add(key, String8("true"));
559 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
560 devDesc->setEncodedFormat(encodedFormat);
561 return NO_ERROR;
562 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700563 }
564 }
cnx421bd2dcc42020-07-11 14:58:44 +0800565 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
566 for (size_t i = 0; i < mOutputs.size(); i++) {
567 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
568 // mute media strategies and delay device switch by the largest
569 // This avoid sending the music tail into the earpiece or headset.
570 setStrategyMute(musicStrategy, true, desc);
571 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
572 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
573 nullptr, true /*fromCache*/).types());
574 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 // Toggle the device state: UNAVAILABLE -> AVAILABLE
576 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100577 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800578 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 device_address, device_name,
580 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800581 if (status != NO_ERROR) {
582 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
583 status);
584 return status;
585 }
586
587 status = setDeviceConnectionState(device,
588 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800589 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800590 if (status != NO_ERROR) {
591 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
592 status);
593 return status;
594 }
595
596 return NO_ERROR;
597}
598
Pattydd807582021-11-04 21:01:03 +0800599status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
600 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800601{
Pattydd807582021-11-04 21:01:03 +0800602 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800603 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800604 std::unordered_set<audio_format_t> formatSet;
605 sp<HwModule> primaryModule =
606 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700607 if (primaryModule == nullptr) {
608 ALOGE("%s() unable to get primary module", __func__);
609 return NO_INIT;
610 }
Pattydd807582021-11-04 21:01:03 +0800611
612 DeviceTypeSet audioDeviceSet;
613
614 switch(device) {
615 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
616 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
617 break;
618 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800619 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
620 break;
621 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
622 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800623 break;
624 default:
625 ALOGE("%s() device type 0x%08x not supported", __func__, device);
626 return BAD_VALUE;
627 }
628
jiabin9a3361e2019-10-01 09:38:30 -0700629 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800630 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800631 for (const auto& device : declaredDevices) {
632 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800633 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800634 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800635 return status;
636}
637
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100638DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
639{
640 DeviceVector rxSinkdevices{};
641 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
642 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
643 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
644 auto rxSinkDevice = rxSinkdevices.itemAt(0);
645 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
646 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
647 // retrieve Rx Source device descriptor
648 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
649 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
650
651 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
652 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
653 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
654 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
655 return DeviceVector(rxSinkDevice);
656 }
657 }
658 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
659 // the device returned is not necessarily reachable via this output
660 // (filter later by setOutputDevices())
661 return getNewOutputDevices(mPrimaryOutput, fromCache);
662}
663
664status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
665{
François Gaffiedb1755b2023-09-01 11:50:35 +0200666 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
668 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
669 }
670 return INVALID_OPERATION;
671}
672
673status_t AudioPolicyManager::updateCallRoutingInternal(
674 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675{
676 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100677 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700678 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200679 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700680 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 }
François Gaffie11d30102018-11-02 16:09:09 +0100683
Francois Gaffie716e1432019-01-14 16:58:59 +0100684 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100685 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200686
687 disconnectTelephonyAudioSource(mCallRxSourceClient);
688 disconnectTelephonyAudioSource(mCallTxSourceClient);
689
690 if (rxDevices.isEmpty()) {
691 ALOGW("%s() no selected output device", __func__);
692 return INVALID_OPERATION;
693 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000694 if (txSourceDevice == nullptr) {
695 ALOGE("%s() selected input device not available", __func__);
696 return INVALID_OPERATION;
697 }
François Gaffiec005e562018-11-06 15:04:49 +0100698
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100699 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100700 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700701
François Gaffie9eb18552018-11-05 10:33:26 +0100702 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700703 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100704 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700705 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100706 // retrieve Rx Source and Tx Sink device descriptors
707 sp<DeviceDescriptor> rxSourceDevice =
708 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
709 String8(),
710 AUDIO_FORMAT_DEFAULT);
711 sp<DeviceDescriptor> txSinkDevice =
712 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
713 String8(),
714 AUDIO_FORMAT_DEFAULT);
715
716 // RX and TX Telephony device are declared by Primary Audio HAL
717 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
718 (telephonyRxModule->getHalVersionMajor() >= 3)) {
719 if (rxSourceDevice == 0 || txSinkDevice == 0) {
720 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100721 ALOGE("%s() no telephony Tx and/or RX device", __func__);
722 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100723 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100724 // createAudioPatchInternal now supports both HW / SW bridging
725 createRxPatch = true;
726 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100727 } else {
728 // If the RX device is on the primary HW module, then use legacy routing method for
729 // voice calls via setOutputDevice() on primary output.
730 // Otherwise, create two audio patches for TX and RX path.
731 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
732 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733 // If the TX device is also on the primary HW module, setOutputDevice() will take care
734 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100735 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
736 (txSinkDevice != 0);
737 }
738 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
739 // Otherwise, create two audio patches for TX and RX path.
740 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200741 if (!hasPrimaryOutput()) {
742 ALOGW("%s() no primary output available", __func__);
743 return INVALID_OPERATION;
744 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530745 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700746 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200747 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800748 // If the TX device is on the primary HW module but RX device is
749 // on other HW module, SinkMetaData of telephony input should handle it
750 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700751 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700752 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100753 // terminate active capture if on the same HW module as the call TX source device
754 // FIXME: would be better to refine to only inputs whose profile connects to the
755 // call TX device but this information is not in the audio patch and logic here must be
756 // symmetric to the one in startInput()
757 for (const auto& activeDesc : mInputs.getActiveInputs()) {
758 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
759 closeActiveClients(activeDesc);
760 }
761 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200762 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100764 if (waitMs != nullptr) {
765 *waitMs = muteWaitMs;
766 }
767 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800768}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700769
Mikhail Naganov100f0122018-11-29 11:22:16 -0800770bool AudioPolicyManager::isDeviceOfModule(
771 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
772 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
773 if (module != 0) {
774 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
775 .indexOf(devDesc) != NAME_NOT_FOUND
776 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
777 .indexOf(devDesc) != NAME_NOT_FOUND;
778 }
779 return false;
780}
781
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200782void AudioPolicyManager::connectTelephonyRxAudioSource()
783{
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200785 const struct audio_port_config source = {
786 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
787 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
788 };
789 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100790
791 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
792 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
793 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
794 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 ALOGE_IF(mCallRxSourceClient == nullptr,
796 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200797}
798
Francois Gaffie601801d2021-06-22 13:27:39 +0200799void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200800{
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 if (clientDesc == nullptr) {
802 return;
803 }
804 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
805 "%s error stopping audio source", __func__);
806 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807}
808
809void AudioPolicyManager::connectTelephonyTxAudioSource(
810 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
811 uint32_t delayMs)
812{
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200814 if (srcDevice == nullptr || sinkDevice == nullptr) {
815 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
816 return;
817 }
818 PatchBuilder patchBuilder;
819 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
820 ALOGV("%s between source %s and sink %s", __func__,
821 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200822 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200823 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
824
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 struct audio_port_config source = {};
826 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100827 mCallTxSourceClient = new SourceClientDescriptor(
828 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
829 mCommunnicationStrategy, toVolumeSource(aa), true);
830 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
831
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
833 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200834 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
835 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200836 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
837 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200839 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200840}
841
Eric Laurente0720872014-03-11 09:30:41 -0700842void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700843{
844 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100845 // store previous phone state for management of sonification strategy below
846 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100847 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100848
849 if (mEngine->setPhoneState(state) != NO_ERROR) {
850 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700851 return;
852 }
François Gaffie2110e042015-03-24 08:41:51 +0100853 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700854 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700855 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700856 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800857 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
859
François Gaffie2110e042015-03-24 08:41:51 +0100860 /**
861 * Switching to or from incall state or switching between telephony and VoIP lead to force
862 * routing command.
863 */
Eric Laurent74b71512019-11-06 17:21:57 -0800864 bool force = ((isStateInCall(oldState) != isStateInCall(state))
865 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700866
867 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700868 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700869
Eric Laurente552edb2014-03-10 17:42:56 -0700870 int delayMs = 0;
871 if (isStateInCall(state)) {
872 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100873 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
874 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700875 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 // mute media and sonification strategies and delay device switch by the largest
878 // latency of any output where either strategy is active.
879 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100880 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
881 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
882 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700883 (delayMs < (int)desc->latency()*2)) {
884 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700885 }
François Gaffiec005e562018-11-06 15:04:49 +0100886 setStrategyMute(musicStrategy, true, desc);
887 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
888 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
889 nullptr, true /*fromCache*/).types());
890 setStrategyMute(sonificationStrategy, true, desc);
891 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
892 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
893 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700894 }
895 }
896
François Gaffiedb1755b2023-09-01 11:50:35 +0200897 if (state == AUDIO_MODE_IN_CALL) {
898 (void)updateCallRouting(false /*fromCache*/, delayMs);
899 } else {
900 if (oldState == AUDIO_MODE_IN_CALL) {
901 disconnectTelephonyAudioSource(mCallRxSourceClient);
902 disconnectTelephonyAudioSource(mCallTxSourceClient);
903 }
904 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100905 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
906 // force routing command to audio hardware when ending call
907 // even if no device change is needed
908 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
909 rxDevices = mPrimaryOutput->devices();
910 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530911 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700912 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700913 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700914
jiabin3ff8d7d2022-12-13 06:27:44 +0000915 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700916 // reevaluate routing on all outputs in case tracks have been started during the call
917 for (size_t i = 0; i < mOutputs.size(); i++) {
918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100919 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000920 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
921 && desc->mPreferredAttrInfo != nullptr) {
922 // If the output is using preferred mixer attributes and the audio mode is not normal,
923 // the output need to reopen with default configuration.
924 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
925 continue;
926 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200927 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
928 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530929 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200930 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700931 }
932 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000933 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700934
Eric Laurent96d1dda2022-03-14 17:14:19 +0100935 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 if (isStateInCall(state)) {
938 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800940 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942
943 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100944 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
945 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700946}
947
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700948audio_mode_t AudioPolicyManager::getPhoneState() {
949 return mEngine->getPhoneState();
950}
951
Eric Laurente0720872014-03-11 09:30:41 -0700952void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100953 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700954{
François Gaffie2110e042015-03-24 08:41:51 +0100955 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700956 if (config == mEngine->getForceUse(usage)) {
957 return;
958 }
Eric Laurente552edb2014-03-10 17:42:56 -0700959
François Gaffie2110e042015-03-24 08:41:51 +0100960 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
961 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
962 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700963 }
François Gaffie2110e042015-03-24 08:41:51 +0100964 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
965 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
966 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700967
968 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700969 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800970
Eric Laurent22fcda22019-05-17 16:28:47 -0700971 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
972 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800973 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700974 }
975
Eric Laurentdc462862016-07-19 12:29:53 -0700976 //FIXME: workaround for truncated touch sounds
977 // to be removed when the problem is handled by system UI
978 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700979 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
980 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
981 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700982
983 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100984 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700985}
986
Eric Laurente0720872014-03-11 09:30:41 -0700987void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700988{
989 ALOGV("setSystemProperty() property %s, value %s", property, value);
990}
991
Dorin Drimusecc9f422022-03-09 17:57:40 +0100992// Find an MSD output profile compatible with the parameters passed.
993// When "directOnly" is set, restrict search to profiles for direct outputs.
994sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
995 const DeviceVector& devices,
996 uint32_t samplingRate,
997 audio_format_t format,
998 audio_channel_mask_t channelMask,
999 audio_output_flags_t flags,
1000 bool directOnly)
1001{
1002 flags = getRelevantFlags(flags, directOnly);
1003
1004 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1005 if (msdModule != nullptr) {
1006 // for the msd module check if there are patches to the output devices
1007 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1008 HwModuleCollection modules;
1009 modules.add(msdModule);
1010 return searchCompatibleProfileHwModules(
1011 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1012 flags, directOnly);
1013 }
1014 }
1015 return nullptr;
1016}
1017
Michael Chana94fbb22018-04-24 14:31:19 +10001018// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1019// search to profiles for direct outputs.
1020sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001021 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001022 uint32_t samplingRate,
1023 audio_format_t format,
1024 audio_channel_mask_t channelMask,
1025 audio_output_flags_t flags,
1026 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001027{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 flags = getRelevantFlags(flags, directOnly);
1029
1030 return searchCompatibleProfileHwModules(
1031 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1032}
1033
1034audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1035 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001036 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 // only retain flags that will drive the direct output profile selection
1038 // if explicitly requested
1039 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001040 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001041 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1042 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001043 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 return flags;
1045}
Eric Laurent861a6282015-05-18 15:40:16 -07001046
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1048 const HwModuleCollection& hwModules,
1049 const DeviceVector& devices,
1050 uint32_t samplingRate,
1051 audio_format_t format,
1052 audio_channel_mask_t channelMask,
1053 audio_output_flags_t flags,
1054 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001055 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001056 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001057 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001058 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059 samplingRate, NULL /*updatedSamplingRate*/,
1060 format, NULL /*updatedFormat*/,
1061 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001062 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 continue;
1064 }
1065 // reject profiles not corresponding to a device currently available
1066 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1067 continue;
1068 }
1069 // reject profiles if connected device does not support codec
1070 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1071 continue;
1072 }
1073 if (!directOnly) {
1074 return curProfile;
1075 }
1076
1077 // when searching for direct outputs, if several profiles are compatible, give priority
1078 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001079 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001080 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001081 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001082 }
1083 profile = curProfile;
1084 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1085 break;
1086 }
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
1088 }
Eric Laurent861a6282015-05-18 15:40:16 -07001089 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001090}
1091
Eric Laurentfa0f6742021-08-17 18:39:44 +02001092sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001093 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001094{
1095 for (const auto& hwModule : mHwModules) {
1096 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001097 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098 continue;
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001101 // reject profiles not corresponding to a device currently available
1102 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1103 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1104 continue;
1105 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1107 != devices.size()) {
1108 continue;
1109 }
1110 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001111 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1112 return curProfile;
1113 }
1114 }
1115 return nullptr;
1116}
1117
Eric Laurentf4e63452017-11-06 19:31:46 +00001118audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001119{
François Gaffiec005e562018-11-06 15:04:49 +01001120 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001121
1122 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1123 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1124 // format, flags, etc. This may result in some discrepancy for functions that utilize
1125 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1126 // and AudioSystem::getOutputSamplingRate().
1127
François Gaffie11d30102018-11-02 16:09:09 +01001128 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001129 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1130 if (stream == AUDIO_STREAM_MUSIC &&
1131 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1132 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1133 }
1134 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001135
François Gaffie11d30102018-11-02 16:09:09 +01001136 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1137 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001138 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001139}
1140
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1142 const audio_attributes_t *srcAttr,
1143 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001144{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001145 if (srcAttr != NULL) {
1146 if (!isValidAttributes(srcAttr)) {
1147 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1148 __func__,
1149 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1150 srcAttr->tags);
1151 return BAD_VALUE;
1152 }
1153 *dstAttr = *srcAttr;
1154 } else {
1155 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1156 ALOGE("%s: invalid stream type", __func__);
1157 return BAD_VALUE;
1158 }
François Gaffiec005e562018-11-06 15:04:49 +01001159 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001160 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001161
1162 // Only honor audibility enforced when required. The client will be
1163 // forced to reconnect if the forced usage changes.
1164 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001165 dstAttr->flags = static_cast<audio_flags_mask_t>(
1166 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001167 }
1168
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169 return NO_ERROR;
1170}
1171
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172status_t AudioPolicyManager::getOutputForAttrInt(
1173 audio_attributes_t *resultAttr,
1174 audio_io_handle_t *output,
1175 audio_session_t session,
1176 const audio_attributes_t *attr,
1177 audio_stream_type_t *stream,
1178 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001179 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180 audio_output_flags_t *flags,
1181 audio_port_handle_t *selectedDeviceId,
1182 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001183 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001185 bool *isSpatialized,
1186 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001187{
François Gaffiec005e562018-11-06 15:04:49 +01001188 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001189 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001190 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001191 const sp<DeviceDescriptor> requestedDevice =
1192 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1193
Eric Laurent8a1095a2019-11-08 14:44:16 -08001194 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001195 *isSpatialized = false;
1196
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001197 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1198 if (status != NO_ERROR) {
1199 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001200 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001201 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001202 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001203 }
François Gaffiec005e562018-11-06 15:04:49 +01001204 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001205
François Gaffiec005e562018-11-06 15:04:49 +01001206 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1207 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001208
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 bool usePrimaryOutputFromPolicyMixes = false;
1210
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1212 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1213 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001215 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1216 .channel_mask = config->channel_mask,
1217 .format = config->format,
1218 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001219 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001220 mAvailableOutputDevices, requestedDevice, primaryMix,
1221 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001222 if (status != OK) {
1223 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001224 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001225
Kevin Rocard153f92d2018-12-18 18:33:28 -08001226 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001227 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1228 && !audio_is_linear_pcm(config->format)) {
1229 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 return BAD_VALUE;
1231 }
1232 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001233 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1235 primaryMix->mDeviceAddress,
1236 AUDIO_FORMAT_DEFAULT);
1237 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001238 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001239 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1240 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001241 // if a direct output can be opened to deliver the track's multi-channel content to the
1242 // output rather than being downmixed by the primary output, then use this direct
1243 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1244 // mix.
1245 bool tryDirectForChannelMask = policyDesc != nullptr
1246 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1247 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001248 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001249 audio_io_handle_t newOutput;
1250 status = openDirectOutput(
1251 *stream, session, config,
1252 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001253 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001255 policyDesc = mOutputs.valueFor(newOutput);
1256 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001257 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001258 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001259 policyDesc = nullptr;
1260 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001261 }
1262 if (policyDesc != nullptr) {
1263 policyDesc->mPolicyMix = primaryMix;
1264 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001265 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1266 : AUDIO_PORT_HANDLE_NONE;
1267 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1268 // Remove direct flag as it is not on a direct output.
1269 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1270 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001271
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001272 ALOGV("getOutputForAttr() returns output %d", *output);
1273 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1274 *outputType = API_OUT_MIX_PLAYBACK;
1275 } else {
1276 *outputType = API_OUTPUT_LEGACY;
1277 }
1278 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001279 } else {
1280 if (policyMixDevice != nullptr) {
1281 ALOGE("%s, try to use primary mix but no output found", __func__);
1282 return INVALID_OPERATION;
1283 }
1284 // Fallback to default engine selection as the selected primary mix device is not
1285 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001286 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287 }
François Gaffiec005e562018-11-06 15:04:49 +01001288 // Virtual sources must always be dynamicaly or explicitly routed
1289 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1290 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1291 return BAD_VALUE;
1292 }
1293 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1294 // in order to let the choice of the order to future vendor engine
1295 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001296
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001297 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001298 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001299 }
1300
Nadav Barb2f18162018-07-18 13:01:53 +03001301 // Set incall music only if device was explicitly set, and fallback to the device which is
1302 // chosen by the engine if not.
1303 // FIXME: provide a more generic approach which is not device specific and move this back
1304 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001305 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001306 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001307 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001308 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001309 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001310 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001311 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001312 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001313 }
1314 }
1315
François Gaffiec005e562018-11-06 15:04:49 +01001316 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1317 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1318 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001319
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001320 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001321 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001322 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001323 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001324 ALOGV("%s() Using MSD devices %s instead of devices %s",
1325 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001326 } else {
1327 *output = AUDIO_IO_HANDLE_NONE;
1328 }
1329 }
1330 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001331 sp<PreferredMixerAttributesInfo> info = nullptr;
1332 if (outputDevices.size() == 1) {
1333 info = getPreferredMixerAttributesInfo(
1334 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001335 mEngine->getProductStrategyForAttributes(*resultAttr),
1336 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001337 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1338 // and it is currently active.
1339 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001340 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001341 info = nullptr;
1342 }
jiabin220eea12024-05-17 17:55:20 +00001343 if (com::android::media::audioserver::
1344 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1345 if (info != nullptr && info->getUid() == uid &&
1346 info->configMatches(*config) &&
1347 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1348 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1349 [this, &outputDevices](audio_usage_t usage) {
1350 return mOutputs.isUsageActiveOnDevice(
1351 usage, outputDevices[0]); }))) {
1352 // Bit-perfect request is not allowed when the phone mode is not normal or
1353 // there is any higher priority user case active.
1354 return INVALID_OPERATION;
1355 }
1356 }
jiabina84c3d32022-12-02 18:59:55 +00001357 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001358 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001359 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001360 // The client will be active if the client is currently preferred mixer owner and the
1361 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001362 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001363 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001364 && info->getUid() == uid
1365 && *output != AUDIO_IO_HANDLE_NONE
1366 // When bit-perfect output is selected for the preferred mixer attributes owner,
1367 // only need to consider the config matches.
1368 && mOutputs.valueFor(*output)->isConfigurationMatched(
1369 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001370
1371 if (*isBitPerfect) {
1372 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1373 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001374 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001375 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001376 AudioProfileVector profiles;
1377 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1378 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001379 const auto channels = profiles[0]->getChannels();
1380 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1381 config->channel_mask = *channels.begin();
1382 }
1383 const auto sampleRates = profiles[0]->getSampleRates();
1384 if (!sampleRates.empty() &&
1385 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1386 config->sample_rate = *sampleRates.begin();
1387 }
jiabinf1c73972022-04-14 16:28:52 -07001388 config->format = profiles[0]->getFormat();
1389 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001390 return INVALID_OPERATION;
1391 }
Paul McLeanaa981192015-03-21 09:55:15 -07001392
François Gaffiec005e562018-11-06 15:04:49 +01001393 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001394 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001395 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001396 *selectedDeviceId = outputDevice->getId();
1397 break;
1398 }
1399 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001400
Eric Laurent8a1095a2019-11-08 14:44:16 -08001401 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1402 *outputType = API_OUTPUT_TELEPHONY_TX;
1403 } else {
1404 *outputType = API_OUTPUT_LEGACY;
1405 }
1406
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001407 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1408
1409 return NO_ERROR;
1410}
1411
1412status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1413 audio_io_handle_t *output,
1414 audio_session_t session,
1415 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001416 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001417 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001418 audio_output_flags_t *flags,
1419 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001420 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001421 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001422 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001423 bool *isSpatialized,
1424 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001425{
1426 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1427 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1428 return INVALID_OPERATION;
1429 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001430 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001431 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001432 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001433 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001434 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001435 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001436 const sp<DeviceDescriptor> requestedDevice =
1437 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1438
1439 // Prevent from storing invalid requested device id in clients
1440 const audio_port_handle_t sanitizedRequestedPortId =
1441 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1442 *selectedDeviceId = sanitizedRequestedPortId;
1443
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001444 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001445 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001446 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1447 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001448 if (status != NO_ERROR) {
1449 return status;
1450 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001451 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001452 if (secondaryOutputs != nullptr) {
1453 for (auto &secondaryMix : secondaryMixes) {
1454 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1455 if (outputDesc != nullptr &&
1456 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1457 secondaryOutputs->push_back(outputDesc->mIoHandle);
1458 weakSecondaryOutputDescs.push_back(outputDesc);
1459 }
1460 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001461 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001462
Eric Laurent8fc147b2018-07-22 19:13:55 -07001463 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001464 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001465 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001466 };
jiabin4ef93452019-09-10 14:29:54 -07001467 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001468
Eric Laurentc209fe42020-06-05 18:11:23 -07001469 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001470 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001471 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001472 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001473 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001474 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001475 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001476 std::move(weakSecondaryOutputDescs),
1477 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001478 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001479
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001480 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1481 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001482
Eric Laurente83b55d2014-11-14 10:06:21 -08001483 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001484}
1485
Eric Laurentc529cf62020-04-17 18:19:10 -07001486status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1487 audio_session_t session,
1488 const audio_config_t *config,
1489 audio_output_flags_t flags,
1490 const DeviceVector &devices,
1491 audio_io_handle_t *output) {
1492
1493 *output = AUDIO_IO_HANDLE_NONE;
1494
1495 // skip direct output selection if the request can obviously be attached to a mixed output
1496 // and not explicitly requested
1497 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1498 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1499 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1500 return NAME_NOT_FOUND;
1501 }
1502
1503 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1504 // This prevents creating an offloaded track and tearing it down immediately after start
1505 // when audioflinger detects there is an active non offloadable effect.
1506 // FIXME: We should check the audio session here but we do not have it in this context.
1507 // This may prevent offloading in rare situations where effects are left active by apps
1508 // in the background.
1509 sp<IOProfile> profile;
1510 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1511 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1512 profile = getProfileForOutput(
1513 devices, config->sample_rate, config->format, config->channel_mask,
1514 flags, true /* directOnly */);
1515 }
1516
1517 if (profile == nullptr) {
1518 return NAME_NOT_FOUND;
1519 }
1520
1521 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1522 for (size_t i = 0; i < mOutputs.size(); i++) {
1523 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1524 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1525 // reuse direct output if currently open by the same client
1526 // and configured with same parameters
1527 if ((config->sample_rate == desc->getSamplingRate()) &&
1528 (config->format == desc->getFormat()) &&
1529 (config->channel_mask == desc->getChannelMask()) &&
1530 (session == desc->mDirectClientSession)) {
1531 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001532 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001533 mOutputs.keyAt(i), session);
1534 *output = mOutputs.keyAt(i);
1535 return NO_ERROR;
1536 }
1537 }
1538 }
1539
1540 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001541 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1542 return NAME_NOT_FOUND;
1543 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1544 // MMAP gracefully handles lack of an exclusive track resource by mixing
1545 // above the audio framework. For AAudio to know that the limit is reached,
1546 // return an error.
1547 return NAME_NOT_FOUND;
1548 } else {
1549 // Close outputs on this profile, if available, to free resources for this request
1550 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1551 const auto desc = mOutputs.valueAt(i);
1552 if (desc->mProfile == profile) {
1553 closeOutput(desc->mIoHandle);
1554 }
1555 }
1556 }
1557 }
1558
1559 // Unable to close streams to find free resources for this request
1560 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001561 return NAME_NOT_FOUND;
1562 }
1563
Atneya Nairb16666a2023-12-11 20:18:33 -08001564 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001565
Michael Chan6fb34492020-12-08 15:44:49 +11001566 // An MSD patch may be using the only output stream that can service this request. Release
1567 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001568 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001569
Eric Laurentf1f22e72021-07-13 14:04:14 +02001570 status_t status =
1571 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001572
1573 // only accept an output with the requested parameters
1574 if (status != NO_ERROR ||
1575 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1576 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1577 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1578 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1579 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1580 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1581 config->channel_mask, outputDesc->getChannelMask());
1582 if (*output != AUDIO_IO_HANDLE_NONE) {
1583 outputDesc->close();
1584 }
1585 // fall back to mixer output if possible when the direct output could not be open
1586 if (audio_is_linear_pcm(config->format) &&
1587 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1588 return NAME_NOT_FOUND;
1589 }
1590 *output = AUDIO_IO_HANDLE_NONE;
1591 return BAD_VALUE;
1592 }
1593 outputDesc->mDirectOpenCount = 1;
1594 outputDesc->mDirectClientSession = session;
1595
1596 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001597 setOutputDevices(__func__, outputDesc,
1598 devices,
1599 true,
1600 0,
1601 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001602 mPreviousOutputs = mOutputs;
1603 ALOGV("%s returns new direct output %d", __func__, *output);
1604 mpClientInterface->onAudioPortListUpdate();
1605 return NO_ERROR;
1606}
1607
François Gaffie11d30102018-11-02 16:09:09 +01001608audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1609 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001610 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001611 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001612 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001613 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001614 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001615 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001616 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001617{
Andy Hungc88b0642018-04-27 15:42:35 -07001618 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001619
jiabine375d412019-02-26 12:54:53 -08001620 // Discard haptic channel mask when forcing muting haptic channels.
1621 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001622 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1623 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001624
Eric Laurente552edb2014-03-10 17:42:56 -07001625 // open a direct output if required by specified parameters
1626 //force direct flag if offload flag is set: offloading implies a direct output stream
1627 // and all common behaviors are driven by checking only the direct flag
1628 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001629 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1630 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001631 }
Nadav Bar766fb022018-01-07 12:18:03 +02001632 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1633 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001634 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001635
1636 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1637
Eric Laurente83b55d2014-11-14 10:06:21 -08001638 // only allow deep buffering for music stream type
1639 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001640 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001641 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001642 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001643 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1644 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001645 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001646 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001647 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001648 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001649 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001650 audio_is_linear_pcm(config->format) &&
1651 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001652 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001653 AUDIO_OUTPUT_FLAG_DIRECT);
1654 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001655 }
Eric Laurente552edb2014-03-10 17:42:56 -07001656
Carter Hsua3abb402021-10-26 11:11:20 +08001657 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1658 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1659 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1660 }
1661
Eric Laurentf9230d52024-01-26 18:49:09 +01001662 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001663 // was specified and offload or direct playback is not explicitly requested, and there is no
1664 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001665 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001666 if (mSpatializerOutput != nullptr &&
1667 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1668 prefMixerConfigInfo == nullptr &&
1669 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1670 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001671 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001672 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001673 }
1674
Eric Laurentc529cf62020-04-17 18:19:10 -07001675 audio_config_t directConfig = *config;
1676 directConfig.channel_mask = channelMask;
1677 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1678 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001679 return output;
1680 }
1681
Eric Laurent14cbfca2016-03-17 09:42:16 -07001682 // A request for HW A/V sync cannot fallback to a mixed output because time
1683 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001684 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001685 return AUDIO_IO_HANDLE_NONE;
1686 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001687 // A request for Tuner cannot fallback to a mixed output
1688 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1689 return AUDIO_IO_HANDLE_NONE;
1690 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001691
Eric Laurente552edb2014-03-10 17:42:56 -07001692 // ignoring channel mask due to downmix capability in mixer
1693
1694 // open a non direct output
1695
1696 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001697 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001698 // get which output is suitable for the specified stream. The actual
1699 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001700 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001701 if (prefMixerConfigInfo != nullptr) {
1702 for (audio_io_handle_t outputHandle : outputs) {
1703 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1704 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1705 output = outputHandle;
1706 break;
1707 }
1708 }
1709 if (output == AUDIO_IO_HANDLE_NONE) {
1710 // No output open with the preferred profile. Open a new one.
1711 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1712 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1713 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1714 config.format = prefMixerConfigInfo->getConfigBase().format;
1715 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1716 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1717 &config, prefMixerConfigInfo->getFlags());
1718 if (preferredOutput == nullptr) {
1719 ALOGE("%s failed to open output with preferred mixer config", __func__);
1720 } else {
1721 output = preferredOutput->mIoHandle;
1722 }
1723 }
1724 } else {
1725 // at this stage we should ignore the DIRECT flag as no direct output could be
1726 // found earlier
1727 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001728 if (com::android::media::audioserver::
1729 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1730 // If the preferred mixer attributes is null, do not select the bit-perfect output
1731 // unless the bit-perfect output is the only output.
1732 // The bit-perfect output can exist while the passed in preferred mixer attributes
1733 // info is null when it is a high priority client. The high priority clients are
1734 // ringtone or alarm, which is not a bit-perfect use case.
1735 size_t i = 0;
1736 while (i < outputs.size() && outputs.size() > 1) {
1737 auto desc = mOutputs.valueFor(outputs[i]);
1738 // The output descriptor must not be null here.
1739 if (desc->isBitPerfect()) {
1740 outputs.removeItemsAt(i);
1741 } else {
1742 i += 1;
1743 }
1744 }
1745 }
jiabina84c3d32022-12-02 18:59:55 +00001746 output = selectOutput(
1747 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1748 }
Eric Laurente552edb2014-03-10 17:42:56 -07001749 }
François Gaffie11d30102018-11-02 16:09:09 +01001750 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001751 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001752 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001753
Eric Laurente552edb2014-03-10 17:42:56 -07001754 return output;
1755}
1756
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001757sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001758 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1759 mAvailableInputDevices);
1760 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1761}
1762
1763DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1764 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1765 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001766}
1767
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001768const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001770 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1771 if (msdModule != 0) {
1772 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1773 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1774 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1775 const struct audio_port_config *source = &patch->mPatch.sources[j];
1776 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1777 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001778 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001779 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 }
1781 }
1782 }
1783 return msdPatches;
1784}
1785
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001786bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1787 ssize_t index = mAudioPatches.indexOfKey(handle);
1788 if (index < 0) {
1789 return false;
1790 }
1791 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1792 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1793 if (msdModule == nullptr) {
1794 return false;
1795 }
1796 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1797 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1798 return true;
1799 }
1800 index = getMsdOutputPatches().indexOfKey(handle);
1801 if (index < 0) {
1802 return false;
1803 }
1804 return true;
1805}
1806
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001807status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1808 const InputProfileCollection &inputProfiles,
1809 const OutputProfileCollection &outputProfiles,
1810 const sp<DeviceDescriptor> &sourceDevice,
1811 const sp<DeviceDescriptor> &sinkDevice,
1812 AudioProfileVector& sourceProfiles,
1813 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001814 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001815 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001816 return NO_INIT;
1817 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001820 return NO_INIT;
1821 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001822 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1824 inProfile->supportsDevice(sourceDevice)) {
1825 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 }
1827 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001828 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001829 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830 outProfile->supportsDevice(sinkDevice)) {
1831 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 }
1833 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001834 return NO_ERROR;
1835}
1836
1837status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1838 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1839 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1840{
Dean Wheatley16809da2022-12-09 14:55:46 +11001841 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1842 static const std::vector<audio_format_t> formatsOrder = {{
1843 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001844 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1845 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001846 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1847 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1848 // preferred).
1849 std::vector<audio_channel_mask_t> masks = {{
1850 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1851 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1852 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1853 // insert index masks (higher counts most preferred) as preferred over position masks
1854 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1855 masks.insert(
1856 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1857 }
1858 return masks;
1859 }();
1860
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001862 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1863 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001864 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001865 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1866 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001867 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001868 }
1869 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1870 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1871 sinkConfig->format = bestSinkConfig.format;
1872 // For encoded streams force direct flag to prevent downstream mixing.
1873 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1874 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001875 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1876 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001878 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1879 // raw and IEC61937 framed streams.
1880 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1881 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1882 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1884 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001885 sourceConfig->channel_mask =
1886 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1887 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1888 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 sourceConfig->format = bestSinkConfig.format;
1890 // Copy input stream directly without any processing (e.g. resampling).
1891 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1892 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1893 if (hwAvSync) {
1894 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1895 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1896 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1897 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1898 }
1899 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1900 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1901 sinkConfig->config_mask |= config_mask;
1902 sourceConfig->config_mask |= config_mask;
1903 return NO_ERROR;
1904}
1905
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001906PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1907 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001908{
1909 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001910 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1911 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1912 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1913 if (deviceModule == nullptr) {
1914 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1915 return patchBuilder;
1916 }
1917 const InputProfileCollection inputProfiles = msdIsSource ?
1918 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1919 const OutputProfileCollection outputProfiles = msdIsSource ?
1920 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1921
1922 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1923 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1924 device : getMsdAudioOutDevices().itemAt(0);
1925 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1926
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1928 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001929 AudioProfileVector sourceProfiles;
1930 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001931 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1932 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001933 for (auto hwAvSync : { true, false }) {
1934 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1935 sourceProfiles, sinkProfiles) != NO_ERROR) {
1936 continue;
1937 }
1938 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1939 &sinkConfig) == NO_ERROR) {
1940 // Found a matching config. Re-create PatchBuilder with this config.
1941 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1942 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001944 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001945 " supporting PCM format conversion.", __func__);
1946 return patchBuilder;
1947}
1948
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001950 DeviceVector devices;
1951 if (outputDevices != nullptr && outputDevices->size() > 0) {
1952 devices.add(*outputDevices);
1953 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001954 // Use media strategy for unspecified output device. This should only
1955 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1956 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001957 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001958 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001959 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001960 }
Michael Chan6fb34492020-12-08 15:44:49 +11001961 std::vector<PatchBuilder> patchesToCreate;
1962 for (auto i = 0u; i < devices.size(); ++i) {
1963 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001964 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001965 }
1966 // Retain only the MSD patches associated with outputDevices request.
1967 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001968 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001969 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1970 auto retainedPatch = false;
1971 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1972 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1973 patchesToRemove.removeItemsAt(i);
1974 retainedPatch = true;
1975 break;
1976 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001977 }
Michael Chan6fb34492020-12-08 15:44:49 +11001978 if (retainedPatch) {
1979 it = patchesToCreate.erase(it);
1980 continue;
1981 }
1982 ++it;
1983 }
1984 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1985 return NO_ERROR;
1986 }
1987 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1988 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001989 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001990 }
Michael Chan6fb34492020-12-08 15:44:49 +11001991 status_t status = NO_ERROR;
1992 for (const auto &p : patchesToCreate) {
1993 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1994 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1995 char message[256];
1996 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1997 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1998 currStatus == NO_ERROR ? "Success" : "Error",
1999 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2000 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2001 if (currStatus == NO_ERROR) {
2002 ALOGD("%s", message);
2003 } else {
2004 ALOGE("%s", message);
2005 if (status == NO_ERROR) {
2006 status = currStatus;
2007 }
2008 }
2009 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 return status;
2011}
2012
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002013void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2014 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002015 for (size_t i = 0; i < msdPatches.size(); i++) {
2016 const auto& patch = msdPatches[i];
2017 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2018 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2019 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2020 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2021 releaseAudioPatch(patch->getHandle(), mUidCached);
2022 break;
2023 }
2024 }
2025 }
2026}
2027
Dorin Drimus94d94412022-02-02 09:05:02 +01002028bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002029 DeviceVector devicesToCheck =
2030 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002031 AudioPatchCollection msdPatches = getMsdOutputPatches();
2032 for (size_t i = 0; i < msdPatches.size(); i++) {
2033 const auto& patch = msdPatches[i];
2034 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2035 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2036 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2037 const auto& foundDevice = devicesToCheck.getDevice(
2038 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2039 if (foundDevice != nullptr) {
2040 devicesToCheck.remove(foundDevice);
2041 if (devicesToCheck.isEmpty()) {
2042 return true;
2043 }
2044 }
2045 }
2046 }
2047 }
2048 return false;
2049}
2050
Eric Laurente0720872014-03-11 09:30:41 -07002051audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002052 audio_output_flags_t flags,
2053 audio_format_t format,
2054 audio_channel_mask_t channelMask,
2055 uint32_t samplingRate,
2056 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002057{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2059 "%s called with format %#x", __func__, format);
2060
jiabinebb6af42020-06-09 17:31:17 -07002061 // Return the output that haptic-generating attached to when 1) session id is specified,
2062 // 2) haptic-generating effect exists for given session id and 3) the output that
2063 // haptic-generating effect attached to is in given outputs.
2064 if (sessionId != AUDIO_SESSION_NONE) {
2065 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2066 sessionId, FX_IID_HAPTICGENERATOR);
2067 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2068 return hapticGeneratingOutput;
2069 }
2070 }
2071
Eric Laurent16c66dd2019-05-01 17:54:10 -07002072 // Flags disqualifying an output: the match must happen before calling selectOutput()
2073 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2074 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2075
2076 // Flags expressing a functional request: must be honored in priority over
2077 // other criteria
2078 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2079 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002080 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2081 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002082 // Flags expressing a performance request: have lower priority than serving
2083 // requested sampling rate or channel mask
2084 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2085 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2086 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2087
2088 const audio_output_flags_t functionalFlags =
2089 (audio_output_flags_t)(flags & kFunctionalFlags);
2090 const audio_output_flags_t performanceFlags =
2091 (audio_output_flags_t)(flags & kPerformanceFlags);
2092
2093 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2094
Eric Laurente552edb2014-03-10 17:42:56 -07002095 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002096 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002097 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002098 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002099 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002100 // with tiebreak preferring the minimum number of extra functional flags
2101 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 // 3: the output supporting the exact channel mask
2103 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002104 // 5: the output with the highest sampling rate if the requested sample rate is
2105 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002106 // 6: the output with the highest number of requested performance flags
2107 // 7: the output with the bit depth the closest to the requested one
2108 // 8: the primary output
2109 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002110
Eric Laurent16c66dd2019-05-01 17:54:10 -07002111 // matching criteria values in priority order for best matching output so far
2112 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002113
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002114 const bool hasOrphanHaptic =
2115 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002116 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2117 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2118 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002119
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002120 for (audio_io_handle_t output : outputs) {
2121 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002122 // matching criteria values in priority order for current output
2123 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002124
Eric Laurent16c66dd2019-05-01 17:54:10 -07002125 if (outputDesc->isDuplicated()) {
2126 continue;
2127 }
2128 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2129 continue;
2130 }
Eric Laurent8838a382014-09-08 16:44:28 -07002131
Eric Laurent16c66dd2019-05-01 17:54:10 -07002132 // If haptic channel is specified, use the haptic output if present.
2133 // When using haptic output, same audio format and sample rate are required.
2134 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002135 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002136 // skip if haptic channel specified but output does not support it, or output support haptic
2137 // but there is no haptic channel requested AND no orphan haptic effect exist
2138 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2139 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002140 continue;
2141 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002142 // In the case of audio-coupled-haptic playback, there is no format conversion and
2143 // resampling in the framework, same format/channel/sampleRate for client and the output
2144 // thread is required. In the case of HapticGenerator effect, do not require format
2145 // matching.
2146 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2147 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002148 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002149 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002150 }
2151
2152 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002153 const int matchingFunctionalFlags =
2154 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2155 const int totalFunctionalFlags =
2156 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2157 // Prefer matching functional flags, but subtract unnecessary functional flags.
2158 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002159
2160 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002161 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2162 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002163 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2164 channelCount <= outputChannelCount) {
2165 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002166 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2167 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002168 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002169 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 currentMatchCriteria[3] = outputChannelCount;
2171 }
2172
2173 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002174 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002175 int diff; // avoid unsigned integer overflow.
2176 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2177
2178 // prefer the closest output sampling rate greater than or equal to target
2179 // if none exists, prefer the closest output sampling rate less than target.
2180 //
2181 // criteria is offset to make non-negative.
2182 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 }
2184
2185 // performance flags match
2186 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2187
2188 // format match
2189 if (format != AUDIO_FORMAT_INVALID) {
2190 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002191 PolicyAudioPort::kFormatDistanceMax -
2192 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002193 }
2194
2195 // primary output match
2196 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2197
2198 // compare match criteria by priority then value
2199 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2200 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2201 bestMatchCriteria = currentMatchCriteria;
2202 bestOutput = output;
2203
2204 std::stringstream result;
2205 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2206 std::ostream_iterator<int>(result, " "));
2207 ALOGV("%s new bestOutput %d criteria %s",
2208 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002209 }
2210 }
2211
Eric Laurent16c66dd2019-05-01 17:54:10 -07002212 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002213}
2214
Eric Laurent8fc147b2018-07-22 19:13:55 -07002215status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002216{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002217 ALOGV("%s portId %d", __FUNCTION__, portId);
2218
2219 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2220 if (outputDesc == 0) {
2221 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002222 return BAD_VALUE;
2223 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002224 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002225
Eric Laurent8fc147b2018-07-22 19:13:55 -07002226 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002227 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002228
jiabin220eea12024-05-17 17:55:20 +00002229 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2230 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2231 && outputDesc->isBitPerfect()) {
2232 // Usually, APM selects bit-perfect output for high priority use cases only when
2233 // bit-perfect output is the only output that can be routed to the selected device.
2234 // However, here is no need to play high priority use cases such as ringtone and alarm
2235 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2236 // can attach to new output.
2237 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2238 __func__, client->stream());
2239 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2240 return DEAD_OBJECT;
2241 }
2242
Eric Laurent733ce942017-12-07 12:18:25 -08002243 status_t status = outputDesc->start();
2244 if (status != NO_ERROR) {
2245 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002246 }
2247
Eric Laurent97ac8712018-07-27 18:59:02 -07002248 uint32_t delayMs;
2249 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002250
2251 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002252 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002253 if (status == DEAD_OBJECT) {
2254 sp<SwAudioOutputDescriptor> desc =
2255 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2256 if (desc == nullptr) {
2257 // This is not common, it may indicate something wrong with the HAL.
2258 ALOGE("%s unable to open output with default config", __func__);
2259 return status;
2260 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002261 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002262 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002263 }
jiabina84c3d32022-12-02 18:59:55 +00002264
2265 // If the client is the first one active on preferred mixer parameters, reopen the output
2266 // if the current mixer parameters doesn't match the preferred one.
2267 if (outputDesc->devices().size() == 1) {
2268 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2269 outputDesc->devices()[0]->getId(), client->strategy());
2270 if (info != nullptr && info->getUid() == client->uid()) {
2271 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2272 info->getConfigBase(), info->getFlags())) {
2273 stopSource(outputDesc, client);
2274 outputDesc->stop();
2275 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2276 config.channel_mask = info->getConfigBase().channel_mask;
2277 config.sample_rate = info->getConfigBase().sample_rate;
2278 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002279 sp<SwAudioOutputDescriptor> desc =
2280 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2281 if (desc == nullptr) {
2282 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002283 }
jiabin220eea12024-05-17 17:55:20 +00002284 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002285 // Intentionally return error to let the client side resending request for
2286 // creating and starting.
2287 return DEAD_OBJECT;
2288 }
2289 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002290 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002291 // If it is first bit-perfect client, reroute all clients that will be routed to
2292 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2293 PortHandleVector clientsToInvalidate;
2294 for (size_t i = 0; i < mOutputs.size(); i++) {
2295 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002296 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002297 continue;
2298 }
2299 for (const auto& c : mOutputs[i]->getClientIterable()) {
2300 clientsToInvalidate.push_back(c->portId());
2301 }
2302 }
2303 if (!clientsToInvalidate.empty()) {
2304 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2305 __func__);
2306 mpClientInterface->invalidateTracks(clientsToInvalidate);
2307 }
2308 }
jiabina84c3d32022-12-02 18:59:55 +00002309 }
2310 }
2311
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002312 if (client->hasPreferredDevice()) {
2313 // playback activity with preferred device impacts routing occurred, inform upper layers
2314 mpClientInterface->onRoutingUpdated();
2315 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002316 if (delayMs != 0) {
2317 usleep(delayMs * 1000);
2318 }
2319
jiabin220eea12024-05-17 17:55:20 +00002320 if (status == NO_ERROR &&
2321 outputDesc->mPreferredAttrInfo != nullptr &&
2322 outputDesc->isBitPerfect() &&
2323 com::android::media::audioserver::
2324 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2325 // A new client is started on bit-perfect output, update all clients internal mute.
2326 updateClientsInternalMute(outputDesc);
2327 }
2328
Eric Laurentc75307b2015-03-17 15:29:32 -07002329 return status;
2330}
2331
Eric Laurent96d1dda2022-03-14 17:14:19 +01002332bool AudioPolicyManager::isLeUnicastActive() const {
2333 if (isInCall()) {
2334 return true;
2335 }
2336 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2337}
2338
2339bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2340 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2341 return false;
2342 }
2343 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2344 ALOGV("%s active %d", __func__, active);
2345 return active;
2346}
2347
Eric Laurent97ac8712018-07-27 18:59:02 -07002348status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2349 const sp<TrackClientDescriptor>& client,
2350 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002351{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002352 // cannot start playback of STREAM_TTS if any other output is being used
2353 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002354
2355 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002356 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002357 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002358 auto clientStrategy = client->strategy();
2359 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002360 if (stream == AUDIO_STREAM_TTS) {
2361 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002362 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002363 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002364 return INVALID_OPERATION;
2365 } else {
2366 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2367 }
2368 } else {
2369 // some playback other than beacon starts
2370 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2371 }
2372
Eric Laurent77305a62016-07-25 16:39:22 -07002373 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002374 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002375 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002376
François Gaffie11d30102018-11-02 16:09:09 +01002377 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002378 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002380 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002381 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002382 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002383 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002384 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002385 } else {
2386 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002387 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002388 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2389 AUDIO_FORMAT_DEFAULT);
2390 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2391 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002392 }
2393
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002394 // requiresMuteCheck is false when we can bypass mute strategy.
2395 // It covers a common case when there is no materially active audio
2396 // and muting would result in unnecessary delay and dropped audio.
2397 const uint32_t outputLatencyMs = outputDesc->latency();
2398 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002399 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002400
Eric Laurente552edb2014-03-10 17:42:56 -07002401 // increment usage count for this stream on the requested output:
2402 // NOTE that the usage count is the same for duplicated output and hardware output which is
2403 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002404 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002405
2406 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002407 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002408 // Preferred device may be exclusive, use only if no other active clients on this output
2409 devices = DeviceVector(
2410 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2411 } else {
2412 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2413 }
François Gaffie11d30102018-11-02 16:09:09 +01002414 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002415 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002416 }
2417 }
Eric Laurente552edb2014-03-10 17:42:56 -07002418
François Gaffiec005e562018-11-06 15:04:49 +01002419 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002420 selectOutputForMusicEffects();
2421 }
2422
François Gaffie1c878552018-11-22 16:53:21 +01002423 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002424 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002425 if (devices.isEmpty()) {
2426 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002427 }
François Gaffiec005e562018-11-06 15:04:49 +01002428 bool shouldWait =
2429 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2430 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2431 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002432 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002433 const bool needToCloseBitPerfectOutput =
2434 (com::android::media::audioserver::
2435 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2436 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2437 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002438 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002439 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002440 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002441 // An output has a shared device if
2442 // - managed by the same hw module
2443 // - supports the currently selected device
2444 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002445 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002446
Eric Laurent77305a62016-07-25 16:39:22 -07002447 // force a device change if any other output is:
2448 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002449 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002450 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002451 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002452 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002453 // change the device currently selected by the other output.
2454 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002455 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002456 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002457 force = true;
2458 }
2459 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002460 // a notification so that audio focus effect can propagate, or that a mute/unmute
2461 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002462 const uint32_t latencyMs = desc->latency();
2463 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2464
2465 if (shouldWait && isActive && (waitMs < latencyMs)) {
2466 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002467 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002468
2469 // Require mute check if another output is on a shared device
2470 // and currently active to have proper drain and avoid pops.
2471 // Note restoring AudioTracks onto this output needs to invoke
2472 // a volume ramp if there is no mute.
2473 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002474
2475 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2476 outputsToReopen.push_back(desc);
2477 }
Eric Laurente552edb2014-03-10 17:42:56 -07002478 }
2479 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002480
jiabin220eea12024-05-17 17:55:20 +00002481 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002482 // If the output is open with preferred mixer attributes, but the routed device is
2483 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2484 // changed.
2485 return DEAD_OBJECT;
2486 }
jiabin220eea12024-05-17 17:55:20 +00002487 for (auto& outputToReopen : outputsToReopen) {
2488 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2489 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002490 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302491 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2492 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002493
Eric Laurente552edb2014-03-10 17:42:56 -07002494 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002495 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002496 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002497 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002498 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002499 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002500 outputDesc->useHwGain() /*force*/)) {
2501 // request AudioService to reinitialize the volume curves asynchronously
2502 ALOGE("checkAndSetVolume failed, requesting volume range init");
2503 mpClientInterface->onVolumeRangeInitRequest();
2504 };
Eric Laurente552edb2014-03-10 17:42:56 -07002505
2506 // update the outputs if starting an output with a stream that can affect notification
2507 // routing
2508 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002509
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002510 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002511 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002512 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002513 }
Eric Laurentdc462862016-07-19 12:29:53 -07002514
2515 if (waitMs > muteWaitMs) {
2516 *delayMs = waitMs - muteWaitMs;
2517 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002518
2519 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2520 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2521 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2522 // change occurs after the MixerThread starts and causes a stream volume
2523 // glitch.
2524 //
2525 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002526 }
Eric Laurentdc462862016-07-19 12:29:53 -07002527
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002528 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002529 mEngine->getForceUse(
2530 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002531 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002532 }
2533
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 // Automatically enable the remote submix input when output is started on a re routing mix
2535 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002536 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2537 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2539 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2540 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002541 "remote-submix",
2542 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 }
2544
Eric Laurent96d1dda2022-03-14 17:14:19 +01002545 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2546
Eric Laurente552edb2014-03-10 17:42:56 -07002547 return NO_ERROR;
2548}
2549
Eric Laurent96d1dda2022-03-14 17:14:19 +01002550void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2551 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2552 bool isUnicastActive = isLeUnicastActive();
2553
2554 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002555 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002556 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2557 for (size_t i = 0; i < mOutputs.size(); i++) {
2558 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2559 if (desc != ignoredOutput && desc->isActive()
2560 && ((isUnicastActive &&
2561 !desc->devices().
2562 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2563 || (wasUnicastActive &&
2564 !desc->devices().getDevicesFromTypes(
2565 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2566 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2567 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002568 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002569 // If the device is using preferred mixer attributes, the output need to reopen
2570 // with default configuration when the new selected devices are different from
2571 // current routing devices.
2572 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2573 continue;
2574 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302575 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002576 // re-apply device specific volume if not done by setOutputDevice()
2577 if (!force) {
2578 applyStreamVolumes(desc, newDevices.types(), delayMs);
2579 }
2580 }
2581 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002582 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002583 }
2584}
2585
Eric Laurent8fc147b2018-07-22 19:13:55 -07002586status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002587{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002588 ALOGV("%s portId %d", __FUNCTION__, portId);
2589
2590 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2591 if (outputDesc == 0) {
2592 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002593 return BAD_VALUE;
2594 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002595 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002596
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002597 if (client->hasPreferredDevice(true)) {
2598 // playback activity with preferred device impacts routing occurred, inform upper layers
2599 mpClientInterface->onRoutingUpdated();
2600 }
2601
Eric Laurent97ac8712018-07-27 18:59:02 -07002602 ALOGV("stopOutput() output %d, stream %d, session %d",
2603 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002604
Eric Laurent97ac8712018-07-27 18:59:02 -07002605 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002606
Eric Laurent733ce942017-12-07 12:18:25 -08002607 if (status == NO_ERROR ) {
2608 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002609 } else {
2610 return status;
2611 }
2612
2613 if (outputDesc->devices().size() == 1) {
2614 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2615 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002616 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002617 if (info != nullptr && info->getUid() == client->uid()) {
2618 info->decreaseActiveClient();
2619 if (info->getActiveClientCount() == 0) {
2620 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002621 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002622 }
2623 }
jiabin220eea12024-05-17 17:55:20 +00002624 if (com::android::media::audioserver::
2625 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2626 !outputReopened && outputDesc->isBitPerfect()) {
2627 // Only need to update the clients' internal mute when the output is bit-perfect and it
2628 // is not reopened.
2629 updateClientsInternalMute(outputDesc);
2630 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002631 }
2632 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002633}
2634
Eric Laurent97ac8712018-07-27 18:59:02 -07002635status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2636 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002637{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002638 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002639 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002640 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002641 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002642
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002643 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2644
François Gaffie1c878552018-11-22 16:53:21 +01002645 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2646 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002647 // Automatically disable the remote submix input when output is stopped on a
2648 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002649 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002650 if (isSingleDeviceType(
2651 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002652 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002653 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002654 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2655 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002656 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002657 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002658 }
2659 }
2660 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002661 if (client->hasPreferredDevice(true) &&
2662 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002663 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002664 forceDeviceUpdate = true;
2665 }
2666
Eric Laurente552edb2014-03-10 17:42:56 -07002667 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002668 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002669
Eric Laurente552edb2014-03-10 17:42:56 -07002670 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002671 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002672 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002673 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002674
2675 // If the routing does not change, if an output is routed on a device using HwGain
2676 // (aka setAudioPortConfig) and there are still active clients following different
2677 // volume group(s), force reapply volume
2678 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2679 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2680
Eric Laurente552edb2014-03-10 17:42:56 -07002681 // delay the device switch by twice the latency because stopOutput() is executed when
2682 // the track stop() command is received and at that time the audio track buffer can
2683 // still contain data that needs to be drained. The latency only covers the audio HAL
2684 // and kernel buffers. Also the latency does not always include additional delay in the
2685 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302686 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002687 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002688
2689 // force restoring the device selection on other active outputs if it differs from the
2690 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002691 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002692 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002693 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002694 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002695 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002696 desc->isActive() &&
2697 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002698 (newDevices != desc->devices())) {
2699 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2700 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002701
jiabin220eea12024-05-17 17:55:20 +00002702 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002703 // If the device is using preferred mixer attributes, the output need to
2704 // reopen with default configuration when the new selected devices are
2705 // different from current routing devices.
2706 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2707 continue;
2708 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302709 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002710
Eric Laurent57de36c2016-09-28 16:59:11 -07002711 // re-apply device specific volume if not done by setOutputDevice()
2712 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002713 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002714 }
Eric Laurente552edb2014-03-10 17:42:56 -07002715 }
2716 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002717 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002718 // update the outputs if stopping one with a stream that can affect notification routing
2719 handleNotificationRoutingForStream(stream);
2720 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002721
2722 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2723 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002724 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002725 }
2726
François Gaffiec005e562018-11-06 15:04:49 +01002727 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002728 selectOutputForMusicEffects();
2729 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002730
2731 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2732
Eric Laurente552edb2014-03-10 17:42:56 -07002733 return NO_ERROR;
2734 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002735 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002736 return INVALID_OPERATION;
2737 }
2738}
2739
jiabinbce0c1d2020-10-05 11:20:18 -07002740bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002741{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002742 ALOGV("%s portId %d", __FUNCTION__, portId);
2743
2744 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2745 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002746 // If an output descriptor is closed due to a device routing change,
2747 // then there are race conditions with releaseOutput from tracks
2748 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2749 // destroyed shortly thereafter.
2750 //
2751 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002752 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002753 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002754 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002755
2756 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002757
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302758 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2759 if (outputDesc->isClientActive(client)) {
2760 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2761 stopOutput(portId);
2762 }
2763
Eric Laurent8fc147b2018-07-22 19:13:55 -07002764 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2765 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002766 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002767 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002768 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002769 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002770 if (--outputDesc->mDirectOpenCount == 0) {
2771 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002772 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002773 }
2774 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302775
Andy Hung39efb7a2018-09-26 15:39:28 -07002776 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002777 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2778 // The output is pending reopened to query dynamic profiles and
2779 // there is no active clients
2780 closeOutput(outputDesc->mIoHandle);
2781 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2782 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2783 if (newOutputDesc == nullptr) {
2784 ALOGE("%s failed to open output", __func__);
2785 }
2786 return true;
2787 }
2788 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002789}
2790
Eric Laurentcaf7f482014-11-25 17:50:47 -08002791status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2792 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002793 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002794 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002795 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002796 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002797 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002798 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002799 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002800 audio_port_handle_t *portId,
2801 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002802{
François Gaffiec005e562018-11-06 15:04:49 +01002803 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002804 "flags %#x attributes=%s requested device ID %d",
2805 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2806 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002807
Eric Laurentad2e7b92017-09-14 20:06:42 -07002808 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002809 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002810 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002811 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002812 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002813 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002814 sp<RecordClientDescriptor> clientDesc;
2815 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002816 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002817 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002818
2819 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2820 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2821 return INVALID_OPERATION;
2822 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002823
Francois Gaffie716e1432019-01-14 16:58:59 +01002824 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2825 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002826 }
2827
Paul McLean466dc8e2015-04-17 13:15:36 -06002828 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002829 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002830 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002831
Eric Laurentad2e7b92017-09-14 20:06:42 -07002832 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2833 // possible
2834 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2835 *input != AUDIO_IO_HANDLE_NONE) {
2836 ssize_t index = mInputs.indexOfKey(*input);
2837 if (index < 0) {
2838 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2839 status = BAD_VALUE;
2840 goto error;
2841 }
2842 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002843 RecordClientVector clients = inputDesc->getClientsForSession(session);
2844 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002845 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2846 status = BAD_VALUE;
2847 goto error;
2848 }
2849 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2850 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002851 // corresponds to a new client and is only permitted from the same UID.
2852 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002853 if (clients.size() > 1) {
2854 for (const auto& client : clients) {
2855 // The client map is ordered by key values (portId) and portIds are allocated
2856 // incrementaly. So the first client in this list is the one opened by audio flinger
2857 // when the mmap stream is created and should be ignored as it does not correspond
2858 // to an actual client
2859 if (client == *clients.cbegin()) {
2860 continue;
2861 }
2862 if (uid != client->uid() && !client->isSilenced()) {
2863 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2864 uid, client->portId(), client->uid());
2865 status = INVALID_OPERATION;
2866 goto error;
2867 }
Eric Laurent331679c2018-04-16 17:03:16 -07002868 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002869 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002870 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002871 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002872
Eric Laurentfecbceb2021-02-09 14:46:43 +01002873 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002874 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002875 }
2876
2877 *input = AUDIO_IO_HANDLE_NONE;
2878 *inputType = API_INPUT_INVALID;
2879
Francois Gaffie716e1432019-01-14 16:58:59 +01002880 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002881 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002882 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002883 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002884 ALOGW("%s could not find input mix for attr %s",
2885 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002886 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002887 }
jiabinc1de2df2019-05-07 14:26:40 -07002888 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2889 String8(attr->tags + strlen("addr=")),
2890 AUDIO_FORMAT_DEFAULT);
2891 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002892 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002893 __func__, attributes.source, attributes.tags);
2894 status = BAD_VALUE;
2895 goto error;
2896 }
2897
Kevin Rocard25f9b052019-02-27 15:08:54 -08002898 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2899 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2900 } else {
2901 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2902 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002903 if (virtualDeviceId) {
2904 *virtualDeviceId = policyMix->mVirtualDeviceId;
2905 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002906 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002907 if (explicitRoutingDevice != nullptr) {
2908 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002909 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002910 // Prevent from storing invalid requested device id in clients
2911 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002912 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002913 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2914 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002915 }
François Gaffie11d30102018-11-02 16:09:09 +01002916 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002917 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002918 status = BAD_VALUE;
2919 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002920 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002921 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2922 *inputType = API_INPUT_MIX_CAPTURE;
2923 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002924 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2925 // there is an external policy, but this input is attached to a mix of recorders,
2926 // meaning it receives audio injected into the framework, so the recorder doesn't
2927 // know about it and is therefore considered "legacy"
2928 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002929
2930 if (virtualDeviceId) {
2931 *virtualDeviceId = policyMix->mVirtualDeviceId;
2932 }
François Gaffie11d30102018-11-02 16:09:09 +01002933 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002934 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002935 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002936 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002937 } else {
2938 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002939 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002940
Eric Laurent599c7582015-12-07 18:05:55 -08002941 }
2942
François Gaffiec005e562018-11-06 15:04:49 +01002943 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002944 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002945 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002946 AudioProfileVector profiles;
2947 status_t ret = getProfilesForDevices(
2948 DeviceVector(device), profiles, flags, true /*isInput*/);
2949 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002950 const auto channels = profiles[0]->getChannels();
2951 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2952 config->channel_mask = *channels.begin();
2953 }
2954 const auto sampleRates = profiles[0]->getSampleRates();
2955 if (!sampleRates.empty() &&
2956 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2957 config->sample_rate = *sampleRates.begin();
2958 }
jiabinf1c73972022-04-14 16:28:52 -07002959 config->format = profiles[0]->getFormat();
2960 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002961 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002962 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002963
Marvin Ramine5a122d2023-12-07 13:57:59 +01002964
2965 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2966 *virtualDeviceId = policyMix->mVirtualDeviceId;
2967 }
2968
Eric Laurent8f42ea12018-08-08 09:08:25 -07002969exit:
2970
François Gaffiec005e562018-11-06 15:04:49 +01002971 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2972 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002973
Francois Gaffie716e1432019-01-14 16:58:59 +01002974 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002975 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002976 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002977
Mikhail Naganov2996f672019-04-18 12:29:59 -07002978 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002979 requestedDeviceId, attributes.source, flags,
2980 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002981 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002982 // Move (if found) effect for the client session to its input
2983 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002984 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002985
2986 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2987 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002988
Eric Laurent599c7582015-12-07 18:05:55 -08002989 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002990
2991error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002992 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002993}
2994
2995
François Gaffie11d30102018-11-02 16:09:09 +01002996audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002997 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002998 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002999 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003000 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003001 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003002{
3003 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003004 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003005 bool isSoundTrigger = false;
3006
François Gaffiec005e562018-11-06 15:04:49 +01003007 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003008 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3009 if (index >= 0) {
3010 input = mSoundTriggerSessions.valueFor(session);
3011 isSoundTrigger = true;
3012 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3013 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3014 } else {
3015 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003016 }
François Gaffiec005e562018-11-06 15:04:49 +01003017 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003018 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003019 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003020 }
3021
Carter Hsua3abb402021-10-26 11:11:20 +08003022 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3023 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3024 }
3025
Eric Laurentfe231122017-11-17 17:48:06 -08003026 // sampling rate and flags may be updated by getInputProfile
3027 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3028 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003029 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003030 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003031 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003032 // find a compatible input profile (not necessarily identical in parameters)
3033 sp<IOProfile> profile = getInputProfile(
3034 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3035 if (profile == nullptr) {
3036 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003037 }
jiabin2fd710d2022-05-02 23:20:22 +00003038
Glenn Kasten05ddca52016-02-11 08:17:12 -08003039 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003040 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003041 if (samplingRate == 0) {
3042 samplingRate = profileSamplingRate;
3043 }
Eric Laurente552edb2014-03-10 17:42:56 -07003044
Eric Laurent322b4d22015-04-03 15:57:54 -07003045 if (profile->getModuleHandle() == 0) {
3046 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003047 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003048 }
3049
Eric Laurentec376dc2021-04-08 20:41:22 +02003050 // Reuse an already opened input if a client with the same session ID already exists
3051 // on that input
3052 for (size_t i = 0; i < mInputs.size(); i++) {
3053 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3054 if (desc->mProfile != profile) {
3055 continue;
3056 }
3057 RecordClientVector clients = desc->clientsList();
3058 for (const auto &client : clients) {
3059 if (session == client->session()) {
3060 return desc->mIoHandle;
3061 }
3062 }
3063 }
3064
Eric Laurent3974e3b2017-12-07 17:58:43 -08003065 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003066 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003067 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003068 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003069 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003070 continue;
3071 }
3072 // if sound trigger, reuse input if used by other sound trigger on same session
3073 // else
3074 // reuse input if active client app is not in IDLE state
3075 //
3076 RecordClientVector clients = desc->clientsList();
3077 bool doClose = false;
3078 for (const auto& client : clients) {
3079 if (isSoundTrigger != client->isSoundTrigger()) {
3080 continue;
3081 }
3082 if (client->isSoundTrigger()) {
3083 if (session == client->session()) {
3084 return desc->mIoHandle;
3085 }
3086 continue;
3087 }
3088 if (client->active() && client->appState() != APP_STATE_IDLE) {
3089 return desc->mIoHandle;
3090 }
3091 doClose = true;
3092 }
3093 if (doClose) {
3094 closeInput(desc->mIoHandle);
3095 } else {
3096 i++;
3097 }
3098 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003099 }
3100
Eric Laurentfe231122017-11-17 17:48:06 -08003101 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003102
Eric Laurentfe231122017-11-17 17:48:06 -08003103 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3104 lConfig.sample_rate = profileSamplingRate;
3105 lConfig.channel_mask = profileChannelMask;
3106 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003107
François Gaffie11d30102018-11-02 16:09:09 +01003108 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003109
3110 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003111 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003112 (profileSamplingRate != lConfig.sample_rate) ||
3113 !audio_formats_match(profileFormat, lConfig.format) ||
3114 (profileChannelMask != lConfig.channel_mask)) {
3115 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003116 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003117 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003118 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003119 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003120 }
Eric Laurent599c7582015-12-07 18:05:55 -08003121 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003122 }
3123
Eric Laurentc722f302014-12-10 11:21:49 -08003124 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003125
Eric Laurent599c7582015-12-07 18:05:55 -08003126 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003127 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003128
Eric Laurent599c7582015-12-07 18:05:55 -08003129 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003130}
3131
Eric Laurent4eb58f12018-12-07 16:41:02 -08003132status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003133{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003134 ALOGV("%s portId %d", __FUNCTION__, portId);
3135
3136 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3137 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003138 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003139 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003140 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003141 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003142 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 if (client->active()) {
3144 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3145 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003146 }
3147
Eric Laurent8f42ea12018-08-08 09:08:25 -07003148 audio_session_t session = client->session();
3149
Eric Laurent4eb58f12018-12-07 16:41:02 -08003150 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003151
Eric Laurent4eb58f12018-12-07 16:41:02 -08003152 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003153
Eric Laurent4eb58f12018-12-07 16:41:02 -08003154 status_t status = inputDesc->start();
3155 if (status != NO_ERROR) {
3156 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003157 }
Eric Laurente552edb2014-03-10 17:42:56 -07003158
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003159 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003160 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003161 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003162
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 // indicate active capture to sound trigger service if starting capture from a mic on
3164 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003165 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003166 if (device != nullptr) {
3167 status = setInputDevice(input, device, true /* force */);
3168 } else {
3169 ALOGW("%s no new input device can be found for descriptor %d",
3170 __FUNCTION__, inputDesc->getId());
3171 status = BAD_VALUE;
3172 }
Eric Laurente552edb2014-03-10 17:42:56 -07003173
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003174 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003175 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003177 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003178 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3179 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003180 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003181 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003182
François Gaffie11d30102018-11-02 16:09:09 +01003183 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3184 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003186 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003187 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003188
Eric Laurent8f42ea12018-08-08 09:08:25 -07003189 // automatically enable the remote submix output when input is started if not
3190 // used by a policy mix of type MIX_TYPE_RECORDERS
3191 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003192 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003193 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003194 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003195 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003196 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3197 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003198 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199 if (address != "") {
3200 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3201 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003202 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003203 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003204 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003205 } else if (status != NO_ERROR) {
3206 // Restore client activity state.
3207 inputDesc->setClientActive(client, false);
3208 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003209 }
3210
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003211 ALOGV("%s input %d source = %d status = %d exit",
3212 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003213
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003214 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003215}
3216
Eric Laurent8fc147b2018-07-22 19:13:55 -07003217status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003218{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003219 ALOGV("%s portId %d", __FUNCTION__, portId);
3220
3221 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3222 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003224 return BAD_VALUE;
3225 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003226 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003227 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003228 if (!client->active()) {
3229 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003230 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003231 }
Carter Hsue6139d52021-07-08 10:30:20 +08003232 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003233 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003234
Eric Laurent8f42ea12018-08-08 09:08:25 -07003235 inputDesc->stop();
3236 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003237 auto current_source = inputDesc->source();
3238 setInputDevice(input, getNewInputDevice(inputDesc),
3239 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003240 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003241 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003242 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003243 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003244 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3245 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003246 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003247 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003248
3249 // automatically disable the remote submix output when input is stopped if not
3250 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003251 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003252 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003253 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003254 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003255 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3256 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003257 }
3258 if (address != "") {
3259 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3260 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003261 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 }
3263 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003264 resetInputDevice(input);
3265
3266 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3267 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003268 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3269 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003270 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003271 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003272 }
3273 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003274 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003275 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003276}
3277
Eric Laurent8fc147b2018-07-22 19:13:55 -07003278void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003280 ALOGV("%s portId %d", __FUNCTION__, portId);
3281
3282 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3283 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003285 return;
3286 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003287 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003288 audio_io_handle_t input = inputDesc->mIoHandle;
3289
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003291
Andy Hung39efb7a2018-09-26 15:39:28 -07003292 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003293
3294 // If no more clients are present in this session, park effects to an orphan chain
3295 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3296 if (clientsOnSession.size() == 0) {
3297 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3298 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003299 if (inputDesc->getClientCount() > 0) {
3300 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003301 return;
3302 }
3303
Eric Laurent05b90f82014-08-27 15:32:29 -07003304 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003305 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003306 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003307}
3308
Eric Laurent8f42ea12018-08-08 09:08:25 -07003309void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003310{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003311 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003312
3313 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003314 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003315 }
3316}
3317
Eric Laurent8f42ea12018-08-08 09:08:25 -07003318void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3319{
3320 stopInput(portId);
3321 releaseInput(portId);
3322}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003323
Eric Laurent0dd51852019-04-19 18:18:58 -07003324void AudioPolicyManager::checkCloseInputs() {
3325 // After connecting or disconnecting an input device, close input if:
3326 // - it has no client (was just opened to check profile) OR
3327 // - none of its supported devices are connected anymore OR
3328 // - one of its clients cannot be routed to one of its supported
3329 // devices anymore. Otherwise update device selection
3330 std::vector<audio_io_handle_t> inputsToClose;
3331 for (size_t i = 0; i < mInputs.size(); i++) {
3332 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3333 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003334 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003335 inputsToClose.push_back(mInputs.keyAt(i));
3336 } else {
3337 bool close = false;
3338 for (const auto& client : input->clientsList()) {
3339 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003340 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3341 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003342 if (!input->supportedDevices().contains(device)) {
3343 close = true;
3344 break;
3345 }
3346 }
3347 if (close) {
3348 inputsToClose.push_back(mInputs.keyAt(i));
3349 } else {
3350 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3351 }
3352 }
3353 }
3354
3355 for (const audio_io_handle_t handle : inputsToClose) {
3356 ALOGV("%s closing input %d", __func__, handle);
3357 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003358 }
Eric Laurentd4692962014-05-05 18:13:44 -07003359}
3360
François Gaffie251c7f02018-11-07 10:41:08 +01003361void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003362{
3363 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003364 if (indexMin < 0 || indexMax < 0) {
3365 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3366 return;
3367 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003368 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003369
3370 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003371 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3372 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003373 continue;
3374 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003375 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003376 }
Eric Laurente552edb2014-03-10 17:42:56 -07003377}
3378
Eric Laurente0720872014-03-11 09:30:41 -07003379status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003380 int index,
3381 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003382{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003383 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003384 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3385 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3386 return NO_ERROR;
3387 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003388 ALOGV("%s: stream %s attributes=%s", __func__,
3389 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003390 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003391}
3392
Eric Laurente0720872014-03-11 09:30:41 -07003393status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003394 int *index,
3395 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003396{
François Gaffiec005e562018-11-06 15:04:49 +01003397 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3398 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003399 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003400 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003401 deviceTypes = mEngine->getOutputDevicesForStream(
3402 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003403 }
jiabin9a3361e2019-10-01 09:38:30 -07003404 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003405}
3406
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003407status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003408 int index,
3409 audio_devices_t device)
3410{
3411 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003412 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3413 if (group == VOLUME_GROUP_NONE) {
3414 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003415 return BAD_VALUE;
3416 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003417 ALOGV("%s: group %d matching with %s index %d",
3418 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003419 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003420 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003421 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003422 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3423 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3424 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3425 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003426 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3427
3428 status = setVolumeCurveIndex(index, device, curves);
3429 if (status != NO_ERROR) {
3430 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3431 return status;
3432 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003433
jiabin9a3361e2019-10-01 09:38:30 -07003434 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003435 auto curCurvAttrs = curves.getAttributes();
3436 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3437 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003438 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003439 } else if (!curves.getStreamTypes().empty()) {
3440 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003441 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003442 } else {
3443 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3444 return BAD_VALUE;
3445 }
jiabin9a3361e2019-10-01 09:38:30 -07003446 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3447 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003448
François Gaffiecfe17322018-11-07 13:41:29 +01003449 // update volume on all outputs and streams matching the following:
3450 // - The requested stream (or a stream matching for volume control) is active on the output
3451 // - The device (or devices) selected by the engine for this stream includes
3452 // the requested device
3453 // - For non default requested device, currently selected device on the output is either the
3454 // requested device or one of the devices selected by the engine for this stream
3455 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3456 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003457 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003458 for (size_t i = 0; i < mOutputs.size(); i++) {
3459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003460 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003461
jiabin9a3361e2019-10-01 09:38:30 -07003462 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3463 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003464 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003465
3466 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003467 continue;
3468 }
3469 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3470 curDevices.find(device) == curDevices.end()) {
3471 continue;
3472 }
3473 bool applyVolume = false;
3474 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3475 curSrcDevices.insert(device);
3476 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003477 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3478 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003479 } else {
3480 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3481 }
3482 if (!applyVolume) {
3483 continue; // next output
3484 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003485 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3486 // If a higher priority strategy is active, and the output is routed to a device with a
3487 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003488 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003489 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003490 // If the volume source is active with higher priority source, ensure at least Sw Muted
3491 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003492 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3493 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3494 false /*preferredDevice*/);
3495 if (activeClients.empty()) {
3496 continue;
3497 }
3498 bool isPreempted = false;
3499 bool isHigherPriority = productStrategy < strategy;
3500 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003501 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003502 ALOGV("%s: Strategy=%d (\nrequester:\n"
3503 " group %d, volumeGroup=%d attributes=%s)\n"
3504 " higher priority source active:\n"
3505 " volumeGroup=%d attributes=%s) \n"
3506 " on output %zu, bailing out", __func__, productStrategy,
3507 group, group, toString(attributes).c_str(),
3508 client->volumeSource(), toString(client->attributes()).c_str(), i);
3509 applyVolume = false;
3510 isPreempted = true;
3511 break;
3512 }
3513 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003514 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003515 applyVolume = true;
3516 }
3517 }
3518 if (isPreempted || applyVolume) {
3519 break;
3520 }
3521 }
3522 if (!applyVolume) {
3523 continue; // next output
3524 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003525 }
François Gaffieed91f582020-01-31 10:35:37 +01003526 //FIXME: workaround for truncated touch sounds
3527 // delayed volume change for system stream to be removed when the problem is
3528 // handled by system UI
3529 status_t volStatus = checkAndSetVolume(
3530 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003531 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003532 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3533 if (volStatus != NO_ERROR) {
3534 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003535 }
3536 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003537
3538 // update voice volume if the an active call route exists
3539 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3540 && (curSrcDevices.find(
3541 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3542 != curSrcDevices.end())) {
3543 bool isVoiceVolSrc;
3544 bool isBtScoVolSrc;
3545 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3546 isVoiceVolSrc, isBtScoVolSrc, __func__)
3547 && (isVoiceVolSrc || isBtScoVolSrc)) {
3548 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3549 }
3550 }
3551
François Gaffiecfe17322018-11-07 13:41:29 +01003552 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3553 return status;
3554}
3555
François Gaffieaaac0fd2018-11-22 17:56:39 +01003556status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003557 audio_devices_t device,
3558 IVolumeCurves &volumeCurves)
3559{
3560 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3561 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003562 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3563 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003564 (index > volumeCurves.getVolumeIndexMax())) {
3565 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3566 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3567 return BAD_VALUE;
3568 }
3569 if (!audio_is_output_device(device)) {
3570 return BAD_VALUE;
3571 }
3572
3573 // Force max volume if stream cannot be muted
3574 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3575
François Gaffieaaac0fd2018-11-22 17:56:39 +01003576 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003577 volumeCurves.addCurrentVolumeIndex(device, index);
3578 return NO_ERROR;
3579}
3580
3581status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3582 int &index,
3583 audio_devices_t device)
3584{
3585 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3586 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003587 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003588 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003589 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003590 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003591 }
jiabin9a3361e2019-10-01 09:38:30 -07003592 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003593}
3594
3595status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3596 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003597 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003598{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003599 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003600 return BAD_VALUE;
3601 }
jiabin9a3361e2019-10-01 09:38:30 -07003602 index = curves.getVolumeIndex(deviceTypes);
3603 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003604 return NO_ERROR;
3605}
3606
3607status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3608 int &index)
3609{
3610 index = getVolumeCurves(attr).getVolumeIndexMin();
3611 return NO_ERROR;
3612}
3613
3614status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3615 int &index)
3616{
3617 index = getVolumeCurves(attr).getVolumeIndexMax();
3618 return NO_ERROR;
3619}
3620
Eric Laurent36829f92017-04-07 19:04:42 -07003621audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003622{
3623 // select one output among several suitable for global effects.
3624 // The priority is as follows:
3625 // 1: An offloaded output. If the effect ends up not being offloadable,
3626 // AudioFlinger will invalidate the track and the offloaded output
3627 // will be closed causing the effect to be moved to a PCM output.
3628 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003629 // 3: The primary output
3630 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003631
François Gaffiec005e562018-11-06 15:04:49 +01003632 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3633 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003634 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003635
Eric Laurent36829f92017-04-07 19:04:42 -07003636 if (outputs.size() == 0) {
3637 return AUDIO_IO_HANDLE_NONE;
3638 }
Eric Laurente552edb2014-03-10 17:42:56 -07003639
Eric Laurent36829f92017-04-07 19:04:42 -07003640 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3641 bool activeOnly = true;
3642
3643 while (output == AUDIO_IO_HANDLE_NONE) {
3644 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3645 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3646 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3647
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003648 for (audio_io_handle_t output : outputs) {
3649 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003650 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003651 continue;
3652 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003653 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3654 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003655 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003656 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003657 }
3658 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003659 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003660 }
3661 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003662 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003663 }
3664 }
3665 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3666 output = outputOffloaded;
3667 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3668 output = outputDeepBuffer;
3669 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3670 output = outputPrimary;
3671 } else {
3672 output = outputs[0];
3673 }
3674 activeOnly = false;
3675 }
3676
3677 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003678 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3679 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003680 mMusicEffectOutput = output;
3681 }
3682
3683 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003684 return output;
3685}
3686
Eric Laurent36829f92017-04-07 19:04:42 -07003687audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3688{
3689 return selectOutputForMusicEffects();
3690}
3691
Eric Laurente0720872014-03-11 09:30:41 -07003692status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003693 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003694 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003695 int session,
3696 int id)
3697{
Shunkai Yao29d10572024-03-19 04:31:47 +00003698 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003699 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003700 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003701 index = mInputs.indexOfKey(io);
3702 if (index < 0) {
3703 ALOGW("registerEffect() unknown io %d", io);
3704 return INVALID_OPERATION;
3705 }
Eric Laurente552edb2014-03-10 17:42:56 -07003706 }
3707 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003708 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3709 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3710 || strategy == PRODUCT_STRATEGY_NONE));
3711 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003712}
3713
Eric Laurentc241b0d2018-11-28 09:08:49 -08003714status_t AudioPolicyManager::unregisterEffect(int id)
3715{
3716 if (mEffects.getEffect(id) == nullptr) {
3717 return INVALID_OPERATION;
3718 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003719 if (mEffects.isEffectEnabled(id)) {
3720 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3721 setEffectEnabled(id, false);
3722 }
3723 return mEffects.unregisterEffect(id);
3724}
3725
3726status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3727{
3728 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3729 if (effect == nullptr) {
3730 return INVALID_OPERATION;
3731 }
3732
3733 status_t status = mEffects.setEffectEnabled(id, enabled);
3734 if (status == NO_ERROR) {
3735 mInputs.trackEffectEnabled(effect, enabled);
3736 }
3737 return status;
3738}
3739
Eric Laurent6c796322019-04-09 14:13:17 -07003740
3741status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3742{
3743 mEffects.moveEffects(ids, io);
3744 return NO_ERROR;
3745}
3746
Eric Laurentc75307b2015-03-17 15:29:32 -07003747bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3748{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003749 auto vs = toVolumeSource(stream, false);
3750 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003751}
3752
3753bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3754{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003755 auto vs = toVolumeSource(stream, false);
3756 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003757}
3758
Eric Laurente0720872014-03-11 09:30:41 -07003759bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003760{
3761 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003762 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003763 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003764 return true;
3765 }
3766 }
3767 return false;
3768}
3769
Eric Laurent275e8e92014-11-30 15:14:47 -08003770// Register a list of custom mixes with their attributes and format.
3771// When a mix is registered, corresponding input and output profiles are
3772// added to the remote submix hw module. The profile contains only the
3773// parameters (sampling rate, format...) specified by the mix.
3774// The corresponding input remote submix device is also connected.
3775//
3776// When a remote submix device is connected, the address is checked to select the
3777// appropriate profile and the corresponding input or output stream is opened.
3778//
3779// When capture starts, getInputForAttr() will:
3780// - 1 look for a mix matching the address passed in attribtutes tags if any
3781// - 2 if none found, getDeviceForInputSource() will:
3782// - 2.1 look for a mix matching the attributes source
3783// - 2.2 if none found, default to device selection by policy rules
3784// At this time, the corresponding output remote submix device is also connected
3785// and active playback use cases can be transferred to this mix if needed when reconnecting
3786// after AudioTracks are invalidated
3787//
3788// When playback starts, getOutputForAttr() will:
3789// - 1 look for a mix matching the address passed in attribtutes tags if any
3790// - 2 if none found, look for a mix matching the attributes usage
3791// - 3 if none found, default to device and output selection by policy rules.
3792
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003793status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003794{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003795 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3796 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003797 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003798 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003799 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 // examine each mix's route type
3801 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003802 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003803 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3804 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3805 ALOGE("Unsupported Policy Mix %zu of %zu: "
3806 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3807 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003808 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003809 break;
3810 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003811 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3812 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003813 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003814 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3815 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003817 rSubmixModule = mHwModules.getModuleFromName(
3818 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3819 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003820 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003821 i);
3822 res = INVALID_OPERATION;
3823 break;
3824 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003825 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003826
Eric Laurent97ac8712018-07-27 18:59:02 -07003827 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003828 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003829 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003830 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003831 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3832 } else {
3833 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3834 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003835 }
François Gaffie036e1e92015-03-19 10:16:24 +01003836
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003837 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003838 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003839 res = INVALID_OPERATION;
3840 break;
3841 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003842 audio_config_t outputConfig = mix.mFormat;
3843 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003844 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3845 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003846 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3847 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003848 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003849 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3850 audio_is_linear_pcm(outputConfig.format)
3851 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003852 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003853 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3854 audio_is_linear_pcm(inputConfig.format)
3855 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003856
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003857 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003858 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003859 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003860 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003861 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003862 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003864 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3865 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003866 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003867 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003868 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003869
3870 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3871 mix.mDeviceType, mix.mDeviceAddress,
3872 String8(), AUDIO_FORMAT_DEFAULT);
3873 if (device == nullptr) {
3874 res = INVALID_OPERATION;
3875 break;
3876 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003878 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003879 // First try to find an already opened output supporting the device
3880 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003881 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003882
Eric Laurentc529cf62020-04-17 18:19:10 -07003883 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003884 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003885 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003886 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003887 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003888 } else {
3889 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003890 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003891 }
3892 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003893 // If no output found, try to find a direct output profile supporting the device
3894 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3895 sp<HwModule> module = mHwModules[i];
3896 for (size_t j = 0;
3897 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3898 j++) {
3899 sp<IOProfile> profile = module->getOutputProfiles()[j];
3900 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3901 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3902 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003903 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003904 res = INVALID_OPERATION;
3905 } else {
3906 foundOutput = true;
3907 }
3908 }
3909 }
3910 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003911 if (res != NO_ERROR) {
3912 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003913 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003914 res = INVALID_OPERATION;
3915 break;
3916 } else if (!foundOutput) {
3917 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003918 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003919 res = INVALID_OPERATION;
3920 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003921 } else {
3922 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003923 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003924 }
Eric Laurentc722f302014-12-10 11:21:49 -08003925 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003926 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003927 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003928 if (audio_flags::audio_mix_ownership()) {
3929 // Only unregister mixes that were actually registered to not accidentally unregister
3930 // mixes that already existed previously.
3931 unregisterPolicyMixes(registeredMixes);
3932 registeredMixes.clear();
3933 } else {
3934 unregisterPolicyMixes(mixes);
3935 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003936 } else if (checkOutputs) {
3937 checkForDeviceAndOutputChanges();
3938 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003939 }
3940 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003941}
3942
3943status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3944{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003945 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003946 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003947 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003948 sp<HwModule> rSubmixModule;
3949 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003950 for (const auto& mix : mixes) {
3951 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003952
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003953 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003954 rSubmixModule = mHwModules.getModuleFromName(
3955 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3956 if (rSubmixModule == 0) {
3957 res = INVALID_OPERATION;
3958 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003959 }
3960 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003961
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003962 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003963
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003964 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003965 res = INVALID_OPERATION;
3966 continue;
3967 }
3968
Marvin Ramin0783e202024-03-05 12:45:50 +01003969 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003970 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01003971 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3972 status_t currentRes =
3973 setDeviceConnectionStateInt(device,
3974 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3975 address.c_str(),
3976 "remote-submix",
3977 AUDIO_FORMAT_DEFAULT);
3978 if (!audio_flags::audio_mix_ownership()) {
3979 res = currentRes;
3980 }
3981 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003982 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003983 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01003984 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003985 }
3986 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003987 }
jiabin5740f082019-08-19 15:08:30 -07003988 rSubmixModule->removeOutputProfile(address.c_str());
3989 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003990
Kevin Rocard153f92d2018-12-18 18:33:28 -08003991 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003992 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003993 res = INVALID_OPERATION;
3994 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003995 } else {
3996 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003997 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003998 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003999 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004000
4001 if (res == NO_ERROR && checkOutputs) {
4002 checkForDeviceAndOutputChanges();
4003 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004004 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004005 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004006}
4007
Marvin Raminbdefaf02023-11-01 09:10:32 +01004008status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4009 if (!audio_flags::audio_mix_test_api()) {
4010 return INVALID_OPERATION;
4011 }
4012
4013 _aidl_return.clear();
4014 _aidl_return.reserve(mPolicyMixes.size());
4015 for (const auto &policyMix: mPolicyMixes) {
4016 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4017 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4018 policyMix->mCbFlags);
4019 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004020 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004021 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004022 }
4023
Vlad Popaa5d73f32024-03-08 16:05:38 -08004024 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004025 return OK;
4026}
4027
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004028status_t AudioPolicyManager::updatePolicyMix(
4029 const AudioMix& mix,
4030 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4031 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4032 if (res == NO_ERROR) {
4033 checkForDeviceAndOutputChanges();
4034 updateCallAndOutputRouting();
4035 }
4036 return res;
4037}
4038
Mikhail Naganov100f0122018-11-29 11:22:16 -08004039void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4040{
4041 size_t i = 0;
4042 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4043 for (const auto& fmt : mManualSurroundFormats) {
4044 if (i++ != 0) dst->append(", ");
4045 std::string sfmt;
4046 FormatConverter::toString(fmt, sfmt);
4047 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4048 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4049 }
4050}
4051
Eric Laurentc529cf62020-04-17 18:19:10 -07004052// Returns true if all devices types match the predicate and are supported by one HW module
4053bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004054 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004055 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004056 const char *context,
4057 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004058 for (size_t i = 0; i < devices.size(); i++) {
4059 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004060 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004061 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004062 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004063 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004064 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004065 return false;
4066 }
4067 }
4068 return true;
4069}
4070
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004071void AudioPolicyManager::changeOutputDevicesMuteState(
4072 const AudioDeviceTypeAddrVector& devices) {
4073 ALOGVV("%s() num devices %zu", __func__, devices.size());
4074
4075 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4076 getSoftwareOutputsForDevices(devices);
4077
4078 for (size_t i = 0; i < outputs.size(); i++) {
4079 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4080 DeviceVector prevDevices = outputDesc->devices();
4081 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4082 }
4083}
4084
4085std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4086 const AudioDeviceTypeAddrVector& devices) const
4087{
4088 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4089 DeviceVector deviceDescriptors;
4090 for (size_t j = 0; j < devices.size(); j++) {
4091 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4092 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4093 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4094 ALOGE("%s: device type %#x address %s not supported or not an output device",
4095 __func__, devices[j].mType, devices[j].getAddress());
4096 continue;
4097 }
4098 deviceDescriptors.add(desc);
4099 }
4100 for (size_t i = 0; i < mOutputs.size(); i++) {
4101 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4102 continue;
4103 }
4104 outputs.push_back(mOutputs.valueAt(i));
4105 }
4106 return outputs;
4107}
4108
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004109status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004110 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004111 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004112 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4113 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004114 }
4115 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004116 if (res != NO_ERROR) {
4117 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4118 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004119 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004120
4121 checkForDeviceAndOutputChanges();
4122 updateCallAndOutputRouting();
4123
4124 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004125}
4126
4127status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4128 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004129 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4130 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004131 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004132 __FUNCTION__, uid);
4133 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004134 }
4135
Eric Laurentc529cf62020-04-17 18:19:10 -07004136 checkForDeviceAndOutputChanges();
4137 updateCallAndOutputRouting();
4138
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004139 return res;
4140}
4141
Eric Laurent2517af32020-11-25 15:31:27 +01004142
jiabin0a488932020-08-07 17:32:40 -07004143status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4144 device_role_t role,
4145 const AudioDeviceTypeAddrVector &devices) {
4146 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4147 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004148
Eric Laurentc529cf62020-04-17 18:19:10 -07004149 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004150 return BAD_VALUE;
4151 }
jiabin0a488932020-08-07 17:32:40 -07004152 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004153 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004154 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4155 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004156 return status;
4157 }
4158
4159 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004160
4161 bool forceVolumeReeval = false;
4162 // FIXME: workaround for truncated touch sounds
4163 // to be removed when the problem is handled by system UI
4164 uint32_t delayMs = 0;
4165 if (strategy == mCommunnicationStrategy) {
4166 forceVolumeReeval = true;
4167 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4168 updateInputRouting();
4169 }
4170 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004171
4172 return NO_ERROR;
4173}
4174
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004175void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4176 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004177{
4178 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004179 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004180 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004181 // Only apply special touch sound delay once
4182 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004183 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004184 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004185 for (size_t i = 0; i < mOutputs.size(); i++) {
4186 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4187 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004188 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4189 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004190 // As done in setDeviceConnectionState, we could also fix default device issue by
4191 // preventing the force re-routing in case of default dev that distinguishes on address.
4192 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004193 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004194 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004195 // If the device is using preferred mixer attributes, the output need to reopen
4196 // with default configuration when the new selected devices are different from
4197 // current routing devices.
4198 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4199 continue;
4200 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304201
4202 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4203 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004204 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004205 // Only apply special touch sound delay once
4206 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004207 }
4208 if (forceVolumeReeval && !newDevices.isEmpty()) {
4209 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4210 }
4211 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004212 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004213 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004214}
4215
Eric Laurent2517af32020-11-25 15:31:27 +01004216void AudioPolicyManager::updateInputRouting() {
4217 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304218 // Skip for hotword recording as the input device switch
4219 // is handled within sound trigger HAL
4220 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4221 continue;
4222 }
Eric Laurent2517af32020-11-25 15:31:27 +01004223 auto newDevice = getNewInputDevice(activeDesc);
4224 // Force new input selection if the new device can not be reached via current input
4225 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4226 setInputDevice(activeDesc->mIoHandle, newDevice);
4227 } else {
4228 closeInput(activeDesc->mIoHandle);
4229 }
4230 }
4231}
4232
Paul Wang5d7cdb52022-11-22 09:45:06 +00004233status_t
4234AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4235 device_role_t role,
4236 const AudioDeviceTypeAddrVector &devices) {
4237 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4238 dumpAudioDeviceTypeAddrVector(devices).c_str());
4239
Eric Laurent78fedbf2023-03-09 14:40:44 +01004240 if (!areAllDevicesSupported(
4241 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004242 return BAD_VALUE;
4243 }
4244 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4245 if (status != NO_ERROR) {
4246 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4247 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4248 return status;
4249 }
4250
4251 checkForDeviceAndOutputChanges();
4252
4253 bool forceVolumeReeval = false;
4254 // TODO(b/263479999): workaround for truncated touch sounds
4255 // to be removed when the problem is handled by system UI
4256 uint32_t delayMs = 0;
4257 if (strategy == mCommunnicationStrategy) {
4258 forceVolumeReeval = true;
4259 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4260 updateInputRouting();
4261 }
4262 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4263
4264 return NO_ERROR;
4265}
4266
4267status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4268 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004269{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004270 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004271
Paul Wang5d7cdb52022-11-22 09:45:06 +00004272 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004273 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004274 ALOGW_IF(status != NAME_NOT_FOUND,
4275 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004276 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004277 return status;
4278 }
4279
4280 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004281
4282 bool forceVolumeReeval = false;
4283 // FIXME: workaround for truncated touch sounds
4284 // to be removed when the problem is handled by system UI
4285 uint32_t delayMs = 0;
4286 if (strategy == mCommunnicationStrategy) {
4287 forceVolumeReeval = true;
4288 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4289 updateInputRouting();
4290 }
4291 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004292
4293 return NO_ERROR;
4294}
4295
jiabin0a488932020-08-07 17:32:40 -07004296status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4297 device_role_t role,
4298 AudioDeviceTypeAddrVector &devices) {
4299 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004300}
4301
Jiabin Huang3b98d322020-09-03 17:54:16 +00004302status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4303 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4304 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4305 dumpAudioDeviceTypeAddrVector(devices).c_str());
4306
Mikhail Naganov55773032020-10-01 15:08:13 -07004307 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004308 return BAD_VALUE;
4309 }
4310 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4311 ALOGW_IF(status != NO_ERROR,
4312 "Engine could not set preferred devices %s for audio source %d role %d",
4313 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4314
4315 return status;
4316}
4317
4318status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4319 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4320 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4321 dumpAudioDeviceTypeAddrVector(devices).c_str());
4322
Mikhail Naganov55773032020-10-01 15:08:13 -07004323 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004324 return BAD_VALUE;
4325 }
4326 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4327 ALOGW_IF(status != NO_ERROR,
4328 "Engine could not add preferred devices %s for audio source %d role %d",
4329 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4330
Eric Laurent2517af32020-11-25 15:31:27 +01004331 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004332 return status;
4333}
4334
4335status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4336 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4337{
4338 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4339 dumpAudioDeviceTypeAddrVector(devices).c_str());
4340
Eric Laurent78fedbf2023-03-09 14:40:44 +01004341 if (!areAllDevicesSupported(
4342 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004343 return BAD_VALUE;
4344 }
4345
4346 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4347 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004348 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004349 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004350 if (status == NO_ERROR) {
4351 updateInputRouting();
4352 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004353 return status;
4354}
4355
4356status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4357 device_role_t role) {
4358 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4359
4360 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004361 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004362 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004363 if (status == NO_ERROR) {
4364 updateInputRouting();
4365 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004366 return status;
4367}
4368
4369status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4370 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4371 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4372}
4373
Oscar Azucena90e77632019-11-27 17:12:28 -08004374status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004375 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004376 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004377 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4378 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004379 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004380 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4381 if (status != NO_ERROR) {
4382 ALOGE("%s() could not set device affinity for userId %d",
4383 __FUNCTION__, userId);
4384 return status;
4385 }
4386
4387 // reevaluate outputs for all devices
4388 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004389 changeOutputDevicesMuteState(devices);
4390 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4391 true /* skipDelays */);
4392 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004393
4394 return NO_ERROR;
4395}
4396
4397status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004398 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004399 AudioDeviceTypeAddrVector devices;
4400 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004401 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4402 if (status != NO_ERROR) {
4403 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4404 __FUNCTION__, userId);
4405 return status;
4406 }
4407
4408 // reevaluate outputs for all devices
4409 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004410 changeOutputDevicesMuteState(devices);
4411 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4412 true /* skipDelays */);
4413 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004414
4415 return NO_ERROR;
4416}
4417
Andy Hungc29d82b2018-10-05 12:23:17 -07004418void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004419{
Andy Hungc29d82b2018-10-05 12:23:17 -07004420 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004421 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004422 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004423 std::string stateLiteral;
4424 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004425 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004426 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4427 "communications", "media", "record", "dock", "system",
4428 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4429 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4430 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004431 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4432 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4433 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4434 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4435 dst->append(" (MANUAL: ");
4436 dumpManualSurroundFormats(dst);
4437 dst->append(")");
4438 }
4439 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004440 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004441 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4442 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004443 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004444 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004445
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004446 dst->append("\n");
4447 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4448 dst->append("\n");
4449 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004450 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004451 mOutputs.dump(dst);
4452 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004453 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004454 mAudioPatches.dump(dst);
4455 mPolicyMixes.dump(dst);
4456 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004457
Kevin Rocardb99cc752019-03-21 20:52:24 -07004458 dst->appendFormat(" AllowedCapturePolicies:\n");
4459 for (auto& policy : mAllowedCapturePolicies) {
4460 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4461 }
4462
jiabina84c3d32022-12-02 18:59:55 +00004463 dst->appendFormat(" Preferred mixer audio configuration:\n");
4464 for (const auto it : mPreferredMixerAttrInfos) {
4465 dst->appendFormat(" - device port id: %d\n", it.first);
4466 for (const auto preferredMixerInfoIt : it.second) {
4467 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4468 preferredMixerInfoIt.second->dump(dst);
4469 }
4470 }
4471
François Gaffiec005e562018-11-06 15:04:49 +01004472 dst->appendFormat("\nPolicy Engine dump:\n");
4473 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004474}
4475
4476status_t AudioPolicyManager::dump(int fd)
4477{
4478 String8 result;
4479 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004480 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004481 return NO_ERROR;
4482}
4483
Kevin Rocardb99cc752019-03-21 20:52:24 -07004484status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4485{
4486 mAllowedCapturePolicies[uid] = capturePolicy;
4487 return NO_ERROR;
4488}
4489
Eric Laurente552edb2014-03-10 17:42:56 -07004490// This function checks for the parameters which can be offloaded.
4491// This can be enhanced depending on the capability of the DSP and policy
4492// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004493audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004494{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004495 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004496 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004497 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004498 offloadInfo.format,
4499 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4500 offloadInfo.has_video);
4501
jiabin2b9d5a12021-12-10 01:06:29 +00004502 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004503 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004504 }
4505
4506 // See if there is a profile to support this.
4507 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004508 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004509 offloadInfo.sample_rate,
4510 offloadInfo.format,
4511 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004512 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4513 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004514 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4515 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4516 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004517 if (profile == nullptr) {
4518 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4519 }
4520 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4521 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4522 }
4523 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004524}
4525
Michael Chana94fbb22018-04-24 14:31:19 +10004526bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4527 const audio_attributes_t& attributes) {
4528 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004529 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004530 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4531 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004532 config.sample_rate,
4533 config.format,
4534 config.channel_mask,
4535 output_flags,
4536 true /* directOnly */);
4537 ALOGV("%s() profile %sfound with name: %s, "
4538 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4539 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004540 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004541 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004542
4543 // also try the MSD module if compatible profile not found
4544 if (profile == nullptr) {
4545 profile = getMsdProfileForOutput(outputDevices,
4546 config.sample_rate,
4547 config.format,
4548 config.channel_mask,
4549 output_flags,
4550 true /* directOnly */);
4551 ALOGV("%s() MSD profile %sfound with name: %s, "
4552 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4553 __FUNCTION__, profile != 0 ? "" : "NOT ",
4554 (profile != 0 ? profile->getTagName().c_str() : "null"),
4555 config.sample_rate, config.format, config.channel_mask, output_flags);
4556 }
4557 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004558}
4559
jiabin2b9d5a12021-12-10 01:06:29 +00004560bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4561 bool durationIgnored) {
4562 if (mMasterMono) {
4563 return false; // no offloading if mono is set.
4564 }
4565
4566 // Check if offload has been disabled
4567 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4568 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4569 return false;
4570 }
4571
4572 // Check if stream type is music, then only allow offload as of now.
4573 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4574 {
4575 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4576 return false;
4577 }
4578
4579 //TODO: enable audio offloading with video when ready
4580 const bool allowOffloadWithVideo =
4581 property_get_bool("audio.offload.video", false /* default_value */);
4582 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4583 ALOGV("%s: has_video == true, returning false", __func__);
4584 return false;
4585 }
4586
4587 //If duration is less than minimum value defined in property, return false
4588 const int min_duration_secs = property_get_int32(
4589 "audio.offload.min.duration.secs", -1 /* default_value */);
4590 if (!durationIgnored) {
4591 if (min_duration_secs >= 0) {
4592 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4593 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4594 __func__, min_duration_secs);
4595 return false;
4596 }
4597 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4598 ALOGV("%s: Offload denied by duration < default min(=%u)",
4599 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4600 return false;
4601 }
4602 }
4603
4604 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4605 // creating an offloaded track and tearing it down immediately after start when audioflinger
4606 // detects there is an active non offloadable effect.
4607 // FIXME: We should check the audio session here but we do not have it in this context.
4608 // This may prevent offloading in rare situations where effects are left active by apps
4609 // in the background.
4610 if (mEffects.isNonOffloadableEffectEnabled()) {
4611 return false;
4612 }
4613
4614 return true;
4615}
4616
4617audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4618 const audio_config_t *config) {
4619 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4620 offloadInfo.format = config->format;
4621 offloadInfo.sample_rate = config->sample_rate;
4622 offloadInfo.channel_mask = config->channel_mask;
4623 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4624 offloadInfo.has_video = false;
4625 offloadInfo.is_streaming = false;
4626 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4627
4628 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4629 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4630 audio_flags_to_audio_output_flags(attr->flags, &flags);
4631 // only retain flags that will drive compressed offload or passthrough
4632 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4633 if (offloadPossible) {
4634 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4635 }
4636 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4637
Dorin Drimusfae3c642022-03-17 18:36:30 +01004638 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004639 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004640 DeviceVector outputDevices = engineOutputDevices;
4641 // the MSD module checks for different conditions and output devices
4642 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4643 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4644 continue;
4645 }
4646 outputDevices = getMsdAudioOutDevices();
4647 }
jiabin2b9d5a12021-12-10 01:06:29 +00004648 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004649 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004650 config->sample_rate, nullptr /*updatedSamplingRate*/,
4651 config->format, nullptr /*updatedFormat*/,
4652 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004653 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004654 continue;
4655 }
4656 // reject profiles not corresponding to a device currently available
4657 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4658 continue;
4659 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004660 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4661 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004662 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004663 != AUDIO_DIRECT_NOT_SUPPORTED) {
4664 // Already reports offload gapless supported. No need to report offload support.
4665 continue;
4666 }
4667 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4668 != AUDIO_OUTPUT_FLAG_NONE) {
4669 // If offload gapless is reported, no need to report offload support.
4670 directMode = (audio_direct_mode_t) ((directMode &
4671 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4672 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4673 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004674 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004675 }
4676 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004677 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004678 }
4679 }
4680 }
4681 return directMode;
4682}
4683
Dorin Drimusf2196d82022-01-03 12:11:18 +01004684status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4685 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004686 if (mEffects.isNonOffloadableEffectEnabled()) {
4687 return OK;
4688 }
jiabinf1c73972022-04-14 16:28:52 -07004689 DeviceVector devices;
4690 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004691 if (status != OK) {
4692 return status;
4693 }
4694 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4695 if (devices.empty()) {
4696 return OK; // no output devices for the attributes
4697 }
jiabinf1c73972022-04-14 16:28:52 -07004698 return getProfilesForDevices(devices, audioProfilesVector,
4699 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004700}
4701
jiabina84c3d32022-12-02 18:59:55 +00004702status_t AudioPolicyManager::getSupportedMixerAttributes(
4703 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4704 ALOGV("%s, portId=%d", __func__, portId);
4705 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4706 if (deviceDescriptor == nullptr) {
4707 ALOGE("%s the requested device is currently unavailable", __func__);
4708 return BAD_VALUE;
4709 }
jiabin96daffc2023-05-11 17:51:55 +00004710 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4711 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4712 deviceDescriptor->type());
4713 return BAD_VALUE;
4714 }
jiabina84c3d32022-12-02 18:59:55 +00004715 for (const auto& hwModule : mHwModules) {
4716 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4717 if (curProfile->supportsDevice(deviceDescriptor)) {
4718 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4719 }
4720 }
4721 }
4722 return NO_ERROR;
4723}
4724
4725status_t AudioPolicyManager::setPreferredMixerAttributes(
4726 const audio_attributes_t *attr,
4727 audio_port_handle_t portId,
4728 uid_t uid,
4729 const audio_mixer_attributes_t *mixerAttributes) {
4730 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4731 "mixerBehavior=%d}, uid=%d, portId=%u",
4732 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4733 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4734 mixerAttributes->mixer_behavior, uid, portId);
4735 if (attr->usage != AUDIO_USAGE_MEDIA) {
4736 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4737 return BAD_VALUE;
4738 }
4739 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4740 if (deviceDescriptor == nullptr) {
4741 ALOGE("%s the requested device is currently unavailable", __func__);
4742 return BAD_VALUE;
4743 }
4744 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4745 ALOGE("%s(%d), type=%d, is not a usb output device",
4746 __func__, portId, deviceDescriptor->type());
4747 return BAD_VALUE;
4748 }
4749
4750 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4751 audio_flags_to_audio_output_flags(attr->flags, &flags);
4752 flags = (audio_output_flags_t) (flags |
4753 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4754 sp<IOProfile> profile = nullptr;
4755 DeviceVector devices(deviceDescriptor);
4756 for (const auto& hwModule : mHwModules) {
4757 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4758 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004759 && curProfile->getCompatibilityScore(
4760 devices,
4761 mixerAttributes->config.sample_rate,
4762 nullptr /*updatedSamplingRate*/,
4763 mixerAttributes->config.format,
4764 nullptr /*updatedFormat*/,
4765 mixerAttributes->config.channel_mask,
4766 nullptr /*updatedChannelMask*/,
4767 flags,
4768 false /*exactMatchRequiredForInputFlags*/)
4769 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004770 profile = curProfile;
4771 break;
4772 }
4773 }
4774 }
4775 if (profile == nullptr) {
4776 ALOGE("%s, there is no compatible profile found", __func__);
4777 return BAD_VALUE;
4778 }
4779
4780 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4781 sp<PreferredMixerAttributesInfo>::make(
4782 uid, portId, profile, flags, *mixerAttributes);
4783 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4784 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4785
4786 // If 1) there is any client from the preferred mixer configuration owner that is currently
4787 // active and matches the strategy and 2) current output is on the preferred device and the
4788 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4789 // configuration.
4790 std::vector<audio_io_handle_t> outputsToReopen;
4791 for (size_t i = 0; i < mOutputs.size(); i++) {
4792 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004793 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4794 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004795 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004796 } else {
4797 for (const auto &client: output->getActiveClients()) {
4798 if (client->uid() == uid && client->strategy() == strategy) {
4799 client->setIsInvalid();
4800 outputsToReopen.push_back(output->mIoHandle);
4801 }
jiabina84c3d32022-12-02 18:59:55 +00004802 }
4803 }
4804 }
4805 }
4806 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4807 config.sample_rate = mixerAttributes->config.sample_rate;
4808 config.channel_mask = mixerAttributes->config.channel_mask;
4809 config.format = mixerAttributes->config.format;
4810 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004811 sp<SwAudioOutputDescriptor> desc =
4812 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4813 if (desc == nullptr) {
4814 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4815 continue;
4816 }
jiabin220eea12024-05-17 17:55:20 +00004817 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004818 }
4819
4820 return NO_ERROR;
4821}
4822
4823sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004824 audio_port_handle_t devicePortId,
4825 product_strategy_t strategy,
4826 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004827 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4828 if (it == mPreferredMixerAttrInfos.end()) {
4829 return nullptr;
4830 }
jiabind9a58d32023-06-01 17:57:30 +00004831 if (activeBitPerfectPreferred) {
4832 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004833 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004834 return info;
4835 }
4836 }
jiabina84c3d32022-12-02 18:59:55 +00004837 }
jiabind9a58d32023-06-01 17:57:30 +00004838 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4839 return strategyMatchedMixerAttrInfoIt == it->second.end()
4840 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004841}
4842
4843status_t AudioPolicyManager::getPreferredMixerAttributes(
4844 const audio_attributes_t *attr,
4845 audio_port_handle_t portId,
4846 audio_mixer_attributes_t* mixerAttributes) {
4847 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4848 portId, mEngine->getProductStrategyForAttributes(*attr));
4849 if (info == nullptr) {
4850 return NAME_NOT_FOUND;
4851 }
4852 *mixerAttributes = info->getMixerAttributes();
4853 return NO_ERROR;
4854}
4855
4856status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4857 audio_port_handle_t portId,
4858 uid_t uid) {
4859 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4860 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4861 if (preferredMixerAttrInfo == nullptr) {
4862 return NAME_NOT_FOUND;
4863 }
4864 if (preferredMixerAttrInfo->getUid() != uid) {
4865 ALOGE("%s, requested uid=%d, owned uid=%d",
4866 __func__, uid, preferredMixerAttrInfo->getUid());
4867 return PERMISSION_DENIED;
4868 }
4869 mPreferredMixerAttrInfos[portId].erase(strategy);
4870 if (mPreferredMixerAttrInfos[portId].empty()) {
4871 mPreferredMixerAttrInfos.erase(portId);
4872 }
4873
4874 // Reconfig existing output
4875 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4876 for (size_t i = 0; i < mOutputs.size(); i++) {
4877 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4878 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4879 }
4880 }
4881 for (const auto output : potentialOutputsToReopen) {
4882 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4883 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4884 preferredMixerAttrInfo->getFlags())) {
4885 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4886 }
4887 }
4888 return NO_ERROR;
4889}
4890
Eric Laurent6a94d692014-05-20 11:18:06 -07004891status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4892 audio_port_type_t type,
4893 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004894 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004895 unsigned int *generation)
4896{
jiabin19cdba52020-11-24 11:28:58 -08004897 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4898 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004899 return BAD_VALUE;
4900 }
4901 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004902 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004903 *num_ports = 0;
4904 }
4905
4906 size_t portsWritten = 0;
4907 size_t portsMax = *num_ports;
4908 *num_ports = 0;
4909 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004910 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4911 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004912 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004913 for (const auto& dev : mAvailableOutputDevices) {
4914 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004915 continue;
4916 }
4917 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004918 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004919 }
4920 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004922 }
4923 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004924 for (const auto& dev : mAvailableInputDevices) {
4925 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004926 continue;
4927 }
4928 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004929 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004930 }
4931 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 }
4934 }
4935 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4936 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4937 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4938 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4939 }
4940 *num_ports += mInputs.size();
4941 }
4942 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004943 size_t numOutputs = 0;
4944 for (size_t i = 0; i < mOutputs.size(); i++) {
4945 if (!mOutputs[i]->isDuplicated()) {
4946 numOutputs++;
4947 if (portsWritten < portsMax) {
4948 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4949 }
4950 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 }
Eric Laurent84c70242014-06-23 08:46:27 -07004952 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004953 }
4954 }
jiabina84c3d32022-12-02 18:59:55 +00004955
Eric Laurent6a94d692014-05-20 11:18:06 -07004956 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004957 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 return NO_ERROR;
4959}
4960
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004961status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4962 std::vector<media::AudioPortFw>* _aidl_return) {
4963 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4964 audio_port_v7 port;
4965 dev->toAudioPort(&port);
4966 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4967 _aidl_return->push_back(std::move(aidlPort));
4968 return OK;
4969 };
4970
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004971 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004972 for (const auto& dev : module->getDeclaredDevices()) {
4973 if (role == media::AudioPortRole::NONE ||
4974 ((role == media::AudioPortRole::SOURCE)
4975 == audio_is_input_device(dev->type()))) {
4976 RETURN_STATUS_IF_ERROR(pushPort(dev));
4977 }
4978 }
4979 }
4980 return OK;
4981}
4982
jiabin19cdba52020-11-24 11:28:58 -08004983status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004984{
Eric Laurent99fcae42018-05-17 16:59:18 -07004985 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4986 return BAD_VALUE;
4987 }
4988 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4989 if (dev != 0) {
4990 dev->toAudioPort(port);
4991 return NO_ERROR;
4992 }
4993 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4994 if (dev != 0) {
4995 dev->toAudioPort(port);
4996 return NO_ERROR;
4997 }
4998 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4999 if (out != 0) {
5000 out->toAudioPort(port);
5001 return NO_ERROR;
5002 }
5003 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5004 if (in != 0) {
5005 in->toAudioPort(port);
5006 return NO_ERROR;
5007 }
5008 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005009}
5010
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005011status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5012 audio_patch_handle_t *handle,
5013 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005014{
François Gaffieafd4cea2019-11-18 15:50:22 +01005015 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 if (handle == NULL || patch == NULL) {
5017 return BAD_VALUE;
5018 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005020 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005021 return BAD_VALUE;
5022 }
5023 // only one source per audio patch supported for now
5024 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 return INVALID_OPERATION;
5026 }
Eric Laurent874c42872014-08-08 15:13:39 -07005027 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 return INVALID_OPERATION;
5029 }
Eric Laurent874c42872014-08-08 15:13:39 -07005030 for (size_t i = 0; i < patch->num_sinks; i++) {
5031 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5032 return INVALID_OPERATION;
5033 }
5034 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005035
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005036 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5037 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5038 if (srcDevice == nullptr || sinkDevice == nullptr) {
5039 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5040 return BAD_VALUE;
5041 }
5042 ALOGV("%s between source %s and sink %s", __func__,
5043 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5044 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5045 // Default attributes, default volume priority, not to infer with non raw audio patches.
5046 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5047 const struct audio_port_config *source = &patch->sources[0];
5048 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005049 new SourceClientDescriptor(
5050 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5051 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5052 true);
5053 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005054
5055 status_t status =
5056 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5057
5058 if (status != NO_ERROR) {
5059 return INVALID_OPERATION;
5060 }
5061 mAudioSources.add(portId, sourceDesc);
5062 return NO_ERROR;
5063}
5064
5065status_t AudioPolicyManager::connectAudioSourceToSink(
5066 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5067 const struct audio_patch *patch,
5068 audio_patch_handle_t &handle,
5069 uid_t uid, uint32_t delayMs)
5070{
5071 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5072 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5073 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5074 return INVALID_OPERATION;
5075 }
5076 sourceDesc->connect(handle, sinkDevice);
5077 if (isMsdPatch(handle)) {
5078 return NO_ERROR;
5079 }
5080 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5081 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5082 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5083 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5084 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5085 goto FailurePatchAdded;
5086 }
5087 status = swOutput->start();
5088 if (status != NO_ERROR) {
5089 goto FailureSourceAdded;
5090 }
5091 swOutput->addClient(sourceDesc);
5092 status = startSource(swOutput, sourceDesc, &delayMs);
5093 if (status != NO_ERROR) {
5094 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5095 goto FailureSourceActive;
5096 }
5097 if (delayMs != 0) {
5098 usleep(delayMs * 1000);
5099 }
5100 return NO_ERROR;
5101
5102FailureSourceActive:
5103 swOutput->stop();
5104 releaseOutput(sourceDesc->portId());
5105FailureSourceAdded:
5106 sourceDesc->setSwOutput(nullptr);
5107FailurePatchAdded:
5108 releaseAudioPatchInternal(handle);
5109 return INVALID_OPERATION;
5110}
5111
5112status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5113 audio_patch_handle_t *handle,
5114 uid_t uid, uint32_t delayMs,
5115 const sp<SourceClientDescriptor>& sourceDesc)
5116{
5117 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005118 sp<AudioPatch> patchDesc;
5119 ssize_t index = mAudioPatches.indexOfKey(*handle);
5120
François Gaffieafd4cea2019-11-18 15:50:22 +01005121 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5122 patch->sources[0].role,
5123 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005124#if LOG_NDEBUG == 0
5125 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005126 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5127 patch->sinks[i].role,
5128 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005129 }
5130#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005131
5132 if (index >= 0) {
5133 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005134 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5135 __func__, mUidCached, patchDesc->getUid(), uid);
5136 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005137 return INVALID_OPERATION;
5138 }
5139 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005140 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005141 }
5142
5143 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005144 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005146 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005147 return BAD_VALUE;
5148 }
Eric Laurent84c70242014-06-23 08:46:27 -07005149 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5150 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005151 if (patchDesc != 0) {
5152 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005153 ALOGV("%s source id differs for patch current id %d new id %d",
5154 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005155 return BAD_VALUE;
5156 }
5157 }
Eric Laurent874c42872014-08-08 15:13:39 -07005158 DeviceVector devices;
5159 for (size_t i = 0; i < patch->num_sinks; i++) {
5160 // Only support mix to devices connection
5161 // TODO add support for mix to mix connection
5162 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005163 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005164 return INVALID_OPERATION;
5165 }
5166 sp<DeviceDescriptor> devDesc =
5167 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5168 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005169 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005170 return BAD_VALUE;
5171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005172
jiabin66acc432024-02-06 00:57:36 +00005173 if (outputDesc->mProfile->getCompatibilityScore(
5174 DeviceVector(devDesc),
5175 patch->sources[0].sample_rate,
5176 nullptr, // updatedSamplingRate
5177 patch->sources[0].format,
5178 nullptr, // updatedFormat
5179 patch->sources[0].channel_mask,
5180 nullptr, // updatedChannelMask
5181 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005182 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005183 return INVALID_OPERATION;
5184 }
5185 devices.add(devDesc);
5186 }
5187 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 return INVALID_OPERATION;
5189 }
Eric Laurent874c42872014-08-08 15:13:39 -07005190
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005192 ALOGV("%s setting device %s on output %d",
5193 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305194 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005195 index = mAudioPatches.indexOfKey(*handle);
5196 if (index >= 0) {
5197 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005198 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005199 }
5200 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005201 patchDesc->setUid(uid);
5202 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 return INVALID_OPERATION;
5206 }
5207 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5208 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5209 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005210 // only one sink supported when connecting an input device to a mix
5211 if (patch->num_sinks > 1) {
5212 return INVALID_OPERATION;
5213 }
François Gaffie53615e22015-03-19 09:24:12 +01005214 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 if (inputDesc == NULL) {
5216 return BAD_VALUE;
5217 }
5218 if (patchDesc != 0) {
5219 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5220 return BAD_VALUE;
5221 }
5222 }
François Gaffie11d30102018-11-02 16:09:09 +01005223 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005224 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005225 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 return BAD_VALUE;
5227 }
5228
jiabin66acc432024-02-06 00:57:36 +00005229 if (inputDesc->mProfile->getCompatibilityScore(
5230 DeviceVector(device),
5231 patch->sinks[0].sample_rate,
5232 nullptr, /*updatedSampleRate*/
5233 patch->sinks[0].format,
5234 nullptr, /*updatedFormat*/
5235 patch->sinks[0].channel_mask,
5236 nullptr, /*updatedChannelMask*/
5237 // FIXME for the parameter type,
5238 // and the NONE
5239 (audio_output_flags_t)
5240 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005241 return INVALID_OPERATION;
5242 }
5243 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005244 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005245 device->toString().c_str(), inputDesc->mIoHandle);
5246 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 index = mAudioPatches.indexOfKey(*handle);
5248 if (index >= 0) {
5249 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005250 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 }
5252 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 patchDesc->setUid(uid);
5254 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005255 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005256 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 return INVALID_OPERATION;
5258 }
5259 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5260 // device to device connection
5261 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005262 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 return BAD_VALUE;
5264 }
5265 }
François Gaffie11d30102018-11-02 16:09:09 +01005266 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005268 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005269 return BAD_VALUE;
5270 }
Eric Laurent874c42872014-08-08 15:13:39 -07005271
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 //update source and sink with our own data as the data passed in the patch may
5273 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005274 PatchBuilder patchBuilder;
5275 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005276
5277 // if first sink is to MSD, establish single MSD patch
5278 if (getMsdAudioOutDevices().contains(
5279 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5280 ALOGV("%s patching to MSD", __FUNCTION__);
5281 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5282 goto installPatch;
5283 }
5284
François Gaffieafd4cea2019-11-18 15:50:22 +01005285 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5286 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005287
Eric Laurent874c42872014-08-08 15:13:39 -07005288 for (size_t i = 0; i < patch->num_sinks; i++) {
5289 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005291 return INVALID_OPERATION;
5292 }
François Gaffie11d30102018-11-02 16:09:09 +01005293 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005294 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005295 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005296 return BAD_VALUE;
5297 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005298 audio_port_config sinkPortConfig = {};
5299 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5300 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005301
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005302 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5303 // volume management purpose (tracking activity)
5304 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5305 // in config XML to reach the sink so that is can be declared as available.
5306 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005307 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005308 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005309 // take care of dynamic routing for SwOutput selection,
5310 audio_attributes_t attributes = sourceDesc->attributes();
5311 audio_stream_type_t stream = sourceDesc->stream();
5312 audio_attributes_t resultAttr;
5313 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5314 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005315 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5316 config.channel_mask =
5317 (audio_channel_mask_get_representation(sourceMask)
5318 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5319 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005320 config.format = sourceDesc->config().format;
5321 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5322 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5323 bool isRequestedDeviceForExclusiveUse = false;
5324 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005325 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005326 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005327 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5328 &stream, sourceDesc->uid(), &config, &flags,
5329 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005330 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005331 if (output == AUDIO_IO_HANDLE_NONE) {
5332 ALOGV("%s no output for device %s",
5333 __FUNCTION__, sinkDevice->toString().c_str());
5334 return INVALID_OPERATION;
5335 }
5336 outputDesc = mOutputs.valueFor(output);
5337 if (outputDesc->isDuplicated()) {
5338 ALOGE("%s output is duplicated", __func__);
5339 return INVALID_OPERATION;
5340 }
François Gaffie7e39df22022-04-26 12:48:49 +02005341 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5342 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005343 } else {
5344 // Same for "raw patches" aka created from createAudioPatch API
5345 SortedVector<audio_io_handle_t> outputs =
5346 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5347 // if the sink device is reachable via an opened output stream, request to
5348 // go via this output stream by adding a second source to the patch
5349 // description
5350 output = selectOutput(outputs);
5351 if (output == AUDIO_IO_HANDLE_NONE) {
5352 ALOGE("%s no output available for internal patch sink", __func__);
5353 return INVALID_OPERATION;
5354 }
5355 outputDesc = mOutputs.valueFor(output);
5356 if (outputDesc->isDuplicated()) {
5357 ALOGV("%s output for device %s is duplicated",
5358 __func__, sinkDevice->toString().c_str());
5359 return INVALID_OPERATION;
5360 }
François Gaffie7e39df22022-04-26 12:48:49 +02005361 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005362 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005363 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005364 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005365 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005366 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005367 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5368 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005369 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5370 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005371 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005372 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005373 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005374 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005375 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005376 return INVALID_OPERATION;
5377 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005378 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005379 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005380 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005381 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005382 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005383 srcMixPortConfig.ext.mix.usecase.stream =
5384 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005385 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5386 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005387 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005388 }
Eric Laurent83b88082014-06-20 18:31:16 -07005389 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005390 }
5391 // TODO: check from routing capabilities in config file and other conflicting patches
5392
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005393installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005394 status_t status = installPatch(
5395 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005396 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005397 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005398 return INVALID_OPERATION;
5399 }
5400 } else {
5401 return BAD_VALUE;
5402 }
5403 } else {
5404 return BAD_VALUE;
5405 }
5406 return NO_ERROR;
5407}
5408
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005409status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005410{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005411 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005412 ssize_t index = mAudioPatches.indexOfKey(handle);
5413
5414 if (index < 0) {
5415 return BAD_VALUE;
5416 }
5417 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005418 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5419 __func__, mUidCached, patchDesc->getUid(), uid);
5420 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 return INVALID_OPERATION;
5422 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005423 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5424 for (size_t i = 0; i < mAudioSources.size(); i++) {
5425 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5426 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5427 portId = sourceDesc->portId();
5428 break;
5429 }
5430 }
5431 return portId != AUDIO_PORT_HANDLE_NONE ?
5432 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005433}
Eric Laurent6a94d692014-05-20 11:18:06 -07005434
François Gaffieafd4cea2019-11-18 15:50:22 +01005435status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005436 uint32_t delayMs,
5437 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005438{
5439 ALOGV("%s patch %d", __func__, handle);
5440 if (mAudioPatches.indexOfKey(handle) < 0) {
5441 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5442 return BAD_VALUE;
5443 }
5444 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005445 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005446 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005447 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005448 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005449 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005450 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005451 return BAD_VALUE;
5452 }
5453
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305454 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005455 getNewOutputDevices(outputDesc, true /*fromCache*/),
5456 true,
5457 0,
5458 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005459 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5460 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005461 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005462 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005463 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005464 return BAD_VALUE;
5465 }
5466 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005467 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005468 true,
5469 NULL);
5470 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005471 status_t status =
5472 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5473 ALOGV("%s patch panel returned %d patchHandle %d",
5474 __func__, status, patchDesc->getAfHandle());
5475 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005476 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005477 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005478 // SW or HW Bridge
5479 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5480 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005481 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005482 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5483 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5484 outputDesc = sourceDesc->swOutput().promote();
5485 }
5486 if (outputDesc == nullptr) {
5487 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5488 // releaseOutput has already called closeOutput in case of direct output
5489 return NO_ERROR;
5490 }
François Gaffie7e39df22022-04-26 12:48:49 +02005491 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005492 // While using a HwBridge, force reconsidering device only if not reusing an existing
5493 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005494 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005495 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5496 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5497 // Reconsider device only for cases:
5498 // 1 / Active Output
5499 // 2 / Inactive Output previously hosting HwBridge
5500 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5501 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5502 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305503 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005504 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5505 outputDesc->devices(),
5506 force,
5507 0,
5508 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005509 } else {
5510 return BAD_VALUE;
5511 }
5512 } else {
5513 return BAD_VALUE;
5514 }
5515 return NO_ERROR;
5516}
5517
5518status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5519 struct audio_patch *patches,
5520 unsigned int *generation)
5521{
François Gaffie53615e22015-03-19 09:24:12 +01005522 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005523 return BAD_VALUE;
5524 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005526 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005527}
5528
Eric Laurente1715a42014-05-20 11:30:42 -07005529status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005530{
Eric Laurente1715a42014-05-20 11:30:42 -07005531 ALOGV("setAudioPortConfig()");
5532
5533 if (config == NULL) {
5534 return BAD_VALUE;
5535 }
5536 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5537 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005538 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5539 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005540 }
5541
Eric Laurenta121f902014-06-03 13:32:54 -07005542 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005543 if (config->type == AUDIO_PORT_TYPE_MIX) {
5544 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005545 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005546 if (outputDesc == NULL) {
5547 return BAD_VALUE;
5548 }
Eric Laurent84c70242014-06-23 08:46:27 -07005549 ALOG_ASSERT(!outputDesc->isDuplicated(),
5550 "setAudioPortConfig() called on duplicated output %d",
5551 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005552 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005553 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005554 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005555 if (inputDesc == NULL) {
5556 return BAD_VALUE;
5557 }
Eric Laurenta121f902014-06-03 13:32:54 -07005558 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005559 } else {
5560 return BAD_VALUE;
5561 }
5562 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5563 sp<DeviceDescriptor> deviceDesc;
5564 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5565 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5566 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5567 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5568 } else {
5569 return BAD_VALUE;
5570 }
5571 if (deviceDesc == NULL) {
5572 return BAD_VALUE;
5573 }
Eric Laurenta121f902014-06-03 13:32:54 -07005574 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005575 } else {
5576 return BAD_VALUE;
5577 }
5578
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005579 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005580 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5581 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005582 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005583 audioPortConfig->toAudioPortConfig(&newConfig, config);
5584 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005585 }
Eric Laurenta121f902014-06-03 13:32:54 -07005586 if (status != NO_ERROR) {
5587 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005588 }
Eric Laurente1715a42014-05-20 11:30:42 -07005589
5590 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005591}
5592
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005593void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5594{
Eric Laurentd60560a2015-04-10 11:31:20 -07005595 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005596 clearAudioPatches(uid);
5597 clearSessionRoutes(uid);
5598}
5599
Eric Laurent6a94d692014-05-20 11:18:06 -07005600void AudioPolicyManager::clearAudioPatches(uid_t uid)
5601{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005602 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005603 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005604 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005605 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005606 }
5607 }
5608}
5609
François Gaffiec005e562018-11-06 15:04:49 +01005610void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005611{
François Gaffiec005e562018-11-06 15:04:49 +01005612 // Take the first attributes following the product strategy as it is used to retrieve the routed
5613 // device. All attributes wihin a strategy follows the same "routing strategy"
5614 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5615 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005616 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005617 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005618 for (size_t j = 0; j < mOutputs.size(); j++) {
5619 if (mOutputs.keyAt(j) == ouptutToSkip) {
5620 continue;
5621 }
5622 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005623 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005624 continue;
5625 }
5626 // If the default device for this strategy is on another output mix,
5627 // invalidate all tracks in this strategy to force re connection.
5628 // Otherwise select new device on the output mix.
5629 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005630 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005631 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005632 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005633 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005634 // If the device is using preferred mixer attributes, the output need to reopen
5635 // with default configuration when the new selected devices are different from
5636 // current routing devices.
5637 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5638 continue;
5639 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305640 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005641 }
5642 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005643 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005644}
5645
5646void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5647{
5648 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005649 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005650 for (size_t i = 0; i < mOutputs.size(); i++) {
5651 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005652 for (const auto& client : outputDesc->getClientIterable()) {
5653 if (client->hasPreferredDevice() && client->uid() == uid) {
5654 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005655 auto clientStrategy = client->strategy();
5656 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5657 end(affectedStrategies)) {
5658 continue;
5659 }
5660 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005661 }
5662 }
5663 }
5664 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005665 for (const auto& strategy : affectedStrategies) {
5666 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005667 }
5668
5669 // remove input routes associated with this uid
5670 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005671 for (size_t i = 0; i < mInputs.size(); i++) {
5672 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005673 for (const auto& client : inputDesc->getClientIterable()) {
5674 if (client->hasPreferredDevice() && client->uid() == uid) {
5675 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5676 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005677 }
5678 }
5679 }
5680 // reroute inputs if necessary
5681 SortedVector<audio_io_handle_t> inputsToClose;
5682 for (size_t i = 0; i < mInputs.size(); i++) {
5683 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005684 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005685 inputsToClose.add(inputDesc->mIoHandle);
5686 }
5687 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005688 for (const auto& input : inputsToClose) {
5689 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005690 }
5691}
5692
Eric Laurentd60560a2015-04-10 11:31:20 -07005693void AudioPolicyManager::clearAudioSources(uid_t uid)
5694{
5695 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005696 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5697 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005698 stopAudioSource(mAudioSources.keyAt(i));
5699 }
5700 }
5701}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005702
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005703status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5704 audio_io_handle_t *ioHandle,
5705 audio_devices_t *device)
5706{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005707 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5708 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005709 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005710 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5711 if (deviceDesc == nullptr) {
5712 return INVALID_OPERATION;
5713 }
5714 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005715
François Gaffiedf372692015-03-19 10:43:27 +01005716 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005717}
5718
Eric Laurentd60560a2015-04-10 11:31:20 -07005719status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005720 const audio_attributes_t *attributes,
5721 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005722 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005723{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005724 ALOGV("%s", __FUNCTION__);
5725 *portId = AUDIO_PORT_HANDLE_NONE;
5726
5727 if (source == NULL || attributes == NULL || portId == NULL) {
5728 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5729 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005730 return BAD_VALUE;
5731 }
5732
Eric Laurentd60560a2015-04-10 11:31:20 -07005733 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5734 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005735 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5736 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005737 return INVALID_OPERATION;
5738 }
5739
François Gaffie11d30102018-11-02 16:09:09 +01005740 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005741 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005742 String8(source->ext.device.address),
5743 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005744 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005745 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005746 return BAD_VALUE;
5747 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005748
jiabin4ef93452019-09-10 14:29:54 -07005749 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005750
François Gaffieaaac0fd2018-11-22 17:56:39 +01005751 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005752 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005753 mEngine->getStreamTypeForAttributes(*attributes),
5754 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005755 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005756
5757 status_t status = connectAudioSource(sourceDesc);
5758 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005759 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005760 }
5761 return status;
5762}
5763
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005764status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005765{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005766 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005767
5768 // make sure we only have one patch per source.
5769 disconnectAudioSource(sourceDesc);
5770
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005771 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005772 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5773 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5774 sourceDesc->srcDevice()->type(),
5775 String8(sourceDesc->srcDevice()->address().c_str()),
5776 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005777 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005778 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005779 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005780 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005781 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5782 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5783 return INVALID_OPERATION;
5784 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005785 PatchBuilder patchBuilder;
5786 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5787 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005788
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005789 return connectAudioSourceToSink(
5790 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005791}
5792
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005793status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005794{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005795 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5796 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005797 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005798 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005799 return BAD_VALUE;
5800 }
5801 status_t status = disconnectAudioSource(sourceDesc);
5802
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005803 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005804 return status;
5805}
5806
Andy Hung2ddee192015-12-18 17:34:44 -08005807status_t AudioPolicyManager::setMasterMono(bool mono)
5808{
5809 if (mMasterMono == mono) {
5810 return NO_ERROR;
5811 }
5812 mMasterMono = mono;
5813 // if enabling mono we close all offloaded devices, which will invalidate the
5814 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5815 // for recreating the new AudioTrack as non-offloaded PCM.
5816 //
5817 // If disabling mono, we leave all tracks as is: we don't know which clients
5818 // and tracks are able to be recreated as offloaded. The next "song" should
5819 // play back offloaded.
5820 if (mMasterMono) {
5821 Vector<audio_io_handle_t> offloaded;
5822 for (size_t i = 0; i < mOutputs.size(); ++i) {
5823 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5824 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5825 offloaded.push(desc->mIoHandle);
5826 }
5827 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005828 for (const auto& handle : offloaded) {
5829 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005830 }
5831 }
5832 // update master mono for all remaining outputs
5833 for (size_t i = 0; i < mOutputs.size(); ++i) {
5834 updateMono(mOutputs.keyAt(i));
5835 }
5836 return NO_ERROR;
5837}
5838
5839status_t AudioPolicyManager::getMasterMono(bool *mono)
5840{
5841 *mono = mMasterMono;
5842 return NO_ERROR;
5843}
5844
Eric Laurentac9cef52017-06-09 15:46:26 -07005845float AudioPolicyManager::getStreamVolumeDB(
5846 audio_stream_type_t stream, int index, audio_devices_t device)
5847{
jiabin9a3361e2019-10-01 09:38:30 -07005848 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005849}
5850
jiabin81772902018-04-02 17:52:27 -07005851status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5852 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005853 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005854{
Kriti Dang6537def2021-03-02 13:46:59 +01005855 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5856 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005857 return BAD_VALUE;
5858 }
Kriti Dang6537def2021-03-02 13:46:59 +01005859 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5860 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005861
5862 size_t formatsWritten = 0;
5863 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005864
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005865 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005866 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5867 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005868 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005869 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005870 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005871 bool formatEnabled = true;
5872 switch (forceUse) {
5873 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005874 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005875 break;
5876 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5877 formatEnabled = false;
5878 break;
5879 default: // AUTO or ALWAYS => true
5880 break;
jiabin81772902018-04-02 17:52:27 -07005881 }
5882 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5883 }
jiabin81772902018-04-02 17:52:27 -07005884 }
5885 return NO_ERROR;
5886}
5887
Kriti Dang6537def2021-03-02 13:46:59 +01005888status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5889 audio_format_t *surroundFormats) {
5890 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5891 return BAD_VALUE;
5892 }
5893 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5894 __func__, *numSurroundFormats, surroundFormats);
5895
5896 size_t formatsWritten = 0;
5897 size_t formatsMax = *numSurroundFormats;
5898 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5899
5900 // Return formats from all device profiles that have already been resolved by
5901 // checkOutputsForDevice().
5902 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5903 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5904 audio_devices_t deviceType = device->type();
5905 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5906 // returns formats reported by HDMI devices.
5907 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5908 continue;
5909 }
5910 // Formats reported by sink devices
5911 std::unordered_set<audio_format_t> formatset;
5912 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5913 formatset.insert(it->second.begin(), it->second.end());
5914 }
5915
5916 // Formats hard-coded in the in policy configuration file (if any).
5917 FormatVector encodedFormats = device->encodedFormats();
5918 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5919 // Filter the formats which are supported by the vendor hardware.
5920 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005921 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005922 formats.insert(*it);
5923 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005924 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005925 if (pair.second.count(*it) != 0) {
5926 formats.insert(pair.first);
5927 break;
5928 }
5929 }
5930 }
5931 }
5932 }
5933 *numSurroundFormats = formats.size();
5934 for (const auto& format: formats) {
5935 if (formatsWritten < formatsMax) {
5936 surroundFormats[formatsWritten++] = format;
5937 }
5938 }
5939 return NO_ERROR;
5940}
5941
jiabin81772902018-04-02 17:52:27 -07005942status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5943{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005944 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005945 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5946 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005947 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005948 return BAD_VALUE;
5949 }
5950
Mikhail Naganov100f0122018-11-29 11:22:16 -08005951 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5952 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005953 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005954 return INVALID_OPERATION;
5955 }
5956
Mikhail Naganov100f0122018-11-29 11:22:16 -08005957 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005958 return NO_ERROR;
5959 }
5960
Mikhail Naganov100f0122018-11-29 11:22:16 -08005961 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005962 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005963 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005964 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005965 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005966 }
5967 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005968 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005969 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005970 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005971 }
5972 }
5973
5974 sp<SwAudioOutputDescriptor> outputDesc;
5975 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005976 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5977 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005978 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5979 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005980 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005981 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005982 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5983 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5984 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005985 name.c_str(),
5986 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005987 if (status != NO_ERROR) {
5988 continue;
5989 }
5990 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5991 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5992 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005993 name.c_str(),
5994 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005995 profileUpdated |= (status == NO_ERROR);
5996 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005997 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005998 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005999 AUDIO_DEVICE_IN_HDMI);
6000 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6001 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006002 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006003 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006004 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6005 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6006 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006007 name.c_str(),
6008 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006009 if (status != NO_ERROR) {
6010 continue;
6011 }
6012 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6013 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6014 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006015 name.c_str(),
6016 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006017 profileUpdated |= (status == NO_ERROR);
6018 }
6019
jiabin81772902018-04-02 17:52:27 -07006020 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006021 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006022 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006023 }
6024
6025 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6026}
6027
Eric Laurent5ada82e2019-08-29 17:53:54 -07006028void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006029{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006030 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006031 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006032 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006033 }
6034}
6035
jiabin6012f912018-11-02 17:06:30 -07006036bool AudioPolicyManager::isHapticPlaybackSupported()
6037{
6038 for (const auto& hwModule : mHwModules) {
6039 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6040 for (const auto &outProfile : outputProfiles) {
6041 struct audio_port audioPort;
6042 outProfile->toAudioPort(&audioPort);
6043 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6044 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6045 return true;
6046 }
6047 }
6048 }
6049 }
6050 return false;
6051}
6052
Carter Hsu325a8eb2022-01-19 19:56:51 +08006053bool AudioPolicyManager::isUltrasoundSupported()
6054{
6055 bool hasUltrasoundOutput = false;
6056 bool hasUltrasoundInput = false;
6057 for (const auto& hwModule : mHwModules) {
6058 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6059 if (!hasUltrasoundOutput) {
6060 for (const auto &outProfile : outputProfiles) {
6061 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6062 hasUltrasoundOutput = true;
6063 break;
6064 }
6065 }
6066 }
6067
6068 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6069 if (!hasUltrasoundInput) {
6070 for (const auto &inputProfile : inputProfiles) {
6071 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6072 hasUltrasoundInput = true;
6073 break;
6074 }
6075 }
6076 }
6077
6078 if (hasUltrasoundOutput && hasUltrasoundInput)
6079 return true;
6080 }
6081 return false;
6082}
6083
Atneya Nair698f5ef2022-12-15 16:15:09 -08006084bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6085{
6086 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6087 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6088 for (const auto& hwModule : mHwModules) {
6089 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6090 for (const auto &inputProfile : inputProfiles) {
6091 if ((inputProfile->getFlags() & mask) == mask) {
6092 return true;
6093 }
6094 }
6095 }
6096 return false;
6097}
6098
Eric Laurent8340e672019-11-06 11:01:08 -08006099bool AudioPolicyManager::isCallScreenModeSupported()
6100{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006101 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006102}
6103
6104
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006105status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006106{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006107 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006108 if (!sourceDesc->isConnected()) {
6109 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6110 return NO_ERROR;
6111 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006112 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6113 if (swOutput != 0) {
6114 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006115 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006116 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006117 }
jiabinbce0c1d2020-10-05 11:20:18 -07006118 if (releaseOutput(sourceDesc->portId())) {
6119 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6120 // no need to release audio patch here but just return NO_ERROR.
6121 return NO_ERROR;
6122 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006123 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006124 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006125 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006126 // close Hwoutput and remove from mHwOutputs
6127 } else {
6128 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6129 }
6130 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006131 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006132 sourceDesc->disconnect();
6133 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006134}
6135
François Gaffiec005e562018-11-06 15:04:49 +01006136sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6137 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006138{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006139 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006140 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006141 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006142 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006143 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6144 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006145 source = sourceDesc;
6146 break;
6147 }
6148 }
6149 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006150}
6151
Eric Laurentb4f42a92022-01-17 17:37:31 +01006152bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006153 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006154 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006155{
6156 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6157 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006158 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006159 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006160 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6161 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6162 return false;
6163 }
6164 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6165 return false;
6166 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006167 }
6168
Eric Laurentd332bc82023-08-04 11:45:23 +02006169 // The caller can have the audio config criteria ignored by either passing a null ptr or
6170 // the AUDIO_CONFIG_INITIALIZER value.
6171 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006172 // some positional channel masks and PCM format and for stereo if low latency performance
6173 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006174
6175 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006176 static const bool stereo_spatialization_enabled =
6177 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006178 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006179 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006180 ? audio_channel_mask_contains_stereo(config->channel_mask)
6181 : audio_is_channel_mask_spatialized(config->channel_mask);
6182 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006183 return false;
6184 }
6185 if (!audio_is_linear_pcm(config->format)) {
6186 return false;
6187 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006188 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6189 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6190 return false;
6191 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006192 }
6193
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006194 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006195 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006196 if (profile == nullptr) {
6197 return false;
6198 }
6199
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006200 return true;
6201}
6202
Shunkai Yao4c3af932024-04-26 04:12:21 +00006203// The Spatializer output is compatible with Haptic use cases if:
6204// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6205// with client if client haptic channel bits were set, or
6206// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6207// including the haptic bits or creating the HapticGenerator effect for same session.
6208bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6209 const audio_config_t* config, audio_session_t sessionId) const {
6210 const auto clientHapticChannel =
6211 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6212 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6213 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6214
6215 if (threadOutputHapticChannel) {
6216 // check format and sampleRate match if client haptic channel mask exist
6217 if (clientHapticChannel) {
6218 return mSpatializerOutput->getFormat() == config->format &&
6219 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6220 }
6221 return true;
6222 } else {
6223 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6224 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6225 // HapticGenerator effect for this session) are not supported.
6226 return clientHapticChannel == 0 &&
6227 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6228 }
6229}
6230
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006231void AudioPolicyManager::checkVirtualizerClientRoutes() {
6232 std::set<audio_stream_type_t> streamsToInvalidate;
6233 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006234 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6235 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006236 audio_attributes_t attr = client->attributes();
6237 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6238 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6239 audio_config_base_t clientConfig = client->config();
6240 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006241 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006242 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006243 streamsToInvalidate.insert(client->stream());
6244 }
6245 }
6246 }
6247
jiabinc44b3462022-12-08 12:52:31 -08006248 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006249}
6250
Eric Laurente191d1b2022-04-15 11:59:25 +02006251
6252bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6253 const sp<SwAudioOutputDescriptor>& outputDesc) {
6254 if (outputDesc->isDuplicated()) {
6255 return false;
6256 }
6257 DeviceVector devices = outputDesc->supportedDevices();
6258 for (size_t i = 0; i < mOutputs.size(); i++) {
6259 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6260 if (desc == outputDesc || desc->isDuplicated()) {
6261 continue;
6262 }
6263 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6264 if (!sharedDevices.isEmpty()
6265 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6266 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6267 return false;
6268 }
6269 }
6270 return true;
6271}
6272
6273
Eric Laurentfa0f6742021-08-17 18:39:44 +02006274status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006275 const audio_attributes_t *attr,
6276 audio_io_handle_t *output) {
6277 *output = AUDIO_IO_HANDLE_NONE;
6278
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006279 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6280 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6281 audio_config_t *configPtr = nullptr;
6282 audio_config_t config;
6283 if (mixerConfig != nullptr) {
6284 config = audio_config_initializer(mixerConfig);
6285 configPtr = &config;
6286 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006287 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006288 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006289 return BAD_VALUE;
6290 }
6291
6292 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006293 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006294 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006295 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006296 return BAD_VALUE;
6297 }
6298
Eric Laurente191d1b2022-04-15 11:59:25 +02006299 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006300 for (size_t i = 0; i < mOutputs.size(); i++) {
6301 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006302 if (!desc->isDuplicated()
6303 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6304 spatializerOutputs.push_back(desc);
6305 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006306 }
6307 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006308 mSpatializerOutput.clear();
6309 bool outputsChanged = false;
6310 for (const auto& desc : spatializerOutputs) {
6311 if (desc->mProfile == profile
6312 && (configPtr == nullptr
6313 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6314 mSpatializerOutput = desc;
6315 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6316 } else {
6317 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6318 " and devices %s", __func__, desc->mIoHandle,
6319 configPtr != nullptr ? configPtr->channel_mask : 0,
6320 devices.toString().c_str());
6321 closeOutput(desc->mIoHandle);
6322 outputsChanged = true;
6323 }
Eric Laurent39095982021-08-24 18:29:27 +02006324 }
6325
Eric Laurente191d1b2022-04-15 11:59:25 +02006326 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006327 sp<SwAudioOutputDescriptor> desc =
6328 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006329 if (desc != nullptr) {
6330 mSpatializerOutput = desc;
6331 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006332 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006333 }
6334
6335 checkVirtualizerClientRoutes();
6336
Eric Laurente191d1b2022-04-15 11:59:25 +02006337 if (outputsChanged) {
6338 mPreviousOutputs = mOutputs;
6339 mpClientInterface->onAudioPortListUpdate();
6340 }
6341
6342 if (mSpatializerOutput == nullptr) {
6343 ALOGV("%s could not open spatializer output with requested config", __func__);
6344 return BAD_VALUE;
6345 }
Eric Laurent39095982021-08-24 18:29:27 +02006346 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006347 ALOGV("%s returning new spatializer output %d", __func__, *output);
6348 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006349}
6350
Eric Laurentfa0f6742021-08-17 18:39:44 +02006351status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6352 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006353 return INVALID_OPERATION;
6354 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006355 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006356 return BAD_VALUE;
6357 }
Eric Laurent39095982021-08-24 18:29:27 +02006358
Eric Laurente191d1b2022-04-15 11:59:25 +02006359 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6360 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6361 closeOutput(mSpatializerOutput->mIoHandle);
6362 //from now on mSpatializerOutput is null
6363 checkVirtualizerClientRoutes();
6364 }
Eric Laurent39095982021-08-24 18:29:27 +02006365
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006366 return NO_ERROR;
6367}
6368
Eric Laurente552edb2014-03-10 17:42:56 -07006369// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006370// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006371// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006372uint32_t AudioPolicyManager::nextAudioPortGeneration()
6373{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006374 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006375}
6376
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006377AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006378 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006379 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006380 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006381 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006382 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006383 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006384 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006385 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006386 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006387 mAudioPortGeneration(1),
6388 mBeaconMuteRefCount(0),
6389 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006390 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006391 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006392 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006393 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006394{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006395}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006396
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006397status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006398 if (mEngine == nullptr) {
6399 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006400 }
6401 mEngine->setObserver(this);
6402 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006403 if (status != NO_ERROR) {
6404 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6405 return status;
6406 }
François Gaffie2110e042015-03-24 08:41:51 +01006407
jiabin29230182023-04-04 21:02:36 +00006408 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6409 // at the end of this function.
6410 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006411 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6412 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6413
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006414 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006415 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006416 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006417
Eric Laurent3a4311c2014-03-17 12:00:47 -07006418 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006419 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6420 defaultOutputDevice == nullptr ||
6421 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6422 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6423 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006424 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006425 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006426 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006427
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006428 // Silence ALOGV statements
6429 property_set("log.tag." LOG_TAG, "D");
6430
Eric Laurente552edb2014-03-10 17:42:56 -07006431 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006432 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006433}
6434
Eric Laurente0720872014-03-11 09:30:41 -07006435AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006436{
Eric Laurente552edb2014-03-10 17:42:56 -07006437 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006438 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006439 }
6440 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006441 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006442 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006443 mAvailableOutputDevices.clear();
6444 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006445 mOutputs.clear();
6446 mInputs.clear();
6447 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006448 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006449 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006450}
6451
Eric Laurente0720872014-03-11 09:30:41 -07006452status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006453{
Eric Laurent87ffa392015-05-22 10:32:38 -07006454 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006455}
6456
Eric Laurente552edb2014-03-10 17:42:56 -07006457// ---
6458
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006459void AudioPolicyManager::onNewAudioModulesAvailable()
6460{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006461 DeviceVector newDevices;
6462 onNewAudioModulesAvailableInt(&newDevices);
6463 if (!newDevices.empty()) {
6464 nextAudioPortGeneration();
6465 mpClientInterface->onAudioPortListUpdate();
6466 }
6467}
6468
6469void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6470{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006471 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006472 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6473 continue;
6474 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006475 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006476 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6477 handle != AUDIO_MODULE_HANDLE_NONE) {
6478 hwModule->setHandle(handle);
6479 } else {
6480 ALOGW("could not load HW module %s", hwModule->getName());
6481 continue;
6482 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006483 }
6484 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006485 // open all output streams needed to access attached devices.
6486 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006487 // This also validates mAvailableOutputDevices list
6488 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6489 if (!outProfile->canOpenNewIo()) {
6490 ALOGE("Invalid Output profile max open count %u for profile %s",
6491 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6492 continue;
6493 }
6494 if (!outProfile->hasSupportedDevices()) {
6495 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6496 continue;
6497 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006498 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6499 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006500 mTtsOutputAvailable = true;
6501 }
6502
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006503 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006504 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006505 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006506 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6507 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006508 } else {
6509 // choose first device present in profile's SupportedDevices also part of
6510 // mAvailableOutputDevices.
6511 if (availProfileDevices.isEmpty()) {
6512 continue;
6513 }
6514 supportedDevice = availProfileDevices.itemAt(0);
6515 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006516 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006517 continue;
6518 }
6519 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6520 mpClientInterface);
6521 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006522 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6523 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006524 AUDIO_STREAM_DEFAULT,
6525 AUDIO_OUTPUT_FLAG_NONE, &output);
6526 if (status != NO_ERROR) {
6527 ALOGW("Cannot open output stream for devices %s on hw module %s",
6528 supportedDevice->toString().c_str(), hwModule->getName());
6529 continue;
6530 }
6531 for (const auto &device : availProfileDevices) {
6532 // give a valid ID to an attached device once confirmed it is reachable
6533 if (!device->isAttached()) {
6534 device->attach(hwModule);
6535 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006536 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006537 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006538 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6539 }
6540 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006541 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006542 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6543 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006544 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006545 }
Eric Laurent39095982021-08-24 18:29:27 +02006546 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006547 outputDesc->close();
6548 } else {
6549 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306550 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006551 DeviceVector(supportedDevice),
6552 true,
6553 0,
6554 NULL);
6555 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006556 }
6557 // open input streams needed to access attached devices to validate
6558 // mAvailableInputDevices list
6559 for (const auto& inProfile : hwModule->getInputProfiles()) {
6560 if (!inProfile->canOpenNewIo()) {
6561 ALOGE("Invalid Input profile max open count %u for profile %s",
6562 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6563 continue;
6564 }
6565 if (!inProfile->hasSupportedDevices()) {
6566 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6567 continue;
6568 }
6569 // chose first device present in profile's SupportedDevices also part of
6570 // available input devices
6571 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006572 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006573 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006574 ALOGV("%s: Input device list is empty! for profile %s",
6575 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006576 continue;
6577 }
6578 sp<AudioInputDescriptor> inputDesc =
6579 new AudioInputDescriptor(inProfile, mpClientInterface);
6580
6581 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6582 status_t status = inputDesc->open(nullptr,
6583 availProfileDevices.itemAt(0),
6584 AUDIO_SOURCE_MIC,
6585 AUDIO_INPUT_FLAG_NONE,
6586 &input);
6587 if (status != NO_ERROR) {
6588 ALOGW("Cannot open input stream for device %s on hw module %s",
6589 availProfileDevices.toString().c_str(),
6590 hwModule->getName());
6591 continue;
6592 }
6593 for (const auto &device : availProfileDevices) {
6594 // give a valid ID to an attached device once confirmed it is reachable
6595 if (!device->isAttached()) {
6596 device->attach(hwModule);
6597 device->importAudioPortAndPickAudioProfile(inProfile, true);
6598 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006599 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006600 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6601 }
6602 }
6603 inputDesc->close();
6604 }
6605 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006606
6607 // Check if spatializer outputs can be closed until used.
6608 // mOutputs vector never contains duplicated outputs at this point.
6609 std::vector<audio_io_handle_t> outputsClosed;
6610 for (size_t i = 0; i < mOutputs.size(); i++) {
6611 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6612 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6613 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6614 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006615 nextAudioPortGeneration();
6616 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6617 if (index >= 0) {
6618 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6619 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6620 patchDesc->getAfHandle(), 0);
6621 mAudioPatches.removeItemsAt(index);
6622 mpClientInterface->onAudioPatchListUpdate();
6623 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006624 desc->close();
6625 }
6626 }
6627 for (auto output : outputsClosed) {
6628 removeOutput(output);
6629 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006630}
6631
Eric Laurent98e38192018-02-15 18:31:53 -08006632void AudioPolicyManager::addOutput(audio_io_handle_t output,
6633 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006634{
Eric Laurent1c333e22014-05-20 10:48:17 -07006635 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006636 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006637 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006638 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006639 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006640}
6641
François Gaffie53615e22015-03-19 09:24:12 +01006642void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6643{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006644 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6645 ALOGV("%s: removing primary output", __func__);
6646 mPrimaryOutput = nullptr;
6647 }
François Gaffie53615e22015-03-19 09:24:12 +01006648 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006649 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006650}
6651
Eric Laurent98e38192018-02-15 18:31:53 -08006652void AudioPolicyManager::addInput(audio_io_handle_t input,
6653 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006654{
Eric Laurent1c333e22014-05-20 10:48:17 -07006655 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006656 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006657}
Eric Laurente552edb2014-03-10 17:42:56 -07006658
François Gaffie11d30102018-11-02 16:09:09 +01006659status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006660 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006661 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006662{
François Gaffie11d30102018-11-02 16:09:09 +01006663 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006664 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006665 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006666
François Gaffie11d30102018-11-02 16:09:09 +01006667 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006668 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006669 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006670 }
Eric Laurente552edb2014-03-10 17:42:56 -07006671
Eric Laurent3b73df72014-03-11 09:06:29 -07006672 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006673 // first call getAudioPort to get the supported attributes from the HAL
6674 struct audio_port_v7 port = {};
6675 device->toAudioPort(&port);
6676 status_t status = mpClientInterface->getAudioPort(&port);
6677 if (status == NO_ERROR) {
6678 device->importAudioPort(port);
6679 }
6680
6681 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006682 for (size_t i = 0; i < mOutputs.size(); i++) {
6683 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006684 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006685 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006686 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6687 mOutputs.keyAt(i), device->toString().c_str());
6688 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006689 }
6690 }
6691 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006692 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006693 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006694 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6695 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006696 if (profile->supportsDevice(device)) {
6697 profiles.add(profile);
6698 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6699 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006700 }
6701 }
6702 }
6703
Eric Laurent7b279bb2015-12-14 10:18:23 -08006704 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006705
Eric Laurente552edb2014-03-10 17:42:56 -07006706 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006707 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006708 return BAD_VALUE;
6709 }
6710
6711 // open outputs for matching profiles if needed. Direct outputs are also opened to
6712 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6713 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006714 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006715
6716 // nothing to do if one output is already opened for this profile
6717 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006718 for (j = 0; j < outputs.size(); j++) {
6719 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006720 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006721 // matching profile: save the sample rates, format and channel masks supported
6722 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006723 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006724 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006725 }
Eric Laurente552edb2014-03-10 17:42:56 -07006726 break;
6727 }
6728 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006729 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006730 continue;
6731 }
6732
Eric Laurent3974e3b2017-12-07 17:58:43 -08006733 if (!profile->canOpenNewIo()) {
6734 ALOGW("Max Output number %u already opened for this profile %s",
6735 profile->maxOpenCount, profile->getTagName().c_str());
6736 continue;
6737 }
6738
Eric Laurent83efe1c2017-07-09 16:51:08 -07006739 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006740 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006741 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6742 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006743 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006744 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006745 profiles.removeAt(profile_index);
6746 profile_index--;
6747 } else {
6748 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006749 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006750 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006751 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6752 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006753 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006754 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006755
François Gaffie11d30102018-11-02 16:09:09 +01006756 if (device_distinguishes_on_address(deviceType)) {
6757 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6758 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306759 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6760 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006761 }
Eric Laurente552edb2014-03-10 17:42:56 -07006762 ALOGV("checkOutputsForDevice(): adding output %d", output);
6763 }
6764 }
6765
6766 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006767 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006768 return BAD_VALUE;
6769 }
Eric Laurentd4692962014-05-05 18:13:44 -07006770 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006771 // check if one opened output is not needed any more after disconnecting one device
6772 for (size_t i = 0; i < mOutputs.size(); i++) {
6773 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006774 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006775 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006776 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006777 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006778 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006779 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006780 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6781 mOutputs.keyAt(i));
6782 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006783 }
Eric Laurente552edb2014-03-10 17:42:56 -07006784 }
6785 }
Eric Laurentd4692962014-05-05 18:13:44 -07006786 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006787 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006788 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6789 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006790 if (!profile->supportsDevice(device)) {
6791 continue;
6792 }
6793 ALOGV("checkOutputsForDevice(): "
6794 "clearing direct output profile %zu on module %s",
6795 j, hwModule->getName());
6796 profile->clearAudioProfiles();
6797 if (!profile->hasDynamicAudioProfile()) {
6798 continue;
6799 }
6800 // When a device is disconnected, if there is an IOProfile that contains dynamic
6801 // profiles and supports the disconnected device, call getAudioPort to repopulate
6802 // the capabilities of the devices that is supported by the IOProfile.
6803 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6804 if (supportedDevice == device ||
6805 !mAvailableOutputDevices.contains(supportedDevice)) {
6806 continue;
6807 }
6808 struct audio_port_v7 port;
6809 supportedDevice->toAudioPort(&port);
6810 status_t status = mpClientInterface->getAudioPort(&port);
6811 if (status == NO_ERROR) {
6812 supportedDevice->importAudioPort(port);
6813 }
Eric Laurente552edb2014-03-10 17:42:56 -07006814 }
6815 }
6816 }
6817 }
6818 return NO_ERROR;
6819}
6820
François Gaffie11d30102018-11-02 16:09:09 +01006821status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006822 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006823{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006824 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006825
François Gaffie11d30102018-11-02 16:09:09 +01006826 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006827 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006828 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006829 }
6830
Eric Laurentd4692962014-05-05 18:13:44 -07006831 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006832 // first call getAudioPort to get the supported attributes from the HAL
6833 struct audio_port_v7 port = {};
6834 device->toAudioPort(&port);
6835 status_t status = mpClientInterface->getAudioPort(&port);
6836 if (status == NO_ERROR) {
6837 device->importAudioPort(port);
6838 }
6839
Eric Laurent0dd51852019-04-19 18:18:58 -07006840 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006841 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006842 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006843 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006844 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006845 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006846 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006847
François Gaffie11d30102018-11-02 16:09:09 +01006848 if (profile->supportsDevice(device)) {
6849 profiles.add(profile);
6850 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6851 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006852 }
6853 }
6854 }
6855
Eric Laurent0dd51852019-04-19 18:18:58 -07006856 if (profiles.isEmpty()) {
6857 ALOGW("%s: No input profile available for device %s",
6858 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006859 return BAD_VALUE;
6860 }
6861
6862 // open inputs for matching profiles if needed. Direct inputs are also opened to
6863 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6864 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6865
Eric Laurent1c333e22014-05-20 10:48:17 -07006866 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006867
Eric Laurentd4692962014-05-05 18:13:44 -07006868 // nothing to do if one input is already opened for this profile
6869 size_t input_index;
6870 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6871 desc = mInputs.valueAt(input_index);
6872 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006873 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006874 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006875 }
Eric Laurentd4692962014-05-05 18:13:44 -07006876 break;
6877 }
6878 }
6879 if (input_index != mInputs.size()) {
6880 continue;
6881 }
6882
Eric Laurent3974e3b2017-12-07 17:58:43 -08006883 if (!profile->canOpenNewIo()) {
6884 ALOGW("Max Input number %u already opened for this profile %s",
6885 profile->maxOpenCount, profile->getTagName().c_str());
6886 continue;
6887 }
6888
Eric Laurentfe231122017-11-17 17:48:06 -08006889 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006890 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006891 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006892
Eric Laurentcf2c0212014-07-25 16:20:43 -07006893 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006894 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006895 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006896 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006897 mpClientInterface->setParameters(input, String8(param));
6898 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006899 }
jiabin12537fc2023-10-12 17:56:08 +00006900 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006901 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006902 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006903 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006904 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006905 }
6906
Eric Laurent0dd51852019-04-19 18:18:58 -07006907 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006908 addInput(input, desc);
6909 }
6910 } // endif input != 0
6911
Eric Laurentcf2c0212014-07-25 16:20:43 -07006912 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006913 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006914 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006915 profiles.removeAt(profile_index);
6916 profile_index--;
6917 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006918 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006919 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006920 }
Eric Laurentd4692962014-05-05 18:13:44 -07006921 ALOGV("checkInputsForDevice(): adding input %d", input);
6922 }
6923 } // end scan profiles
6924
6925 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006926 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006927 return BAD_VALUE;
6928 }
6929 } else {
6930 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006931 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006932 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006933 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006934 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006935 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006936 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006937 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006938 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6939 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006940 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006941 }
6942 }
6943 }
6944 } // end disconnect
6945
6946 return NO_ERROR;
6947}
6948
6949
Eric Laurente0720872014-03-11 09:30:41 -07006950void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006951{
6952 ALOGV("closeOutput(%d)", output);
6953
François Gaffie1c878552018-11-22 16:53:21 +01006954 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6955 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006956 ALOGW("closeOutput() unknown output %d", output);
6957 return;
6958 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006959 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006960 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006961
Eric Laurente552edb2014-03-10 17:42:56 -07006962 // look for duplicated outputs connected to the output being removed.
6963 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006964 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6965 if (dupOutput->isDuplicated() &&
6966 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6967 sp<SwAudioOutputDescriptor> remainingOutput =
6968 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006969 // As all active tracks on duplicated output will be deleted,
6970 // and as they were also referenced on the other output, the reference
6971 // count for their stream type must be adjusted accordingly on
6972 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006973 const bool wasActive = remainingOutput->isActive();
6974 // Note: no-op on the closing output where all clients has already been set inactive
6975 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006976 // stop() will be a no op if the output is still active but is needed in case all
6977 // active streams refcounts where cleared above
6978 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006979 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006980 }
Eric Laurente552edb2014-03-10 17:42:56 -07006981 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6982 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6983
6984 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006985 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006986 }
6987 }
6988
Eric Laurent05b90f82014-08-27 15:32:29 -07006989 nextAudioPortGeneration();
6990
François Gaffie1c878552018-11-22 16:53:21 +01006991 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006992 if (index >= 0) {
6993 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006994 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6995 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006996 mAudioPatches.removeItemsAt(index);
6997 mpClientInterface->onAudioPatchListUpdate();
6998 }
6999
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007000 if (closingOutputWasActive) {
7001 closingOutput->stop();
7002 }
François Gaffie1c878552018-11-22 16:53:21 +01007003 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007004 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007005 for (const auto device : closingOutput->devices()) {
7006 device->setPreferredConfig(nullptr);
7007 }
7008 }
Eric Laurente552edb2014-03-10 17:42:56 -07007009
François Gaffie53615e22015-03-19 09:24:12 +01007010 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007011 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007012 if (closingOutput == mSpatializerOutput) {
7013 mSpatializerOutput.clear();
7014 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007015
7016 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7017 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007018 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007019 bool directOutputOpen = false;
7020 for (size_t i = 0; i < mOutputs.size(); i++) {
7021 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7022 directOutputOpen = true;
7023 break;
7024 }
7025 }
7026 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007027 ALOGV("no direct outputs open, reset MSD patches");
7028 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7029 // how output devices for patching are resolved. Avoid by caching and reusing the
7030 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7031 // devices to patch to. This may be complicated by the fact that devices may become
7032 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007033 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007034 }
7035 }
jiabin220eea12024-05-17 17:55:20 +00007036
7037 if (closingOutput->mPreferredAttrInfo != nullptr) {
7038 closingOutput->mPreferredAttrInfo->resetActiveClient();
7039 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007040}
7041
7042void AudioPolicyManager::closeInput(audio_io_handle_t input)
7043{
7044 ALOGV("closeInput(%d)", input);
7045
7046 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7047 if (inputDesc == NULL) {
7048 ALOGW("closeInput() unknown input %d", input);
7049 return;
7050 }
7051
Eric Laurent6a94d692014-05-20 11:18:06 -07007052 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007053
François Gaffie11d30102018-11-02 16:09:09 +01007054 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007055 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007056 if (index >= 0) {
7057 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007058 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7059 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007060 mAudioPatches.removeItemsAt(index);
7061 mpClientInterface->onAudioPatchListUpdate();
7062 }
7063
François Gaffie6ebbce02023-07-19 13:27:53 +02007064 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007065 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007066 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007067
François Gaffie11d30102018-11-02 16:09:09 +01007068 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7069 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007070 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007071 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007072 }
Eric Laurente552edb2014-03-10 17:42:56 -07007073}
7074
François Gaffie11d30102018-11-02 16:09:09 +01007075SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7076 const DeviceVector &devices,
7077 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007078{
7079 SortedVector<audio_io_handle_t> outputs;
7080
François Gaffie11d30102018-11-02 16:09:09 +01007081 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007082 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007083 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007084 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007085 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007086 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007087 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007088 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007089 outputs.add(openOutputs.keyAt(i));
7090 }
7091 }
7092 return outputs;
7093}
7094
Mikhail Naganov37977152018-07-11 15:54:44 -07007095void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7096{
7097 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7098 // output is suspended before any tracks are moved to it
7099 checkA2dpSuspend();
7100 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007101 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007102 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007103 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007104 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007105 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7106 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7107 // configuration changes will ultimately be rerouted correctly. We can still avoid
7108 // unnecessary rerouting by caching and reusing the arguments to
7109 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7110 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007111 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007112 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007113 // an event that changed routing likely occurred, inform upper layers
7114 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007115}
7116
François Gaffiec005e562018-11-06 15:04:49 +01007117bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7118 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007119{
François Gaffiec005e562018-11-06 15:04:49 +01007120 return mEngine->getProductStrategyForAttributes(lAttr) ==
7121 mEngine->getProductStrategyForAttributes(rAttr);
7122}
7123
Francois Gaffieff1eb522020-05-06 18:37:04 +02007124void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7125{
7126 for (size_t i = 0; i < mAudioSources.size(); i++) {
7127 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7128 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007129 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007130 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007131 connectAudioSource(sourceDesc);
7132 }
7133 }
7134}
7135
7136void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7137{
7138 for (size_t i = 0; i < mAudioSources.size(); i++) {
7139 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7140 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7141 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7142 disconnectAudioSource(sourceDesc);
7143 }
7144 }
7145}
7146
François Gaffiec005e562018-11-06 15:04:49 +01007147void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7148{
7149 auto psId = mEngine->getProductStrategyForAttributes(attr);
7150
7151 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7152 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007153
François Gaffie11d30102018-11-02 16:09:09 +01007154 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7155 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007156
Eric Laurentc209fe42020-06-05 18:11:23 -07007157 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007158 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007159 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007160 // take into account dynamic audio policies related changes: if a client is now associated
7161 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007162 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007163 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7164 if (desc->isDuplicated()) {
7165 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007166 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007167 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7168 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7169 continue;
7170 }
7171 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007172 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007173 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7174 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7175 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007176 if (status != OK) {
7177 continue;
7178 }
yucliuf4de36d2020-09-14 14:57:56 -07007179 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007180 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007181 maxLatency = desc->latency();
7182 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007183 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007184 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007185 }
7186 }
7187
Eric Laurent56ed8842022-11-15 16:04:41 +01007188 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007189 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7190 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007191 for (audio_io_handle_t srcOut : srcOutputs) {
7192 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007193 if (desc == nullptr) continue;
7194
7195 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007196 maxLatency = desc->latency();
7197 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007198
Eric Laurent56ed8842022-11-15 16:04:41 +01007199 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007200 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007201 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007202 // a client on a non direct outputs has necessarily a linear PCM format
7203 // so we can call selectOutput() safely
7204 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7205 client->flags(),
7206 client->config().format,
7207 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007208 client->config().sample_rate,
7209 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007210 if (newOutput != srcOut) {
7211 invalidate = true;
7212 break;
7213 }
7214 } else {
7215 sp<IOProfile> profile = getProfileForOutput(newDevices,
7216 client->config().sample_rate,
7217 client->config().format,
7218 client->config().channel_mask,
7219 client->flags(),
7220 true /* directOnly */);
7221 if (profile != desc->mProfile) {
7222 invalidate = true;
7223 break;
7224 }
7225 }
7226 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007227 // mute strategy while moving tracks from one output to another
7228 if (invalidate) {
7229 invalidatedOutputs.push_back(desc);
7230 if (desc->isStrategyActive(psId)) {
7231 setStrategyMute(psId, true, desc);
7232 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7233 newDevices.types());
7234 }
Eric Laurente552edb2014-03-10 17:42:56 -07007235 }
François Gaffiec005e562018-11-06 15:04:49 +01007236 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007237 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007238 connectAudioSource(source);
7239 }
Eric Laurente552edb2014-03-10 17:42:56 -07007240 }
7241
Eric Laurent56ed8842022-11-15 16:04:41 +01007242 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7243 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7244 std::to_string(srcOutputs[0]).c_str(),
7245 std::to_string(dstOutputs[0]).c_str());
7246
François Gaffiec005e562018-11-06 15:04:49 +01007247 // Move effects associated to this stream from previous output to new output
7248 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007249 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007250 }
François Gaffiec005e562018-11-06 15:04:49 +01007251 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007252 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007253 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007254 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007255 desc->setTracksInvalidatedStatusByStrategy(psId);
7256 }
Eric Laurente552edb2014-03-10 17:42:56 -07007257 }
7258 }
7259}
7260
Eric Laurente0720872014-03-11 09:30:41 -07007261void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007262{
François Gaffiec005e562018-11-06 15:04:49 +01007263 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7264 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7265 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007266 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007267 }
Eric Laurente552edb2014-03-10 17:42:56 -07007268}
7269
Kevin Rocard153f92d2018-12-18 18:33:28 -08007270void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007271 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007272 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007273 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007274 for (size_t i = 0; i < mOutputs.size(); i++) {
7275 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7276 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007277 sp<AudioPolicyMix> primaryMix;
7278 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007279 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007280 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7281 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7282 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007283 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7284 for (auto &secondaryMix : secondaryMixes) {
7285 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7286 if (outputDesc != nullptr &&
7287 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7288 secondaryDescs.push_back(outputDesc);
7289 }
7290 }
7291
jiabinc44b3462022-12-08 12:52:31 -08007292 if (status != OK &&
7293 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7294 // When it failed to query secondary output, only invalidate the client that is not
7295 // MMAP. The reason is that MMAP stream will not support secondary output.
7296 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007297 } else if (!std::equal(
7298 client->getSecondaryOutputs().begin(),
7299 client->getSecondaryOutputs().end(),
7300 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007301 if (!audio_is_linear_pcm(client->config().format)) {
7302 // If the format is not PCM, the tracks should be invalidated to get correct
7303 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007304 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007305 } else {
7306 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7307 std::vector<audio_io_handle_t> secondaryOutputIds;
7308 for (const auto &secondaryDesc: secondaryDescs) {
7309 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7310 weakSecondaryDescs.push_back(secondaryDesc);
7311 }
7312 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7313 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007314 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007315 }
7316 }
7317 }
jiabin10a03f12021-05-07 23:46:28 +00007318 if (!trackSecondaryOutputs.empty()) {
7319 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7320 }
jiabinc44b3462022-12-08 12:52:31 -08007321 if (!clientsToInvalidate.empty()) {
7322 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7323 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007324 }
7325}
7326
Eric Laurent2517af32020-11-25 15:31:27 +01007327bool AudioPolicyManager::isScoRequestedForComm() const {
7328 AudioDeviceTypeAddrVector devices;
7329 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7330 for (const auto &device : devices) {
7331 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7332 return true;
7333 }
7334 }
7335 return false;
7336}
7337
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007338bool AudioPolicyManager::isHearingAidUsedForComm() const {
7339 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7340 true /*fromCache*/);
7341 for (const auto &device : devices) {
7342 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7343 return true;
7344 }
7345 }
7346 return false;
7347}
7348
7349
Eric Laurente0720872014-03-11 09:30:41 -07007350void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007351{
François Gaffie53615e22015-03-19 09:24:12 +01007352 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007353 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007354 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007355 return;
7356 }
7357
Eric Laurent3a4311c2014-03-17 12:00:47 -07007358 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007359 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7360 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007361 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007362
7363 // if suspended, restore A2DP output if:
7364 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007365 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007366 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007367 //
Eric Laurentf732e072016-08-03 19:30:28 -07007368 // if not suspended, suspend A2DP output if:
7369 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007370 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007371 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007372 //
7373 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007374 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007375 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007376 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007377 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007378
7379 mpClientInterface->restoreOutput(a2dpOutput);
7380 mA2dpSuspended = false;
7381 }
7382 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007383 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007384 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007385 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007386 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007387
7388 mpClientInterface->suspendOutput(a2dpOutput);
7389 mA2dpSuspended = true;
7390 }
7391 }
7392}
7393
François Gaffie11d30102018-11-02 16:09:09 +01007394DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7395 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007396{
François Gaffiedb1755b2023-09-01 11:50:35 +02007397 if (outputDesc == nullptr) {
7398 return DeviceVector{};
7399 }
François Gaffie11d30102018-11-02 16:09:09 +01007400
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007401 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007402 if (index >= 0) {
7403 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007404 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007405 ALOGV("%s device %s forced by patch %d", __func__,
7406 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7407 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007408 }
7409 }
7410
Dean Wheatley514b4312020-06-17 21:45:00 +10007411 // Do not retrieve engine device for outputs through MSD
7412 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7413 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7414 return outputDesc->devices();
7415 }
7416
Eric Laurent97ac8712018-07-27 18:59:02 -07007417 // Honor explicit routing requests only if no client using default routing is active on this
7418 // input: a specific app can not force routing for other apps by setting a preferred device.
7419 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007420 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007421 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007422 if (device != nullptr) {
7423 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007424 }
7425
François Gaffiea807ef92018-11-05 10:44:33 +01007426 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7427 // of setForceUse / Default Bus device here
7428 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7429 if (device != nullptr) {
7430 return DeviceVector(device);
7431 }
7432
François Gaffiedb1755b2023-09-01 11:50:35 +02007433 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007434 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7435 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307436 auto hasStreamActive = [&](auto stream) {
7437 return hasStream(streams, stream) && isStreamActive(stream, 0);
7438 };
Eric Laurent484e9272018-06-07 17:29:23 -07007439
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307440 auto doGetOutputDevicesForVoice = [&]() {
7441 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007442 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307443 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007444 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7445 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307446 };
7447
7448 // With low-latency playing on speaker, music on WFD, when the first low-latency
7449 // output is stopped, getNewOutputDevices checks for a product strategy
7450 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007451 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307452 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7453 // stream is associated to the output descriptor.
7454 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7455 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7456 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7457 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007458 // Retrieval of devices for voice DL is done on primary output profile, cannot
7459 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007460 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007461 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7462 break;
7463 }
Eric Laurente552edb2014-03-10 17:42:56 -07007464 }
François Gaffiec005e562018-11-06 15:04:49 +01007465 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007466 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007467}
7468
François Gaffie11d30102018-11-02 16:09:09 +01007469sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7470 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007471{
François Gaffie11d30102018-11-02 16:09:09 +01007472 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007473
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007474 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007475 if (index >= 0) {
7476 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007477 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007478 ALOGV("getNewInputDevice() device %s forced by patch %d",
7479 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7480 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007481 }
7482 }
7483
Eric Laurent97ac8712018-07-27 18:59:02 -07007484 // Honor explicit routing requests only if no client using default routing is active on this
7485 // input: a specific app can not force routing for other apps by setting a preferred device.
7486 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007487 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7488 if (device != nullptr) {
7489 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007490 }
7491
Eric Laurentdc95a252018-04-12 12:46:56 -07007492 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007493 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007494 audio_attributes_t attributes;
7495 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007496 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007497 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7498 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007499 attributes = topClient->attributes();
7500 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007501 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007502 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007503 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7504 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007505 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007506 }
7507
Francois Gaffie716e1432019-01-14 16:58:59 +01007508 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7509 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007510 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007511 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007512 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007513 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007514
Eric Laurente552edb2014-03-10 17:42:56 -07007515 return device;
7516}
7517
Eric Laurent794fde22016-03-11 09:50:45 -08007518bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7519 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007520 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007521}
7522
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007523status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007524 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007525 if (devices == nullptr) {
7526 return BAD_VALUE;
7527 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007528
Andy Hung6d23c0f2022-02-16 09:37:15 -08007529 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007530 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7531 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007532 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007533 for (const auto& device : curDevices) {
7534 devices->push_back(device->getDeviceTypeAddr());
7535 }
7536 return NO_ERROR;
7537}
7538
Eric Laurente0720872014-03-11 09:30:41 -07007539void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007540 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007541 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007542 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007543 updateDevicesAndOutputs();
7544 break;
7545 default:
7546 break;
7547 }
7548}
7549
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007550uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007551
7552 // skip beacon mute management if a dedicated TTS output is available
7553 if (mTtsOutputAvailable) {
7554 return 0;
7555 }
7556
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007557 switch(event) {
7558 case STARTING_OUTPUT:
7559 mBeaconMuteRefCount++;
7560 break;
7561 case STOPPING_OUTPUT:
7562 if (mBeaconMuteRefCount > 0) {
7563 mBeaconMuteRefCount--;
7564 }
7565 break;
7566 case STARTING_BEACON:
7567 mBeaconPlayingRefCount++;
7568 break;
7569 case STOPPING_BEACON:
7570 if (mBeaconPlayingRefCount > 0) {
7571 mBeaconPlayingRefCount--;
7572 }
7573 break;
7574 }
7575
7576 if (mBeaconMuteRefCount > 0) {
7577 // any playback causes beacon to be muted
7578 return setBeaconMute(true);
7579 } else {
7580 // no other playback: unmute when beacon starts playing, mute when it stops
7581 return setBeaconMute(mBeaconPlayingRefCount == 0);
7582 }
7583}
7584
7585uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7586 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7587 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7588 // keep track of muted state to avoid repeating mute/unmute operations
7589 if (mBeaconMuted != mute) {
7590 // mute/unmute AUDIO_STREAM_TTS on all outputs
7591 ALOGV("\t muting %d", mute);
7592 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007593 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7594 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7595 ALOGV("\t no tts volume source available");
7596 return 0;
7597 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007598 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007599 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007600 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007601 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007602 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007603 maxLatency = latency;
7604 }
7605 }
7606 mBeaconMuted = mute;
7607 return maxLatency;
7608 }
7609 return 0;
7610}
7611
Eric Laurente0720872014-03-11 09:30:41 -07007612void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007613{
François Gaffiec005e562018-11-06 15:04:49 +01007614 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007615 mPreviousOutputs = mOutputs;
7616}
7617
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007618uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007619 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007620 uint32_t delayMs)
7621{
7622 // mute/unmute strategies using an incompatible device combination
7623 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7624 // if unmuting, unmute only after the specified delay
7625 if (outputDesc->isDuplicated()) {
7626 return 0;
7627 }
7628
7629 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007630 DeviceVector devices = outputDesc->devices();
7631 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007632
François Gaffiec005e562018-11-06 15:04:49 +01007633 auto productStrategies = mEngine->getOrderedProductStrategies();
7634 for (const auto &productStrategy : productStrategies) {
7635 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7636 DeviceVector curDevices =
7637 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7638 curDevices = curDevices.filter(outputDesc->supportedDevices());
7639 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007640 bool doMute = false;
7641
François Gaffiec005e562018-11-06 15:04:49 +01007642 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007643 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007644 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7645 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007646 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007647 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007648 }
Eric Laurent99401132014-05-07 19:48:15 -07007649 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007650 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007651 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007652 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007653 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007654 continue;
7655 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307656 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007657 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7658 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7659 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007660 if (mute) {
7661 // FIXME: should not need to double latency if volume could be applied
7662 // immediately by the audioflinger mixer. We must account for the delay
7663 // between now and the next time the audioflinger thread for this output
7664 // will process a buffer (which corresponds to one buffer size,
7665 // usually 1/2 or 1/4 of the latency).
7666 if (muteWaitMs < desc->latency() * 2) {
7667 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007668 }
7669 }
7670 }
7671 }
7672 }
7673 }
7674
Eric Laurent99401132014-05-07 19:48:15 -07007675 // temporary mute output if device selection changes to avoid volume bursts due to
7676 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007677 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007678 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007679
Eric Laurentdc462862016-07-19 12:29:53 -07007680 if (muteWaitMs < tempMuteWaitMs) {
7681 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007682 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007683
7684 // If recommended duration is defined, replace temporary mute duration to avoid
7685 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7686 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7687 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7688 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7689 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7690
François Gaffieaaac0fd2018-11-22 17:56:39 +01007691 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7692 // make sure that we do not start the temporary mute period too early in case of
7693 // delayed device change
7694 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7695 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007696 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007697 }
7698 }
7699
Eric Laurente552edb2014-03-10 17:42:56 -07007700 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7701 if (muteWaitMs > delayMs) {
7702 muteWaitMs -= delayMs;
7703 usleep(muteWaitMs * 1000);
7704 return muteWaitMs;
7705 }
7706 return 0;
7707}
7708
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307709uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7710 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007711 const DeviceVector &devices,
7712 bool force,
7713 int delayMs,
7714 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007715 bool requiresMuteCheck, bool requiresVolumeCheck,
7716 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007717{
jiabin3ff8d7d2022-12-13 06:27:44 +00007718 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307719 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7720 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7721 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007722 uint32_t muteWaitMs;
7723
7724 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307725 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007726 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307727 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007728 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007729 return muteWaitMs;
7730 }
Eric Laurente552edb2014-03-10 17:42:56 -07007731
7732 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007733 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007734 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007735 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007736
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307737 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7738 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007739
7740 if (!filteredDevices.isEmpty()) {
7741 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007742 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007743
7744 // if the outputs are not materially active, there is no need to mute.
7745 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007746 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007747 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307748 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7749 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007750 muteWaitMs = 0;
7751 }
Eric Laurente552edb2014-03-10 17:42:56 -07007752
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007753 bool outputRouted = outputDesc->isRouted();
7754
Eric Laurent79ea9582020-06-11 18:49:24 -07007755 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7756 // output profile or if new device is not supported AND previous device(s) is(are) still
7757 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007758 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307759 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7760 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007761 // restore previous device after evaluating strategy mute state
7762 outputDesc->setDevices(prevDevices);
7763 return muteWaitMs;
7764 }
7765
Eric Laurente552edb2014-03-10 17:42:56 -07007766 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007767 // the requested device is AUDIO_DEVICE_NONE
7768 // OR the requested device is the same as current device
7769 // AND force is not specified
7770 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007771 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007772 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307773 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7774 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7775 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007776 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307777 ALOGV("%s %s setting same device on routed output, force apply volumes",
7778 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007779 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7780 }
Eric Laurente552edb2014-03-10 17:42:56 -07007781 return muteWaitMs;
7782 }
7783
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307784 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7785 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007786
Eric Laurente552edb2014-03-10 17:42:56 -07007787 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007788 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007789 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007790 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007791 PatchBuilder patchBuilder;
7792 patchBuilder.addSource(outputDesc);
7793 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7794 for (const auto &filteredDevice : filteredDevices) {
7795 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007796 }
7797
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007798 // Add half reported latency to delayMs when muteWaitMs is null in order
7799 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007800 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7801 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7802 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007803 }
Eric Laurente552edb2014-03-10 17:42:56 -07007804
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007805 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7806 if (!skipMuteDelay) {
7807 // update stream volumes according to new device
7808 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7809 }
Eric Laurente552edb2014-03-10 17:42:56 -07007810
7811 return muteWaitMs;
7812}
7813
Eric Laurentc75307b2015-03-17 15:29:32 -07007814status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007815 int delayMs,
7816 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007817{
Eric Laurent6a94d692014-05-20 11:18:06 -07007818 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007819 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7820 return INVALID_OPERATION;
7821 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007822 if (patchHandle) {
7823 index = mAudioPatches.indexOfKey(*patchHandle);
7824 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007825 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007826 }
7827 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007828 return INVALID_OPERATION;
7829 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007830 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007831 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007832 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007833 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007834 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007835 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007836 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007837 return status;
7838}
7839
7840status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007841 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007842 bool force,
7843 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007844{
7845 status_t status = NO_ERROR;
7846
Eric Laurent1f2f2232014-06-02 12:01:23 -07007847 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007848 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7849 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007850
François Gaffie11d30102018-11-02 16:09:09 +01007851 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007852 PatchBuilder patchBuilder;
7853 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007854 // AUDIO_SOURCE_HOTWORD is for internal use only:
7855 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007856 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7857 auto result = usecase;
7858 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7859 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7860 }
7861 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007862 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007863 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007864 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007865 }
7866 }
7867 return status;
7868}
7869
Eric Laurent6a94d692014-05-20 11:18:06 -07007870status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7871 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007872{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007873 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007874 ssize_t index;
7875 if (patchHandle) {
7876 index = mAudioPatches.indexOfKey(*patchHandle);
7877 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007878 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007879 }
7880 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007881 return INVALID_OPERATION;
7882 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007883 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007884 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007885 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007886 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007887 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007888 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007889 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007890 return status;
7891}
7892
François Gaffie11d30102018-11-02 16:09:09 +01007893sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007894 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007895 audio_format_t& format,
7896 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007897 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007898{
7899 // Choose an input profile based on the requested capture parameters: select the first available
7900 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007901 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007902
Atneya Nair0f0a8032022-12-12 16:20:12 -08007903 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7904 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7905 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7906
7907 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007908
jiabin2fd710d2022-05-02 23:20:22 +00007909 for (;;) {
7910 sp<IOProfile> firstInexact = nullptr;
7911 uint32_t updatedSamplingRate = 0;
7912 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7913 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7914 for (const auto& hwModule : mHwModules) {
7915 for (const auto& profile : hwModule->getInputProfiles()) {
7916 // profile->log();
7917 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007918 if (profile->getCompatibilityScore(
7919 DeviceVector(device),
7920 samplingRate,
7921 &updatedSamplingRate,
7922 format,
7923 &updatedFormat,
7924 channelMask,
7925 &updatedChannelMask,
7926 // FIXME ugly cast
7927 (audio_output_flags_t) flags,
7928 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7929 samplingRate = updatedSamplingRate;
7930 format = updatedFormat;
7931 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007932 return profile;
7933 }
jiabin66acc432024-02-06 00:57:36 +00007934 if (firstInexact == nullptr
7935 && profile->getCompatibilityScore(
7936 DeviceVector(device),
7937 samplingRate,
7938 &updatedSamplingRate,
7939 format,
7940 &updatedFormat,
7941 channelMask,
7942 &updatedChannelMask,
7943 // FIXME ugly cast
7944 (audio_output_flags_t) flags,
7945 false /*exactMatchRequiredForInputFlags*/)
7946 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007947 firstInexact = profile;
7948 }
7949 }
7950 }
7951
7952 if (firstInexact != nullptr) {
7953 samplingRate = updatedSamplingRate;
7954 format = updatedFormat;
7955 channelMask = updatedChannelMask;
7956 return firstInexact;
7957 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7958 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7959 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7960 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7961 flags = AUDIO_INPUT_FLAG_NONE;
7962 } else { // fail
7963 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7964 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7965 samplingRate, format, channelMask, oriFlags);
7966 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007967 }
7968 }
jiabin2fd710d2022-05-02 23:20:22 +00007969
7970 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007971}
7972
François Gaffieaaac0fd2018-11-22 17:56:39 +01007973float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7974 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007975 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007976 const DeviceTypeSet& deviceTypes,
7977 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07007978{
jiabin9a3361e2019-10-01 09:38:30 -07007979 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007980
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007981 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
7982 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
7983
7984 if (!computeInternalInteraction) {
7985 return volumeDb;
7986 }
7987
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007988 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7989 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7990 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7991 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007992 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7993 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7994 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7995 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7996 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007997 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007998 mOutputs.isActive(ringVolumeSrc, 0)) {
7999 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008000 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8001 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008002 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008003 }
8004
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008005 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008006 if ((volumeSource != callVolumeSrc && (isInCall() ||
8007 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008008 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008009 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8010 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008011 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8012 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8013 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008014 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008015 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008016 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008017 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008018 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8019 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008020 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008021 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8022 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8023 // programmatically muted.
8024 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8025 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8026 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008027 bool exemptFromCapping =
8028 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8029 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008030 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8031 volumeSource, volumeDb);
8032 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008033 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8034 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8035 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008036 }
8037 }
Eric Laurente552edb2014-03-10 17:42:56 -07008038 // if a headset is connected, apply the following rules to ring tones and notifications
8039 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008040 // - always attenuate notifications volume by 6dB
8041 // - attenuate ring tones volume by 6dB unless music is not playing and
8042 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008043 // - if music is playing, always limit the volume to current music volume,
8044 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008045 if (!Intersection(deviceTypes,
8046 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8047 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008048 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8049 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008050 ((volumeSource == alarmVolumeSrc ||
8051 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008052 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8053 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8054 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008055 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8056 curves.canBeMuted()) {
8057
Eric Laurente552edb2014-03-10 17:42:56 -07008058 // when the phone is ringing we must consider that music could have been paused just before
8059 // by the music application and behave as if music was active if the last music track was
8060 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008061 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8062 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008063 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008064 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008065 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8066 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008067 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008068 float musicVolDb = computeVolume(musicCurves,
8069 musicVolumeSrc,
8070 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008071 musicDevice,
8072 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008073 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8074 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8075 if (volumeDb > minVolDb) {
8076 volumeDb = minVolDb;
8077 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008078 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008079 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8080 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8081 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008082 // on A2DP, also ensure notification volume is not too low compared to media when
8083 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01008084 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008085 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008086 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8087 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008088 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8089 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008090 }
8091 }
jiabin9a3361e2019-10-01 09:38:30 -07008092 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008093 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008094 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008095 }
8096 }
8097
François Gaffie43c73442018-11-08 08:21:55 +01008098 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008099}
8100
Eric Laurent3839bc02018-07-10 18:33:34 -07008101int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008102 VolumeSource fromVolumeSource,
8103 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008104{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008105 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008106 return srcIndex;
8107 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008108 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8109 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008110 float minSrc = (float)srcCurves.getVolumeIndexMin();
8111 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8112 float minDst = (float)dstCurves.getVolumeIndexMin();
8113 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008114
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008115 // preserve mute request or correct range
8116 if (srcIndex < minSrc) {
8117 if (srcIndex == 0) {
8118 return 0;
8119 }
8120 srcIndex = minSrc;
8121 } else if (srcIndex > maxSrc) {
8122 srcIndex = maxSrc;
8123 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008124 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8125}
8126
François Gaffieaaac0fd2018-11-22 17:56:39 +01008127status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8128 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008129 int index,
8130 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008131 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008132 int delayMs,
8133 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008134{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008135 // do not change actual attributes volume if the attributes is muted
8136 if (outputDesc->isMuted(volumeSource)) {
8137 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8138 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008139 return NO_ERROR;
8140 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008141
Eric Laurentae6e88c2024-01-10 14:42:57 +01008142 bool isVoiceVolSrc;
8143 bool isBtScoVolSrc;
8144 if (!isVolumeConsistentForCalls(
8145 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008146 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008147 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008148 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008149 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008150
jiabin9a3361e2019-10-01 09:38:30 -07008151 if (deviceTypes.empty()) {
8152 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008153 index = curves.getVolumeIndex(deviceTypes);
8154 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
8155 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008156 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008157
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008158 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8159 ALOGE("invalid volume index range");
8160 return BAD_VALUE;
8161 }
8162
jiabin9a3361e2019-10-01 09:38:30 -07008163 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8164 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008165 // Force VoIP volume to max for bluetooth SCO device except if muted
8166 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008167 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008168 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008169 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008170 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008171 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8172 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008173
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008174 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008175 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008176 }
Eric Laurente552edb2014-03-10 17:42:56 -07008177 return NO_ERROR;
8178}
8179
Eric Laurentae6e88c2024-01-10 14:42:57 +01008180void AudioPolicyManager::setVoiceVolume(
8181 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8182 float voiceVolume;
8183 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8184 // by the headset
8185 if (isVoiceVolSrc) {
8186 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8187 } else {
8188 voiceVolume = index == 0 ? 0.0 : 1.0;
8189 }
8190 if (voiceVolume != mLastVoiceVolume) {
8191 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8192 mLastVoiceVolume = voiceVolume;
8193 }
8194}
8195
8196bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8197 const DeviceTypeSet& deviceTypes,
8198 bool& isVoiceVolSrc,
8199 bool& isBtScoVolSrc,
8200 const char* caller) {
8201 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8202 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8203 const bool isScoRequested = isScoRequestedForComm();
8204 const bool isHAUsed = isHearingAidUsedForComm();
8205
8206 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8207 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8208
8209 if ((callVolSrc != btScoVolSrc) &&
8210 ((isVoiceVolSrc && isScoRequested) ||
8211 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8212 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8213 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8214 volumeSource, isScoRequested ? " " : " not ");
8215 return false;
8216 }
8217 return true;
8218}
8219
Eric Laurentc75307b2015-03-17 15:29:32 -07008220void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008221 const DeviceTypeSet& deviceTypes,
8222 int delayMs,
8223 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008224{
jiabincd510522020-01-22 09:40:55 -08008225 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008226 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8227 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8228 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008229 curves.getVolumeIndex(deviceTypes),
8230 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008231 }
8232}
8233
François Gaffiec005e562018-11-06 15:04:49 +01008234void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8235 bool on,
8236 const sp<AudioOutputDescriptor>& outputDesc,
8237 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008238 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008239{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008240 std::vector<VolumeSource> sourcesToMute;
8241 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8242 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8243 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008244 VolumeSource source = toVolumeSource(attributes, false);
8245 if ((source != VOLUME_SOURCE_NONE) &&
8246 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8247 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008248 sourcesToMute.push_back(source);
8249 }
Eric Laurente552edb2014-03-10 17:42:56 -07008250 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008251 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008252 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008253 }
8254
Eric Laurente552edb2014-03-10 17:42:56 -07008255}
8256
François Gaffieaaac0fd2018-11-22 17:56:39 +01008257void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8258 bool on,
8259 const sp<AudioOutputDescriptor>& outputDesc,
8260 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008261 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008262{
jiabin9a3361e2019-10-01 09:38:30 -07008263 if (deviceTypes.empty()) {
8264 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008265 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008266 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008267 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008268 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008269 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008270 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008271 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8272 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008273 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008274 }
8275 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008276 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8277 // ignored
8278 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008279 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008280 if (!outputDesc->isMuted(volumeSource)) {
8281 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008282 return;
8283 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008284 if (outputDesc->decMuteCount(volumeSource) == 0) {
8285 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008286 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008287 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008288 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008289 delayMs);
8290 }
8291 }
8292}
8293
François Gaffie53615e22015-03-19 09:24:12 +01008294bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8295{
François Gaffiec005e562018-11-06 15:04:49 +01008296 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008297 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8298 return true;
8299 }
8300
8301 // has known usage?
8302 switch (paa->usage) {
8303 case AUDIO_USAGE_UNKNOWN:
8304 case AUDIO_USAGE_MEDIA:
8305 case AUDIO_USAGE_VOICE_COMMUNICATION:
8306 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8307 case AUDIO_USAGE_ALARM:
8308 case AUDIO_USAGE_NOTIFICATION:
8309 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8310 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8311 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8312 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8313 case AUDIO_USAGE_NOTIFICATION_EVENT:
8314 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8315 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8316 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8317 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008318 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008319 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008320 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008321 case AUDIO_USAGE_EMERGENCY:
8322 case AUDIO_USAGE_SAFETY:
8323 case AUDIO_USAGE_VEHICLE_STATUS:
8324 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008325 break;
8326 default:
8327 return false;
8328 }
8329 return true;
8330}
8331
François Gaffie2110e042015-03-24 08:41:51 +01008332audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8333{
8334 return mEngine->getForceUse(usage);
8335}
8336
Eric Laurent96d1dda2022-03-14 17:14:19 +01008337bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008338 return isStateInCall(mEngine->getPhoneState());
8339}
8340
Eric Laurent96d1dda2022-03-14 17:14:19 +01008341bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008342 return is_state_in_call(state);
8343}
8344
Eric Laurentf9cccec2022-11-16 19:12:00 +01008345bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008346 audio_mode_t mode = mEngine->getPhoneState();
8347 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008348 || (mode == AUDIO_MODE_CALL_SCREEN)
8349 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008350}
8351
Eric Laurentf9cccec2022-11-16 19:12:00 +01008352bool AudioPolicyManager::isInCallOrScreening() const {
8353 audio_mode_t mode = mEngine->getPhoneState();
8354 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8355}
8356
Eric Laurentd60560a2015-04-10 11:31:20 -07008357void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8358{
8359 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008360 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008361 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008362 sourceDesc->sinkDevice()->equals(deviceDesc))
8363 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008364 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008365 }
8366 }
8367
8368 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8369 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8370 bool release = false;
8371 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8372 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8373 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8374 source->ext.device.type == deviceDesc->type()) {
8375 release = true;
8376 }
8377 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008378 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008379 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8380 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8381 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008382 sink->ext.device.type == deviceDesc->type() &&
8383 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8384 || strncmp(sink->ext.device.address, address,
8385 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008386 release = true;
8387 }
8388 }
8389 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008390 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8391 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008392 }
8393 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008394
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008395 mInputs.clearSessionRoutesForDevice(deviceDesc);
8396
Francois Gaffie716e1432019-01-14 16:58:59 +01008397 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008398}
8399
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008400void AudioPolicyManager::modifySurroundFormats(
8401 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008402 std::unordered_set<audio_format_t> enforcedSurround(
8403 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008404 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008405 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008406 allSurround.insert(pair.first);
8407 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8408 }
Phil Burk09bc4612016-02-24 15:58:15 -08008409
8410 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8411 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008412 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008413 // This is the resulting set of formats depending on the surround mode:
8414 // 'all surround' = allSurround
8415 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8416 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8417 // 'manual surround' = mManualSurroundFormats
8418 // AUTO: formats v 'enforced surround'
8419 // ALWAYS: formats v 'all surround' v 'enforced surround'
8420 // NEVER: formats ^ 'non-surround'
8421 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008422
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008423 std::unordered_set<audio_format_t> formatSet;
8424 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8425 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008426 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008427 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008428 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008429 formatSet.insert(*formatIter);
8430 }
8431 }
8432 } else {
8433 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8434 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008435 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008436
jiabin81772902018-04-02 17:52:27 -07008437 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008438 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008439 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8440 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8441 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008442 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008443 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8444 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8445 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008446 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008447 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008448 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008449 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008450 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008451 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008452}
8453
jiabin06e4bab2019-07-29 10:13:34 -07008454void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8455 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008456 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8457 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8458
8459 // If NEVER, then remove support for channelMasks > stereo.
8460 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008461 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8462 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008463 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008464 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008465 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008466 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008467 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008468 }
8469 }
jiabin81772902018-04-02 17:52:27 -07008470 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8471 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8472 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008473 bool supports5dot1 = false;
8474 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008475 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008476 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8477 supports5dot1 = true;
8478 break;
8479 }
8480 }
8481 // If not then add 5.1 support.
8482 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008483 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008484 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008485 }
Phil Burk09bc4612016-02-24 15:58:15 -08008486 }
8487}
8488
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008489void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008490 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008491 const sp<IOProfile>& profile) {
8492 if (!profile->hasDynamicAudioProfile()) {
8493 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008494 }
François Gaffie112b0af2015-11-19 16:13:25 +01008495
jiabin12537fc2023-10-12 17:56:08 +00008496 audio_port_v7 devicePort;
8497 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008498
jiabin12537fc2023-10-12 17:56:08 +00008499 audio_port_v7 mixPort;
8500 profile->toAudioPort(&mixPort);
8501 mixPort.ext.mix.handle = ioHandle;
8502
8503 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8504 if (status != NO_ERROR) {
8505 ALOGE("%s failed to query the attributes of the mix port", __func__);
8506 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008507 }
jiabin12537fc2023-10-12 17:56:08 +00008508
8509 std::set<audio_format_t> supportedFormats;
8510 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8511 supportedFormats.insert(mixPort.audio_profiles[i].format);
8512 }
8513 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8514 mReportedFormatsMap[devDesc] = formats;
8515
8516 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8517 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8518 modifySurroundFormats(devDesc, &formats);
8519 size_t modifiedNumProfiles = 0;
8520 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8521 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8522 formats.end()) {
8523 // Skip the format that is not present after modifying surround formats.
8524 continue;
8525 }
8526 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8527 sizeof(struct audio_profile));
8528 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8529 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8530 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8531 modifySurroundChannelMasks(&channels);
8532 std::copy(channels.begin(), channels.end(),
8533 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8534 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8535 }
8536 mixPort.num_audio_profiles = modifiedNumProfiles;
8537 }
8538 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008539}
Eric Laurentd60560a2015-04-10 11:31:20 -07008540
Mikhail Naganovdc769682018-05-04 15:34:08 -07008541status_t AudioPolicyManager::installPatch(const char *caller,
8542 audio_patch_handle_t *patchHandle,
8543 AudioIODescriptorInterface *ioDescriptor,
8544 const struct audio_patch *patch,
8545 int delayMs)
8546{
8547 ssize_t index = mAudioPatches.indexOfKey(
8548 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8549 *patchHandle : ioDescriptor->getPatchHandle());
8550 sp<AudioPatch> patchDesc;
8551 status_t status = installPatch(
8552 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8553 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008554 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008555 }
8556 return status;
8557}
8558
8559status_t AudioPolicyManager::installPatch(const char *caller,
8560 ssize_t index,
8561 audio_patch_handle_t *patchHandle,
8562 const struct audio_patch *patch,
8563 int delayMs,
8564 uid_t uid,
8565 sp<AudioPatch> *patchDescPtr)
8566{
8567 sp<AudioPatch> patchDesc;
8568 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8569 if (index >= 0) {
8570 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008571 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008572 }
8573
8574 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8575 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8576 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8577 if (status == NO_ERROR) {
8578 if (index < 0) {
8579 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008580 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008581 } else {
8582 patchDesc->mPatch = *patch;
8583 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008584 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008585 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008586 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008587 }
8588 nextAudioPortGeneration();
8589 mpClientInterface->onAudioPatchListUpdate();
8590 }
8591 if (patchDescPtr) *patchDescPtr = patchDesc;
8592 return status;
8593}
8594
jiabinbce0c1d2020-10-05 11:20:18 -07008595bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8596{
8597 const TrackClientVector activeClients = output->getActiveClients();
8598 if (activeClients.empty()) {
8599 return true;
8600 }
8601 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8602 if (index < 0) {
8603 ALOGE("%s, no audio patch found while there are active clients on output %d",
8604 __func__, output->getId());
8605 return false;
8606 }
8607 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8608 DeviceVector routedDevices;
8609 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8610 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8611 patchDesc->mPatch.sinks[i].id);
8612 if (device == nullptr) {
8613 ALOGE("%s, no audio device found with id(%d)",
8614 __func__, patchDesc->mPatch.sinks[i].id);
8615 return false;
8616 }
8617 routedDevices.add(device);
8618 }
8619 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008620 if (client->isInvalid()) {
8621 // No need to take care about invalidated clients.
8622 continue;
8623 }
jiabinbce0c1d2020-10-05 11:20:18 -07008624 sp<DeviceDescriptor> preferredDevice =
8625 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8626 if (mEngine->getOutputDevicesForAttributes(
8627 client->attributes(), preferredDevice, false) == routedDevices) {
8628 return false;
8629 }
8630 }
8631 return true;
8632}
8633
8634sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008635 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008636 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8637 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008638{
8639 for (const auto& device : devices) {
8640 // TODO: This should be checking if the profile supports the device combo.
8641 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008642 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8643 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008644 return nullptr;
8645 }
8646 }
8647 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8648 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008649 status_t status = desc->open(halConfig, mixerConfig, devices,
8650 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008651 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008652 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008653 return nullptr;
8654 }
jiabin14b50cc2023-12-13 19:01:52 +00008655 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8656 auto portConfig = desc->getConfig();
8657 for (const auto& device : devices) {
8658 device->setPreferredConfig(&portConfig);
8659 }
8660 }
jiabinbce0c1d2020-10-05 11:20:18 -07008661
8662 // Here is where the out_set_parameters() for card & device gets called
8663 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8664 const audio_devices_t deviceType = device->type();
8665 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008666 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008667 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8668 mpClientInterface->setParameters(output, String8(param));
8669 free(param);
8670 }
jiabin12537fc2023-10-12 17:56:08 +00008671 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008672 if (!profile->hasValidAudioProfile()) {
8673 ALOGW("%s() missing param", __func__);
8674 desc->close();
8675 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008676 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8677 // Reopen the output with the best audio profile picked by APM when the profile supports
8678 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008679 desc->close();
8680 output = AUDIO_IO_HANDLE_NONE;
8681 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8682 profile->pickAudioProfile(
8683 config.sample_rate, config.channel_mask, config.format);
8684 config.offload_info.sample_rate = config.sample_rate;
8685 config.offload_info.channel_mask = config.channel_mask;
8686 config.offload_info.format = config.format;
8687
jiabina84c3d32022-12-02 18:59:55 +00008688 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008689 if (status != NO_ERROR) {
8690 return nullptr;
8691 }
8692 }
8693
8694 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008695 setOutputDevices(__func__, desc,
8696 devices,
8697 true,
8698 0,
8699 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008700 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8701 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8702
jiabinbce0c1d2020-10-05 11:20:18 -07008703 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8704 sp<AudioPolicyMix> policyMix;
8705 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8706 policyMix->setOutput(desc);
8707 desc->mPolicyMix = policyMix;
8708 } else {
8709 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008710 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008711 }
8712
baek.kim -61c20122022-07-27 10:05:32 +00008713 } else if (hasPrimaryOutput() && speaker != nullptr
8714 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008715 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8716 // no duplicated output for:
8717 // - direct outputs
8718 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008719 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008720 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8721
8722 //TODO: configure audio effect output stage here
8723
8724 // open a duplicating output thread for the new output and the primary output
8725 sp<SwAudioOutputDescriptor> dupOutputDesc =
8726 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8727 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8728 if (status == NO_ERROR) {
8729 // add duplicated output descriptor
8730 addOutput(duplicatedOutput, dupOutputDesc);
8731 } else {
8732 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8733 mPrimaryOutput->mIoHandle, output);
8734 desc->close();
8735 removeOutput(output);
8736 nextAudioPortGeneration();
8737 return nullptr;
8738 }
8739 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008740 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8741 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8742 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008743 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008744 }
jiabinbce0c1d2020-10-05 11:20:18 -07008745 return desc;
8746}
8747
jiabinf1c73972022-04-14 16:28:52 -07008748status_t AudioPolicyManager::getDevicesForAttributes(
8749 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8750 // Devices are determined in the following precedence:
8751 //
8752 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8753 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8754 //
8755 // If no such dynamic policy then
8756 // 2) Devices containing an active client using setPreferredDevice
8757 // with same strategy as the attributes.
8758 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8759 //
8760 // If no corresponding active client with setPreferredDevice then
8761 // 3) Devices associated with the strategy determined by the attributes
8762 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8763 //
8764 // See related getOutputForAttrInt().
8765
8766 // check dynamic policies but only for primary descriptors (secondary not used for audible
8767 // audio routing, only used for duplication for playback capture)
8768 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008769 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008770 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008771 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8772 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8773 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008774 if (status != OK) {
8775 return status;
8776 }
8777
8778 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8779 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8780 // as they are unaffected by device/stream volume
8781 // (per SwAudioOutputDescriptor::isFixedVolume()).
8782 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8783 ) {
8784 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8785 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8786 devices.add(deviceDesc);
8787 } else {
8788 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8789 // which selects setPreferredDevice if active. This means forVolume call
8790 // will take an active setPreferredDevice, if such exists.
8791
8792 devices = mEngine->getOutputDevicesForAttributes(
8793 attr, nullptr /* preferredDevice */, false /* fromCache */);
8794 }
8795
8796 if (forVolume) {
8797 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8798 // for single volume control in AudioService (such relationship should exist if
8799 // SPEAKER_SAFE is present).
8800 //
8801 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8802 DeviceVector speakerSafeDevices =
8803 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8804 if (!speakerSafeDevices.isEmpty()) {
8805 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8806 devices.remove(speakerSafeDevices);
8807 }
8808 }
8809
8810 return NO_ERROR;
8811}
8812
8813status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8814 AudioProfileVector& audioProfiles,
8815 uint32_t flags,
8816 bool isInput) {
8817 for (const auto& hwModule : mHwModules) {
8818 // the MSD module checks for different conditions
8819 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8820 continue;
8821 }
8822 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8823 : hwModule->getOutputProfiles();
8824 for (const auto& profile : ioProfiles) {
8825 if (!profile->areAllDevicesSupported(devices) ||
8826 !profile->isCompatibleProfileForFlags(
8827 flags, false /*exactMatchRequiredForInputFlags*/)) {
8828 continue;
8829 }
8830 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8831 }
8832 }
8833
8834 if (!isInput) {
8835 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8836 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8837 if (msdModule != nullptr) {
8838 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8839 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8840 for (const auto &profile: msdModule->getOutputProfiles()) {
8841 if (!profile->asAudioPort()->isDirectOutput()) {
8842 continue;
8843 }
8844 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8845 }
8846 } else {
8847 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8848 }
8849 }
8850 }
8851
8852 return NO_ERROR;
8853}
8854
jiabin3ff8d7d2022-12-13 06:27:44 +00008855sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8856 const audio_config_t *config,
8857 audio_output_flags_t flags,
8858 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008859 closeOutput(outputDesc->mIoHandle);
8860 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8861 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8862 if (preferredOutput == nullptr) {
8863 ALOGE("%s failed to reopen output device=%d, caller=%s",
8864 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008865 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008866 return preferredOutput;
8867}
8868
8869void AudioPolicyManager::reopenOutputsWithDevices(
8870 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8871 for (const auto& [output, devices] : outputsToReopen) {
8872 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8873 closeOutput(output);
8874 openOutputWithProfileAndDevice(desc->mProfile, devices);
8875 }
jiabina84c3d32022-12-02 18:59:55 +00008876}
8877
jiabinc44b3462022-12-08 12:52:31 -08008878PortHandleVector AudioPolicyManager::getClientsForStream(
8879 audio_stream_type_t streamType) const {
8880 PortHandleVector clients;
8881 for (size_t i = 0; i < mOutputs.size(); ++i) {
8882 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8883 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8884 }
8885 return clients;
8886}
8887
8888void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8889 PortHandleVector clients;
8890 for (auto stream : streams) {
8891 PortHandleVector clientsForStream = getClientsForStream(stream);
8892 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8893 }
8894 mpClientInterface->invalidateTracks(clients);
8895}
8896
jiabin220eea12024-05-17 17:55:20 +00008897void AudioPolicyManager::updateClientsInternalMute(
8898 const sp<android::SwAudioOutputDescriptor> &desc) {
8899 if (!desc->isBitPerfect() ||
8900 !com::android::media::audioserver::
8901 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
8902 // This is only used for bit perfect output now.
8903 return;
8904 }
8905 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
8906 bool bitPerfectClientInternalMute = false;
8907 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
8908 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
8909 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
8910 bitPerfectClient = client;
8911 continue;
8912 }
8913 bool muted = false;
8914 if (client->stream() == AUDIO_STREAM_SYSTEM) {
8915 // System sound is muted.
8916 muted = true;
8917 } else {
8918 bitPerfectClientInternalMute = true;
8919 }
8920 if (client->setInternalMute(muted)) {
8921 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
8922 if (!result.ok()) {
8923 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
8924 continue;
8925 }
8926 media::TrackInternalMuteInfo info;
8927 info.portId = result.value();
8928 info.muted = client->getInternalMute();
8929 clientsInternalMute.push_back(std::move(info));
8930 }
8931 }
8932 if (bitPerfectClient != nullptr &&
8933 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
8934 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
8935 if (result.ok()) {
8936 media::TrackInternalMuteInfo info;
8937 info.portId = result.value();
8938 info.muted = bitPerfectClient->getInternalMute();
8939 clientsInternalMute.push_back(std::move(info));
8940 } else {
8941 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
8942 __func__, bitPerfectClient->portId());
8943 }
8944 }
8945 if (!clientsInternalMute.empty()) {
8946 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
8947 status != NO_ERROR) {
8948 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
8949 }
8950 }
8951}
8952
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008953} // namespace android