blob: e3e81b5e28b94c443f052ba40894a4b4b5cd4230 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000341 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700399 // Propagate device availability to Engine
400 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200401
Eric Laurent0dd51852019-04-19 18:18:58 -0700402 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
404
Eric Laurent0dd51852019-04-19 18:18:58 -0700405 mAvailableInputDevices.remove(device);
406
jiabinc0048632023-04-27 22:04:31 +0000407 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100408
409 mHwModules.cleanUpForDevice(device);
410
Eric Laurentd4692962014-05-05 18:13:44 -0700411 return INVALID_OPERATION;
412 }
413
Eric Laurentd4692962014-05-05 18:13:44 -0700414 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700415
416 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700417 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700418 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700420 return INVALID_OPERATION;
421 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700422
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
jiabinc0048632023-04-27 22:04:31 +0000425 // Notify the HAL to prepare to disconnect device
426 broadcastDeviceConnectionState(
427 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
François Gaffie11d30102018-11-02 16:09:09 +0100429 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700430
431 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432
jiabinc0048632023-04-27 22:04:31 +0000433 // Set Disconnect to HALs
434 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
435
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436 // remove device from mReportedFormatsMap cache
437 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700438
439 // Propagate device availability to Engine
440 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700441 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700442
443 default:
François Gaffie11d30102018-11-02 16:09:09 +0100444 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return BAD_VALUE;
446 }
447
Eric Laurent0dd51852019-04-19 18:18:58 -0700448 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700449 // As the input device list can impact the output device selection, update
450 // getDeviceForStrategy() cache
451 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700452
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100453 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200454 // Reconnect Audio Source
455 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
456 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
457 checkAudioSourceForAttributes(attributes);
458 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700459 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100460 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700461 }
462
Eric Laurentb52c1522014-05-20 11:27:36 -0700463 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700465 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700466
François Gaffie11d30102018-11-02 16:09:09 +0100467 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700468 return BAD_VALUE;
469}
470
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100471status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
472 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800473 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700474 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
475 devDescr->setName(device_name);
476 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100477}
478
Eric Laurent736a1022019-03-27 18:28:46 -0700479void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
480 audio_policy_dev_state_t state) {
481
482 // the Engine does not have to know about remote submix devices used by dynamic audio policies
483 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
484 return;
485 }
486 mEngine->setDeviceConnectionState(device, state);
487}
488
489
Eric Laurente0720872014-03-11 09:30:41 -0700490audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100491 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700492{
Eric Laurent634b7142016-04-20 13:48:02 -0700493 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
495 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700496 (strlen(device_address) != 0)/*matchAddress*/);
497
498 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100499 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700500 device, device_address);
501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
502 }
François Gaffie53615e22015-03-19 09:24:12 +0100503
Eric Laurent3a4311c2014-03-17 12:00:47 -0700504 DeviceVector *deviceVector;
505
Eric Laurente552edb2014-03-10 17:42:56 -0700506 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700507 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700508 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 deviceVector = &mAvailableInputDevices;
510 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100511 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 }
Eric Laurent634b7142016-04-20 13:48:02 -0700514
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 return (deviceVector->getDevice(
516 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800518}
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
521 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 const char *device_name,
523 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
526 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800528 // connect/disconnect only 1 device at a time
529 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
530
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800531 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700532 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534 // Nothing to do: device is not connected
535 return NO_ERROR;
536 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800538
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700539 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 // configure codecs.
541 // Handle two specific cases by sending a set parameter to
542 // configure A2DP codecs. No need to toggle device state.
543 // Case 1: A2DP active device switches from primary to primary
544 // module
545 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100546 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700547 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
549 if (availablePrimaryOutputDevices().contains(devDesc) &&
550 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 bool isA2dp = audio_is_a2dp_out_device(device);
552 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
553 : String8(AudioParameter::keyReconfigLeSupported);
554 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800555 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 int isReconfigSupported;
557 repliedParameters.getInt(supportKey, isReconfigSupported);
558 if (isReconfigSupported) {
559 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
560 : String8(AudioParameter::keyReconfigLe);
561 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800562 param.add(key, String8("true"));
563 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
564 devDesc->setEncodedFormat(encodedFormat);
565 return NO_ERROR;
566 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700567 }
568 }
cnx421bd2dcc42020-07-11 14:58:44 +0800569 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000570 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800571 for (size_t i = 0; i < mOutputs.size(); i++) {
572 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000573 // mute media strategies to avoid sending the music tail into
574 // the earpiece or headset.
575 if (desc->isStrategyActive(musicStrategy)) {
576 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
577 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
578 tempRecommendedMuteDuration : desc->latency() * 4;
579 if (muteWaitMs < tempMuteDurationMs) {
580 muteWaitMs = tempMuteDurationMs;
581 }
582 }
cnx421bd2dcc42020-07-11 14:58:44 +0800583 setStrategyMute(musicStrategy, true, desc);
584 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
585 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
586 nullptr, true /*fromCache*/).types());
587 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000588 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
589 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
590 // happens after the actual device switch.
591 if (muteWaitMs > 0) {
592 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
593 usleep(muteWaitMs * 1000);
594 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800595 // Toggle the device state: UNAVAILABLE -> AVAILABLE
596 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100597 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800598 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800599 device_address, device_name,
600 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800601 if (status != NO_ERROR) {
602 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
603 status);
604 return status;
605 }
606
607 status = setDeviceConnectionState(device,
608 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800609 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800610 if (status != NO_ERROR) {
611 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
612 status);
613 return status;
614 }
615
616 return NO_ERROR;
617}
618
Pattydd807582021-11-04 21:01:03 +0800619status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
620 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800621{
Pattydd807582021-11-04 21:01:03 +0800622 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800623 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 std::unordered_set<audio_format_t> formatSet;
625 sp<HwModule> primaryModule =
626 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700627 if (primaryModule == nullptr) {
628 ALOGE("%s() unable to get primary module", __func__);
629 return NO_INIT;
630 }
Pattydd807582021-11-04 21:01:03 +0800631
632 DeviceTypeSet audioDeviceSet;
633
634 switch(device) {
635 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
636 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
637 break;
638 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800639 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
640 break;
641 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
642 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800643 break;
644 default:
645 ALOGE("%s() device type 0x%08x not supported", __func__, device);
646 return BAD_VALUE;
647 }
648
jiabin9a3361e2019-10-01 09:38:30 -0700649 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800650 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800651 for (const auto& device : declaredDevices) {
652 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800653 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800654 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800655 return status;
656}
657
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
659{
660 DeviceVector rxSinkdevices{};
661 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
662 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
663 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
664 auto rxSinkDevice = rxSinkdevices.itemAt(0);
665 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
666 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
667 // retrieve Rx Source device descriptor
668 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
669 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
670
671 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
672 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
673 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
674 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
675 return DeviceVector(rxSinkDevice);
676 }
677 }
678 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
679 // the device returned is not necessarily reachable via this output
680 // (filter later by setOutputDevices())
681 return getNewOutputDevices(mPrimaryOutput, fromCache);
682}
683
684status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
685{
François Gaffiedb1755b2023-09-01 11:50:35 +0200686 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100687 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
688 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
689 }
690 return INVALID_OPERATION;
691}
692
693status_t AudioPolicyManager::updateCallRoutingInternal(
694 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695{
696 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100697 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700698 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200699 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700700 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700702 }
François Gaffie11d30102018-11-02 16:09:09 +0100703
Francois Gaffie716e1432019-01-14 16:58:59 +0100704 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100705 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200706
707 disconnectTelephonyAudioSource(mCallRxSourceClient);
708 disconnectTelephonyAudioSource(mCallTxSourceClient);
709
710 if (rxDevices.isEmpty()) {
711 ALOGW("%s() no selected output device", __func__);
712 return INVALID_OPERATION;
713 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000714 if (txSourceDevice == nullptr) {
715 ALOGE("%s() selected input device not available", __func__);
716 return INVALID_OPERATION;
717 }
François Gaffiec005e562018-11-06 15:04:49 +0100718
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100719 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100720 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700721
François Gaffie9eb18552018-11-05 10:33:26 +0100722 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700723 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100724 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700725 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100726 // retrieve Rx Source and Tx Sink device descriptors
727 sp<DeviceDescriptor> rxSourceDevice =
728 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731 sp<DeviceDescriptor> txSinkDevice =
732 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
733 String8(),
734 AUDIO_FORMAT_DEFAULT);
735
736 // RX and TX Telephony device are declared by Primary Audio HAL
737 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
738 (telephonyRxModule->getHalVersionMajor() >= 3)) {
739 if (rxSourceDevice == 0 || txSinkDevice == 0) {
740 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100741 ALOGE("%s() no telephony Tx and/or RX device", __func__);
742 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100743 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100744 // createAudioPatchInternal now supports both HW / SW bridging
745 createRxPatch = true;
746 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100747 } else {
748 // If the RX device is on the primary HW module, then use legacy routing method for
749 // voice calls via setOutputDevice() on primary output.
750 // Otherwise, create two audio patches for TX and RX path.
751 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
752 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700753 // If the TX device is also on the primary HW module, setOutputDevice() will take care
754 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100755 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
756 (txSinkDevice != 0);
757 }
758 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
759 // Otherwise, create two audio patches for TX and RX path.
760 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200761 if (!hasPrimaryOutput()) {
762 ALOGW("%s() no primary output available", __func__);
763 return INVALID_OPERATION;
764 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530765 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700766 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200767 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800768 // If the TX device is on the primary HW module but RX device is
769 // on other HW module, SinkMetaData of telephony input should handle it
770 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700771 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700772 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100773 // terminate active capture if on the same HW module as the call TX source device
774 // FIXME: would be better to refine to only inputs whose profile connects to the
775 // call TX device but this information is not in the audio patch and logic here must be
776 // symmetric to the one in startInput()
777 for (const auto& activeDesc : mInputs.getActiveInputs()) {
778 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
779 closeActiveClients(activeDesc);
780 }
781 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800783 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100784 if (waitMs != nullptr) {
785 *waitMs = muteWaitMs;
786 }
787 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800788}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700789
Mikhail Naganov100f0122018-11-29 11:22:16 -0800790bool AudioPolicyManager::isDeviceOfModule(
791 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
792 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
793 if (module != 0) {
794 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
795 .indexOf(devDesc) != NAME_NOT_FOUND
796 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
797 .indexOf(devDesc) != NAME_NOT_FOUND;
798 }
799 return false;
800}
801
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200802void AudioPolicyManager::connectTelephonyRxAudioSource()
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805 const struct audio_port_config source = {
806 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
807 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
808 };
809 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100810
811 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
812 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
813 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
814 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200815 ALOGE_IF(mCallRxSourceClient == nullptr,
816 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200817}
818
Francois Gaffie601801d2021-06-22 13:27:39 +0200819void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 if (clientDesc == nullptr) {
822 return;
823 }
824 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
825 "%s error stopping audio source", __func__);
826 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200827}
828
829void AudioPolicyManager::connectTelephonyTxAudioSource(
830 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
831 uint32_t delayMs)
832{
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200834 if (srcDevice == nullptr || sinkDevice == nullptr) {
835 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
836 return;
837 }
838 PatchBuilder patchBuilder;
839 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
840 ALOGV("%s between source %s and sink %s", __func__,
841 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200843 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
844
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200845 struct audio_port_config source = {};
846 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100847 mCallTxSourceClient = new SourceClientDescriptor(
848 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
849 mCommunnicationStrategy, toVolumeSource(aa), true);
850 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
851
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
853 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
855 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200856 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
857 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200858 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200859 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200860}
861
Eric Laurente0720872014-03-11 09:30:41 -0700862void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700863{
864 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100865 // store previous phone state for management of sonification strategy below
866 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100867 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100868
869 if (mEngine->setPhoneState(state) != NO_ERROR) {
870 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700871 return;
872 }
François Gaffie2110e042015-03-24 08:41:51 +0100873 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700874 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700875 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700876 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800877 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700878 }
879
François Gaffie2110e042015-03-24 08:41:51 +0100880 /**
881 * Switching to or from incall state or switching between telephony and VoIP lead to force
882 * routing command.
883 */
Eric Laurent74b71512019-11-06 17:21:57 -0800884 bool force = ((isStateInCall(oldState) != isStateInCall(state))
885 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700886
887 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700888 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 int delayMs = 0;
891 if (isStateInCall(state)) {
892 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100893 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
894 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700896 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 // mute media and sonification strategies and delay device switch by the largest
898 // latency of any output where either strategy is active.
899 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100900 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
901 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
902 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700903 (delayMs < (int)desc->latency()*2)) {
904 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700905 }
François Gaffiec005e562018-11-06 15:04:49 +0100906 setStrategyMute(musicStrategy, true, desc);
907 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
908 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
909 nullptr, true /*fromCache*/).types());
910 setStrategyMute(sonificationStrategy, true, desc);
911 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
912 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
913 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700914 }
915 }
916
François Gaffiedb1755b2023-09-01 11:50:35 +0200917 if (state == AUDIO_MODE_IN_CALL) {
918 (void)updateCallRouting(false /*fromCache*/, delayMs);
919 } else {
920 if (oldState == AUDIO_MODE_IN_CALL) {
921 disconnectTelephonyAudioSource(mCallRxSourceClient);
922 disconnectTelephonyAudioSource(mCallTxSourceClient);
923 }
924 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100925 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
926 // force routing command to audio hardware when ending call
927 // even if no device change is needed
928 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
929 rxDevices = mPrimaryOutput->devices();
930 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530931 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700932 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700933 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700934
jiabin3ff8d7d2022-12-13 06:27:44 +0000935 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700936 // reevaluate routing on all outputs in case tracks have been started during the call
937 for (size_t i = 0; i < mOutputs.size(); i++) {
938 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100939 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000940 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
941 && desc->mPreferredAttrInfo != nullptr) {
942 // If the output is using preferred mixer attributes and the audio mode is not normal,
943 // the output need to reopen with default configuration.
944 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
945 continue;
946 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200947 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
948 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530949 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200950 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700951 }
952 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000953 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700954
Eric Laurent96d1dda2022-03-14 17:14:19 +0100955 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
956
Eric Laurente552edb2014-03-10 17:42:56 -0700957 if (isStateInCall(state)) {
958 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700959 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800960 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962
963 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100964 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
965 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700966}
967
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700968audio_mode_t AudioPolicyManager::getPhoneState() {
969 return mEngine->getPhoneState();
970}
971
Eric Laurente0720872014-03-11 09:30:41 -0700972void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100973 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700974{
François Gaffie2110e042015-03-24 08:41:51 +0100975 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700976 if (config == mEngine->getForceUse(usage)) {
977 return;
978 }
Eric Laurente552edb2014-03-10 17:42:56 -0700979
François Gaffie2110e042015-03-24 08:41:51 +0100980 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
981 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
982 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700983 }
François Gaffie2110e042015-03-24 08:41:51 +0100984 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
985 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
986 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700987
988 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700989 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800990
Eric Laurent22fcda22019-05-17 16:28:47 -0700991 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
992 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800993 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700994 }
995
Eric Laurentdc462862016-07-19 12:29:53 -0700996 //FIXME: workaround for truncated touch sounds
997 // to be removed when the problem is handled by system UI
998 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700999 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1000 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1001 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001002
1003 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001004 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001005}
1006
Eric Laurente0720872014-03-11 09:30:41 -07001007void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001008{
1009 ALOGV("setSystemProperty() property %s, value %s", property, value);
1010}
1011
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012// Find an MSD output profile compatible with the parameters passed.
1013// When "directOnly" is set, restrict search to profiles for direct outputs.
1014sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1015 const DeviceVector& devices,
1016 uint32_t samplingRate,
1017 audio_format_t format,
1018 audio_channel_mask_t channelMask,
1019 audio_output_flags_t flags,
1020 bool directOnly)
1021{
1022 flags = getRelevantFlags(flags, directOnly);
1023
1024 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1025 if (msdModule != nullptr) {
1026 // for the msd module check if there are patches to the output devices
1027 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1028 HwModuleCollection modules;
1029 modules.add(msdModule);
1030 return searchCompatibleProfileHwModules(
1031 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1032 flags, directOnly);
1033 }
1034 }
1035 return nullptr;
1036}
1037
Michael Chana94fbb22018-04-24 14:31:19 +10001038// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1039// search to profiles for direct outputs.
1040sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001041 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001042 uint32_t samplingRate,
1043 audio_format_t format,
1044 audio_channel_mask_t channelMask,
1045 audio_output_flags_t flags,
1046 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001047{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001048 flags = getRelevantFlags(flags, directOnly);
1049
1050 return searchCompatibleProfileHwModules(
1051 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1052}
1053
1054audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1055 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001056 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 // only retain flags that will drive the direct output profile selection
1058 // if explicitly requested
1059 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001060 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001061 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1062 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001063 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001064 return flags;
1065}
Eric Laurent861a6282015-05-18 15:40:16 -07001066
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1068 const HwModuleCollection& hwModules,
1069 const DeviceVector& devices,
1070 uint32_t samplingRate,
1071 audio_format_t format,
1072 audio_channel_mask_t channelMask,
1073 audio_output_flags_t flags,
1074 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001075 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001076 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001077 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001078 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 samplingRate, NULL /*updatedSamplingRate*/,
1080 format, NULL /*updatedFormat*/,
1081 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001082 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001083 continue;
1084 }
1085 // reject profiles not corresponding to a device currently available
1086 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1087 continue;
1088 }
1089 // reject profiles if connected device does not support codec
1090 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1091 continue;
1092 }
1093 if (!directOnly) {
1094 return curProfile;
1095 }
1096
1097 // when searching for direct outputs, if several profiles are compatible, give priority
1098 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001099 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001100 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001101 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001102 }
1103 profile = curProfile;
1104 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1105 break;
1106 }
Eric Laurente552edb2014-03-10 17:42:56 -07001107 }
1108 }
Eric Laurent861a6282015-05-18 15:40:16 -07001109 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001110}
1111
Eric Laurentfa0f6742021-08-17 18:39:44 +02001112sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001113 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114{
1115 for (const auto& hwModule : mHwModules) {
1116 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001117 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001118 continue;
1119 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001120 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001121 // reject profiles not corresponding to a device currently available
1122 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1123 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1124 continue;
1125 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001126 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1127 != devices.size()) {
1128 continue;
1129 }
1130 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001131 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1132 return curProfile;
1133 }
1134 }
1135 return nullptr;
1136}
1137
Eric Laurentf4e63452017-11-06 19:31:46 +00001138audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001139{
François Gaffiec005e562018-11-06 15:04:49 +01001140 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001141
1142 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1143 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1144 // format, flags, etc. This may result in some discrepancy for functions that utilize
1145 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1146 // and AudioSystem::getOutputSamplingRate().
1147
François Gaffie11d30102018-11-02 16:09:09 +01001148 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001149 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1150 if (stream == AUDIO_STREAM_MUSIC &&
1151 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1152 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1153 }
1154 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001155
François Gaffie11d30102018-11-02 16:09:09 +01001156 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1157 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001158 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001159}
1160
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1162 const audio_attributes_t *srcAttr,
1163 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001164{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001165 if (srcAttr != NULL) {
1166 if (!isValidAttributes(srcAttr)) {
1167 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1168 __func__,
1169 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1170 srcAttr->tags);
1171 return BAD_VALUE;
1172 }
1173 *dstAttr = *srcAttr;
1174 } else {
1175 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1176 ALOGE("%s: invalid stream type", __func__);
1177 return BAD_VALUE;
1178 }
François Gaffiec005e562018-11-06 15:04:49 +01001179 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001180 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001181
1182 // Only honor audibility enforced when required. The client will be
1183 // forced to reconnect if the forced usage changes.
1184 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001185 dstAttr->flags = static_cast<audio_flags_mask_t>(
1186 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001187 }
1188
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001189 return NO_ERROR;
1190}
1191
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192status_t AudioPolicyManager::getOutputForAttrInt(
1193 audio_attributes_t *resultAttr,
1194 audio_io_handle_t *output,
1195 audio_session_t session,
1196 const audio_attributes_t *attr,
1197 audio_stream_type_t *stream,
1198 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001199 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 audio_output_flags_t *flags,
1201 audio_port_handle_t *selectedDeviceId,
1202 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001204 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001205 bool *isSpatialized,
1206 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207{
François Gaffiec005e562018-11-06 15:04:49 +01001208 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001209 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001210 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001211 const sp<DeviceDescriptor> requestedDevice =
1212 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1213
Eric Laurent8a1095a2019-11-08 14:44:16 -08001214 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001215 *isSpatialized = false;
1216
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001217 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1218 if (status != NO_ERROR) {
1219 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001220 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001221 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001222 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001223 }
François Gaffiec005e562018-11-06 15:04:49 +01001224 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001225
François Gaffiec005e562018-11-06 15:04:49 +01001226 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1227 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001228
Oscar Azucena873d10f2023-01-12 18:34:42 -08001229 bool usePrimaryOutputFromPolicyMixes = false;
1230
Kevin Rocard153f92d2018-12-18 18:33:28 -08001231 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1232 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1233 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001235 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1236 .channel_mask = config->channel_mask,
1237 .format = config->format,
1238 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001239 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001240 mAvailableOutputDevices, requestedDevice, primaryMix,
1241 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001242 if (status != OK) {
1243 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001244 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001245
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001247 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1248 && !audio_is_linear_pcm(config->format)) {
1249 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 return BAD_VALUE;
1251 }
1252 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001253 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1255 primaryMix->mDeviceAddress,
1256 AUDIO_FORMAT_DEFAULT);
1257 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001258 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001259 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1260 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001261 // if a direct output can be opened to deliver the track's multi-channel content to the
1262 // output rather than being downmixed by the primary output, then use this direct
1263 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1264 // mix.
1265 bool tryDirectForChannelMask = policyDesc != nullptr
1266 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1267 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001268 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001269 audio_io_handle_t newOutput;
1270 status = openDirectOutput(
1271 *stream, session, config,
1272 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001273 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001274 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001275 policyDesc = mOutputs.valueFor(newOutput);
1276 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001277 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001278 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001279 policyDesc = nullptr;
1280 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 }
1282 if (policyDesc != nullptr) {
1283 policyDesc->mPolicyMix = primaryMix;
1284 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001285 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1286 : AUDIO_PORT_HANDLE_NONE;
1287 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1288 // Remove direct flag as it is not on a direct output.
1289 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1290 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001291
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001292 ALOGV("getOutputForAttr() returns output %d", *output);
1293 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1294 *outputType = API_OUT_MIX_PLAYBACK;
1295 } else {
1296 *outputType = API_OUTPUT_LEGACY;
1297 }
1298 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001299 } else {
1300 if (policyMixDevice != nullptr) {
1301 ALOGE("%s, try to use primary mix but no output found", __func__);
1302 return INVALID_OPERATION;
1303 }
1304 // Fallback to default engine selection as the selected primary mix device is not
1305 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001306 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001307 }
François Gaffiec005e562018-11-06 15:04:49 +01001308 // Virtual sources must always be dynamicaly or explicitly routed
1309 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1310 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1311 return BAD_VALUE;
1312 }
1313 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1314 // in order to let the choice of the order to future vendor engine
1315 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001316
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001317 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001318 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001319 }
1320
Nadav Barb2f18162018-07-18 13:01:53 +03001321 // Set incall music only if device was explicitly set, and fallback to the device which is
1322 // chosen by the engine if not.
1323 // FIXME: provide a more generic approach which is not device specific and move this back
1324 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001325 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001326 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001327 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001328 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001329 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001330 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001331 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001332 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001333 }
1334 }
1335
François Gaffiec005e562018-11-06 15:04:49 +01001336 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1337 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1338 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001339
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001340 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001341 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001342 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001343 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001344 ALOGV("%s() Using MSD devices %s instead of devices %s",
1345 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 } else {
1347 *output = AUDIO_IO_HANDLE_NONE;
1348 }
1349 }
1350 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001351 sp<PreferredMixerAttributesInfo> info = nullptr;
1352 if (outputDevices.size() == 1) {
1353 info = getPreferredMixerAttributesInfo(
1354 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001355 mEngine->getProductStrategyForAttributes(*resultAttr),
1356 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001357 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1358 // and it is currently active.
1359 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001360 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001361 info = nullptr;
1362 }
jiabin220eea12024-05-17 17:55:20 +00001363 if (com::android::media::audioserver::
1364 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1365 if (info != nullptr && info->getUid() == uid &&
1366 info->configMatches(*config) &&
1367 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1368 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1369 [this, &outputDevices](audio_usage_t usage) {
1370 return mOutputs.isUsageActiveOnDevice(
1371 usage, outputDevices[0]); }))) {
1372 // Bit-perfect request is not allowed when the phone mode is not normal or
1373 // there is any higher priority user case active.
1374 return INVALID_OPERATION;
1375 }
1376 }
jiabina84c3d32022-12-02 18:59:55 +00001377 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001378 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001379 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001380 // The client will be active if the client is currently preferred mixer owner and the
1381 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001382 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001383 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001384 && info->getUid() == uid
1385 && *output != AUDIO_IO_HANDLE_NONE
1386 // When bit-perfect output is selected for the preferred mixer attributes owner,
1387 // only need to consider the config matches.
1388 && mOutputs.valueFor(*output)->isConfigurationMatched(
1389 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001390
1391 if (*isBitPerfect) {
1392 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1393 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001394 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001395 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001396 AudioProfileVector profiles;
1397 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1398 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001399 const auto channels = profiles[0]->getChannels();
1400 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1401 config->channel_mask = *channels.begin();
1402 }
1403 const auto sampleRates = profiles[0]->getSampleRates();
1404 if (!sampleRates.empty() &&
1405 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1406 config->sample_rate = *sampleRates.begin();
1407 }
jiabinf1c73972022-04-14 16:28:52 -07001408 config->format = profiles[0]->getFormat();
1409 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001410 return INVALID_OPERATION;
1411 }
Paul McLeanaa981192015-03-21 09:55:15 -07001412
François Gaffiec005e562018-11-06 15:04:49 +01001413 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001414 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001415 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001416 *selectedDeviceId = outputDevice->getId();
1417 break;
1418 }
1419 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001420
Eric Laurent8a1095a2019-11-08 14:44:16 -08001421 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1422 *outputType = API_OUTPUT_TELEPHONY_TX;
1423 } else {
1424 *outputType = API_OUTPUT_LEGACY;
1425 }
1426
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1428
1429 return NO_ERROR;
1430}
1431
1432status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1433 audio_io_handle_t *output,
1434 audio_session_t session,
1435 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001436 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001437 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001438 audio_output_flags_t *flags,
1439 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001440 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001441 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001442 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001443 bool *isSpatialized,
1444 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001445{
1446 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1447 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1448 return INVALID_OPERATION;
1449 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001450 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001451 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001452 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001454 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001455 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001456 const sp<DeviceDescriptor> requestedDevice =
1457 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1458
1459 // Prevent from storing invalid requested device id in clients
1460 const audio_port_handle_t sanitizedRequestedPortId =
1461 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1462 *selectedDeviceId = sanitizedRequestedPortId;
1463
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001465 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001466 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1467 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001468 if (status != NO_ERROR) {
1469 return status;
1470 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001471 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001472 if (secondaryOutputs != nullptr) {
1473 for (auto &secondaryMix : secondaryMixes) {
1474 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1475 if (outputDesc != nullptr &&
1476 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1477 secondaryOutputs->push_back(outputDesc->mIoHandle);
1478 weakSecondaryOutputDescs.push_back(outputDesc);
1479 }
1480 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001481 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001482
Eric Laurent8fc147b2018-07-22 19:13:55 -07001483 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001484 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001485 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001486 };
jiabin4ef93452019-09-10 14:29:54 -07001487 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001488
Eric Laurentc209fe42020-06-05 18:11:23 -07001489 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001490 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001491 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001492 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001493 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001494 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001495 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001496 std::move(weakSecondaryOutputDescs),
1497 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001498 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001499
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001500 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1501 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001502
Eric Laurente83b55d2014-11-14 10:06:21 -08001503 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001504}
1505
Eric Laurentc529cf62020-04-17 18:19:10 -07001506status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1507 audio_session_t session,
1508 const audio_config_t *config,
1509 audio_output_flags_t flags,
1510 const DeviceVector &devices,
1511 audio_io_handle_t *output) {
1512
1513 *output = AUDIO_IO_HANDLE_NONE;
1514
1515 // skip direct output selection if the request can obviously be attached to a mixed output
1516 // and not explicitly requested
1517 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1518 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1519 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1520 return NAME_NOT_FOUND;
1521 }
1522
1523 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1524 // This prevents creating an offloaded track and tearing it down immediately after start
1525 // when audioflinger detects there is an active non offloadable effect.
1526 // FIXME: We should check the audio session here but we do not have it in this context.
1527 // This may prevent offloading in rare situations where effects are left active by apps
1528 // in the background.
1529 sp<IOProfile> profile;
1530 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1531 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1532 profile = getProfileForOutput(
1533 devices, config->sample_rate, config->format, config->channel_mask,
1534 flags, true /* directOnly */);
1535 }
1536
1537 if (profile == nullptr) {
1538 return NAME_NOT_FOUND;
1539 }
1540
1541 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1542 for (size_t i = 0; i < mOutputs.size(); i++) {
1543 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1544 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1545 // reuse direct output if currently open by the same client
1546 // and configured with same parameters
1547 if ((config->sample_rate == desc->getSamplingRate()) &&
1548 (config->format == desc->getFormat()) &&
1549 (config->channel_mask == desc->getChannelMask()) &&
1550 (session == desc->mDirectClientSession)) {
1551 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001552 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001553 mOutputs.keyAt(i), session);
1554 *output = mOutputs.keyAt(i);
1555 return NO_ERROR;
1556 }
1557 }
1558 }
1559
1560 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001561 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1562 return NAME_NOT_FOUND;
1563 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1564 // MMAP gracefully handles lack of an exclusive track resource by mixing
1565 // above the audio framework. For AAudio to know that the limit is reached,
1566 // return an error.
1567 return NAME_NOT_FOUND;
1568 } else {
1569 // Close outputs on this profile, if available, to free resources for this request
1570 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1571 const auto desc = mOutputs.valueAt(i);
1572 if (desc->mProfile == profile) {
1573 closeOutput(desc->mIoHandle);
1574 }
1575 }
1576 }
1577 }
1578
1579 // Unable to close streams to find free resources for this request
1580 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001581 return NAME_NOT_FOUND;
1582 }
1583
Atneya Nairb16666a2023-12-11 20:18:33 -08001584 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001585
Michael Chan6fb34492020-12-08 15:44:49 +11001586 // An MSD patch may be using the only output stream that can service this request. Release
1587 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001588 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001589
Eric Laurentf1f22e72021-07-13 14:04:14 +02001590 status_t status =
1591 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001592
1593 // only accept an output with the requested parameters
1594 if (status != NO_ERROR ||
1595 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1596 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1597 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1598 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1599 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1600 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1601 config->channel_mask, outputDesc->getChannelMask());
1602 if (*output != AUDIO_IO_HANDLE_NONE) {
1603 outputDesc->close();
1604 }
1605 // fall back to mixer output if possible when the direct output could not be open
1606 if (audio_is_linear_pcm(config->format) &&
1607 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1608 return NAME_NOT_FOUND;
1609 }
1610 *output = AUDIO_IO_HANDLE_NONE;
1611 return BAD_VALUE;
1612 }
1613 outputDesc->mDirectOpenCount = 1;
1614 outputDesc->mDirectClientSession = session;
1615
1616 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001617 setOutputDevices(__func__, outputDesc,
1618 devices,
1619 true,
1620 0,
1621 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001622 mPreviousOutputs = mOutputs;
1623 ALOGV("%s returns new direct output %d", __func__, *output);
1624 mpClientInterface->onAudioPortListUpdate();
1625 return NO_ERROR;
1626}
1627
François Gaffie11d30102018-11-02 16:09:09 +01001628audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1629 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001630 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001631 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001632 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001633 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001634 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001635 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001636 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001637{
Andy Hungc88b0642018-04-27 15:42:35 -07001638 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001639
jiabine375d412019-02-26 12:54:53 -08001640 // Discard haptic channel mask when forcing muting haptic channels.
1641 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001642 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1643 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001644
Eric Laurente552edb2014-03-10 17:42:56 -07001645 // open a direct output if required by specified parameters
1646 //force direct flag if offload flag is set: offloading implies a direct output stream
1647 // and all common behaviors are driven by checking only the direct flag
1648 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001649 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1650 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001651 }
Nadav Bar766fb022018-01-07 12:18:03 +02001652 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1653 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001654 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001655
1656 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1657
Eric Laurente83b55d2014-11-14 10:06:21 -08001658 // only allow deep buffering for music stream type
1659 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001660 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001661 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001662 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001663 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1664 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001665 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001666 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001667 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001668 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001669 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001670 audio_is_linear_pcm(config->format) &&
1671 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001672 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001673 AUDIO_OUTPUT_FLAG_DIRECT);
1674 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001675 }
Eric Laurente552edb2014-03-10 17:42:56 -07001676
Carter Hsua3abb402021-10-26 11:11:20 +08001677 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1678 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1679 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1680 }
1681
Eric Laurentf9230d52024-01-26 18:49:09 +01001682 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001683 // was specified and offload or direct playback is not explicitly requested, and there is no
1684 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001685 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001686 if (mSpatializerOutput != nullptr &&
1687 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1688 prefMixerConfigInfo == nullptr &&
1689 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1690 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001691 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001692 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001693 }
1694
Eric Laurentc529cf62020-04-17 18:19:10 -07001695 audio_config_t directConfig = *config;
1696 directConfig.channel_mask = channelMask;
1697 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1698 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001699 return output;
1700 }
1701
Eric Laurent14cbfca2016-03-17 09:42:16 -07001702 // A request for HW A/V sync cannot fallback to a mixed output because time
1703 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001704 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001705 return AUDIO_IO_HANDLE_NONE;
1706 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001707 // A request for Tuner cannot fallback to a mixed output
1708 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1709 return AUDIO_IO_HANDLE_NONE;
1710 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001711
Eric Laurente552edb2014-03-10 17:42:56 -07001712 // ignoring channel mask due to downmix capability in mixer
1713
1714 // open a non direct output
1715
1716 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001717 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001718 // get which output is suitable for the specified stream. The actual
1719 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001720 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001721 if (prefMixerConfigInfo != nullptr) {
1722 for (audio_io_handle_t outputHandle : outputs) {
1723 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1724 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1725 output = outputHandle;
1726 break;
1727 }
1728 }
1729 if (output == AUDIO_IO_HANDLE_NONE) {
1730 // No output open with the preferred profile. Open a new one.
1731 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1732 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1733 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1734 config.format = prefMixerConfigInfo->getConfigBase().format;
1735 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1736 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1737 &config, prefMixerConfigInfo->getFlags());
1738 if (preferredOutput == nullptr) {
1739 ALOGE("%s failed to open output with preferred mixer config", __func__);
1740 } else {
1741 output = preferredOutput->mIoHandle;
1742 }
1743 }
1744 } else {
1745 // at this stage we should ignore the DIRECT flag as no direct output could be
1746 // found earlier
1747 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001748 if (com::android::media::audioserver::
1749 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1750 // If the preferred mixer attributes is null, do not select the bit-perfect output
1751 // unless the bit-perfect output is the only output.
1752 // The bit-perfect output can exist while the passed in preferred mixer attributes
1753 // info is null when it is a high priority client. The high priority clients are
1754 // ringtone or alarm, which is not a bit-perfect use case.
1755 size_t i = 0;
1756 while (i < outputs.size() && outputs.size() > 1) {
1757 auto desc = mOutputs.valueFor(outputs[i]);
1758 // The output descriptor must not be null here.
1759 if (desc->isBitPerfect()) {
1760 outputs.removeItemsAt(i);
1761 } else {
1762 i += 1;
1763 }
1764 }
1765 }
jiabina84c3d32022-12-02 18:59:55 +00001766 output = selectOutput(
1767 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1768 }
Eric Laurente552edb2014-03-10 17:42:56 -07001769 }
François Gaffie11d30102018-11-02 16:09:09 +01001770 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001771 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001772 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001773
Eric Laurente552edb2014-03-10 17:42:56 -07001774 return output;
1775}
1776
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001777sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001778 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1779 mAvailableInputDevices);
1780 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1781}
1782
1783DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1784 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1785 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786}
1787
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001789 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001790 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1791 if (msdModule != 0) {
1792 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1793 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1794 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1795 const struct audio_port_config *source = &patch->mPatch.sources[j];
1796 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1797 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001798 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001799 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
1801 }
1802 }
1803 return msdPatches;
1804}
1805
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001806bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1807 ssize_t index = mAudioPatches.indexOfKey(handle);
1808 if (index < 0) {
1809 return false;
1810 }
1811 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1812 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1813 if (msdModule == nullptr) {
1814 return false;
1815 }
1816 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1817 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1818 return true;
1819 }
1820 index = getMsdOutputPatches().indexOfKey(handle);
1821 if (index < 0) {
1822 return false;
1823 }
1824 return true;
1825}
1826
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1828 const InputProfileCollection &inputProfiles,
1829 const OutputProfileCollection &outputProfiles,
1830 const sp<DeviceDescriptor> &sourceDevice,
1831 const sp<DeviceDescriptor> &sinkDevice,
1832 AudioProfileVector& sourceProfiles,
1833 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001834 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 return NO_INIT;
1837 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001838 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 return NO_INIT;
1841 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1844 inProfile->supportsDevice(sourceDevice)) {
1845 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001846 }
1847 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001849 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850 outProfile->supportsDevice(sinkDevice)) {
1851 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852 }
1853 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 return NO_ERROR;
1855}
1856
1857status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1858 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1859 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1860{
Dean Wheatley16809da2022-12-09 14:55:46 +11001861 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1862 static const std::vector<audio_format_t> formatsOrder = {{
1863 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001864 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1865 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001866 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1867 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1868 // preferred).
1869 std::vector<audio_channel_mask_t> masks = {{
1870 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1871 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1872 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1873 // insert index masks (higher counts most preferred) as preferred over position masks
1874 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1875 masks.insert(
1876 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1877 }
1878 return masks;
1879 }();
1880
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001882 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1883 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1886 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001887 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 }
1889 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1890 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1891 sinkConfig->format = bestSinkConfig.format;
1892 // For encoded streams force direct flag to prevent downstream mixing.
1893 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1894 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001895 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1896 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001898 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1899 // raw and IEC61937 framed streams.
1900 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1901 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1902 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1904 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001905 sourceConfig->channel_mask =
1906 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1907 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1908 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001909 sourceConfig->format = bestSinkConfig.format;
1910 // Copy input stream directly without any processing (e.g. resampling).
1911 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1912 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1913 if (hwAvSync) {
1914 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1915 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1916 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1917 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1918 }
1919 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1920 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1921 sinkConfig->config_mask |= config_mask;
1922 sourceConfig->config_mask |= config_mask;
1923 return NO_ERROR;
1924}
1925
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1927 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001928{
1929 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001930 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1931 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1932 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1933 if (deviceModule == nullptr) {
1934 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1935 return patchBuilder;
1936 }
1937 const InputProfileCollection inputProfiles = msdIsSource ?
1938 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1939 const OutputProfileCollection outputProfiles = msdIsSource ?
1940 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1941
1942 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1943 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1944 device : getMsdAudioOutDevices().itemAt(0);
1945 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1946
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1948 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001949 AudioProfileVector sourceProfiles;
1950 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1952 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 for (auto hwAvSync : { true, false }) {
1954 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1955 sourceProfiles, sinkProfiles) != NO_ERROR) {
1956 continue;
1957 }
1958 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1959 &sinkConfig) == NO_ERROR) {
1960 // Found a matching config. Re-create PatchBuilder with this config.
1961 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001964 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001965 " supporting PCM format conversion.", __func__);
1966 return patchBuilder;
1967}
1968
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001969status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001970 DeviceVector devices;
1971 if (outputDevices != nullptr && outputDevices->size() > 0) {
1972 devices.add(*outputDevices);
1973 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001974 // Use media strategy for unspecified output device. This should only
1975 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1976 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001977 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001978 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001979 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001980 }
Michael Chan6fb34492020-12-08 15:44:49 +11001981 std::vector<PatchBuilder> patchesToCreate;
1982 for (auto i = 0u; i < devices.size(); ++i) {
1983 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001984 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001985 }
1986 // Retain only the MSD patches associated with outputDevices request.
1987 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001988 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001989 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1990 auto retainedPatch = false;
1991 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1992 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1993 patchesToRemove.removeItemsAt(i);
1994 retainedPatch = true;
1995 break;
1996 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001997 }
Michael Chan6fb34492020-12-08 15:44:49 +11001998 if (retainedPatch) {
1999 it = patchesToCreate.erase(it);
2000 continue;
2001 }
2002 ++it;
2003 }
2004 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2005 return NO_ERROR;
2006 }
2007 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2008 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002009 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 }
Michael Chan6fb34492020-12-08 15:44:49 +11002011 status_t status = NO_ERROR;
2012 for (const auto &p : patchesToCreate) {
2013 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2014 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2015 char message[256];
2016 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2017 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2018 currStatus == NO_ERROR ? "Success" : "Error",
2019 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2020 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2021 if (currStatus == NO_ERROR) {
2022 ALOGD("%s", message);
2023 } else {
2024 ALOGE("%s", message);
2025 if (status == NO_ERROR) {
2026 status = currStatus;
2027 }
2028 }
2029 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002030 return status;
2031}
2032
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002033void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2034 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002035 for (size_t i = 0; i < msdPatches.size(); i++) {
2036 const auto& patch = msdPatches[i];
2037 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2038 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2039 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2040 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2041 releaseAudioPatch(patch->getHandle(), mUidCached);
2042 break;
2043 }
2044 }
2045 }
2046}
2047
Dorin Drimus94d94412022-02-02 09:05:02 +01002048bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002049 DeviceVector devicesToCheck =
2050 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002051 AudioPatchCollection msdPatches = getMsdOutputPatches();
2052 for (size_t i = 0; i < msdPatches.size(); i++) {
2053 const auto& patch = msdPatches[i];
2054 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2055 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2056 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2057 const auto& foundDevice = devicesToCheck.getDevice(
2058 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2059 if (foundDevice != nullptr) {
2060 devicesToCheck.remove(foundDevice);
2061 if (devicesToCheck.isEmpty()) {
2062 return true;
2063 }
2064 }
2065 }
2066 }
2067 }
2068 return false;
2069}
2070
Eric Laurente0720872014-03-11 09:30:41 -07002071audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002072 audio_output_flags_t flags,
2073 audio_format_t format,
2074 audio_channel_mask_t channelMask,
2075 uint32_t samplingRate,
2076 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002077{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2079 "%s called with format %#x", __func__, format);
2080
jiabinebb6af42020-06-09 17:31:17 -07002081 // Return the output that haptic-generating attached to when 1) session id is specified,
2082 // 2) haptic-generating effect exists for given session id and 3) the output that
2083 // haptic-generating effect attached to is in given outputs.
2084 if (sessionId != AUDIO_SESSION_NONE) {
2085 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2086 sessionId, FX_IID_HAPTICGENERATOR);
2087 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2088 return hapticGeneratingOutput;
2089 }
2090 }
2091
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 // Flags disqualifying an output: the match must happen before calling selectOutput()
2093 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2094 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2095
2096 // Flags expressing a functional request: must be honored in priority over
2097 // other criteria
2098 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2099 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002100 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2101 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 // Flags expressing a performance request: have lower priority than serving
2103 // requested sampling rate or channel mask
2104 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2105 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2106 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2107
2108 const audio_output_flags_t functionalFlags =
2109 (audio_output_flags_t)(flags & kFunctionalFlags);
2110 const audio_output_flags_t performanceFlags =
2111 (audio_output_flags_t)(flags & kPerformanceFlags);
2112
2113 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2114
Eric Laurente552edb2014-03-10 17:42:56 -07002115 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002116 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002117 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002118 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002119 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002120 // with tiebreak preferring the minimum number of extra functional flags
2121 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002122 // 3: the output supporting the exact channel mask
2123 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002124 // 5: the output with the highest sampling rate if the requested sample rate is
2125 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 // 6: the output with the highest number of requested performance flags
2127 // 7: the output with the bit depth the closest to the requested one
2128 // 8: the primary output
2129 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002130
Eric Laurent16c66dd2019-05-01 17:54:10 -07002131 // matching criteria values in priority order for best matching output so far
2132 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002134 const bool hasOrphanHaptic =
2135 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002136 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2137 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2138 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002139
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002140 for (audio_io_handle_t output : outputs) {
2141 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002142 // matching criteria values in priority order for current output
2143 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002144
Eric Laurent16c66dd2019-05-01 17:54:10 -07002145 if (outputDesc->isDuplicated()) {
2146 continue;
2147 }
2148 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2149 continue;
2150 }
Eric Laurent8838a382014-09-08 16:44:28 -07002151
Eric Laurent16c66dd2019-05-01 17:54:10 -07002152 // If haptic channel is specified, use the haptic output if present.
2153 // When using haptic output, same audio format and sample rate are required.
2154 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002155 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002156 // skip if haptic channel specified but output does not support it, or output support haptic
2157 // but there is no haptic channel requested AND no orphan haptic effect exist
2158 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2159 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002160 continue;
2161 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002162 // In the case of audio-coupled-haptic playback, there is no format conversion and
2163 // resampling in the framework, same format/channel/sampleRate for client and the output
2164 // thread is required. In the case of HapticGenerator effect, do not require format
2165 // matching.
2166 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2167 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002168 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002169 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002170 }
2171
2172 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002173 const int matchingFunctionalFlags =
2174 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2175 const int totalFunctionalFlags =
2176 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2177 // Prefer matching functional flags, but subtract unnecessary functional flags.
2178 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179
2180 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002181 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2182 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2184 channelCount <= outputChannelCount) {
2185 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002186 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2187 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002189 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 currentMatchCriteria[3] = outputChannelCount;
2191 }
2192
2193 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002194 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002195 int diff; // avoid unsigned integer overflow.
2196 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2197
2198 // prefer the closest output sampling rate greater than or equal to target
2199 // if none exists, prefer the closest output sampling rate less than target.
2200 //
2201 // criteria is offset to make non-negative.
2202 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 }
2204
2205 // performance flags match
2206 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2207
2208 // format match
2209 if (format != AUDIO_FORMAT_INVALID) {
2210 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002211 PolicyAudioPort::kFormatDistanceMax -
2212 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002213 }
2214
2215 // primary output match
2216 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2217
2218 // compare match criteria by priority then value
2219 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2220 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2221 bestMatchCriteria = currentMatchCriteria;
2222 bestOutput = output;
2223
2224 std::stringstream result;
2225 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2226 std::ostream_iterator<int>(result, " "));
2227 ALOGV("%s new bestOutput %d criteria %s",
2228 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002229 }
2230 }
2231
Eric Laurent16c66dd2019-05-01 17:54:10 -07002232 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002233}
2234
Eric Laurent8fc147b2018-07-22 19:13:55 -07002235status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002236{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002237 ALOGV("%s portId %d", __FUNCTION__, portId);
2238
2239 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2240 if (outputDesc == 0) {
2241 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002242 return BAD_VALUE;
2243 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002244 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Eric Laurent8fc147b2018-07-22 19:13:55 -07002246 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002247 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002248
jiabin220eea12024-05-17 17:55:20 +00002249 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2250 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2251 && outputDesc->isBitPerfect()) {
2252 // Usually, APM selects bit-perfect output for high priority use cases only when
2253 // bit-perfect output is the only output that can be routed to the selected device.
2254 // However, here is no need to play high priority use cases such as ringtone and alarm
2255 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2256 // can attach to new output.
2257 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2258 __func__, client->stream());
2259 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2260 return DEAD_OBJECT;
2261 }
2262
Eric Laurent733ce942017-12-07 12:18:25 -08002263 status_t status = outputDesc->start();
2264 if (status != NO_ERROR) {
2265 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002266 }
2267
Eric Laurent97ac8712018-07-27 18:59:02 -07002268 uint32_t delayMs;
2269 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002270
2271 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002272 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002273 if (status == DEAD_OBJECT) {
2274 sp<SwAudioOutputDescriptor> desc =
2275 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2276 if (desc == nullptr) {
2277 // This is not common, it may indicate something wrong with the HAL.
2278 ALOGE("%s unable to open output with default config", __func__);
2279 return status;
2280 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002281 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002282 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002283 }
jiabina84c3d32022-12-02 18:59:55 +00002284
2285 // If the client is the first one active on preferred mixer parameters, reopen the output
2286 // if the current mixer parameters doesn't match the preferred one.
2287 if (outputDesc->devices().size() == 1) {
2288 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2289 outputDesc->devices()[0]->getId(), client->strategy());
2290 if (info != nullptr && info->getUid() == client->uid()) {
2291 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2292 info->getConfigBase(), info->getFlags())) {
2293 stopSource(outputDesc, client);
2294 outputDesc->stop();
2295 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2296 config.channel_mask = info->getConfigBase().channel_mask;
2297 config.sample_rate = info->getConfigBase().sample_rate;
2298 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002299 sp<SwAudioOutputDescriptor> desc =
2300 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2301 if (desc == nullptr) {
2302 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002303 }
jiabin220eea12024-05-17 17:55:20 +00002304 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002305 // Intentionally return error to let the client side resending request for
2306 // creating and starting.
2307 return DEAD_OBJECT;
2308 }
2309 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002310 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002311 // If it is first bit-perfect client, reroute all clients that will be routed to
2312 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2313 PortHandleVector clientsToInvalidate;
2314 for (size_t i = 0; i < mOutputs.size(); i++) {
2315 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002316 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002317 continue;
2318 }
2319 for (const auto& c : mOutputs[i]->getClientIterable()) {
2320 clientsToInvalidate.push_back(c->portId());
2321 }
2322 }
2323 if (!clientsToInvalidate.empty()) {
2324 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2325 __func__);
2326 mpClientInterface->invalidateTracks(clientsToInvalidate);
2327 }
2328 }
jiabina84c3d32022-12-02 18:59:55 +00002329 }
2330 }
2331
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002332 if (client->hasPreferredDevice()) {
2333 // playback activity with preferred device impacts routing occurred, inform upper layers
2334 mpClientInterface->onRoutingUpdated();
2335 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002336 if (delayMs != 0) {
2337 usleep(delayMs * 1000);
2338 }
2339
jiabin220eea12024-05-17 17:55:20 +00002340 if (status == NO_ERROR &&
2341 outputDesc->mPreferredAttrInfo != nullptr &&
2342 outputDesc->isBitPerfect() &&
2343 com::android::media::audioserver::
2344 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2345 // A new client is started on bit-perfect output, update all clients internal mute.
2346 updateClientsInternalMute(outputDesc);
2347 }
2348
Eric Laurentc75307b2015-03-17 15:29:32 -07002349 return status;
2350}
2351
Eric Laurent96d1dda2022-03-14 17:14:19 +01002352bool AudioPolicyManager::isLeUnicastActive() const {
2353 if (isInCall()) {
2354 return true;
2355 }
2356 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2357}
2358
2359bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2360 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2361 return false;
2362 }
2363 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2364 ALOGV("%s active %d", __func__, active);
2365 return active;
2366}
2367
Eric Laurent97ac8712018-07-27 18:59:02 -07002368status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2369 const sp<TrackClientDescriptor>& client,
2370 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002371{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002372 // cannot start playback of STREAM_TTS if any other output is being used
2373 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002374
2375 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002376 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002377 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002378 auto clientStrategy = client->strategy();
2379 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002380 if (stream == AUDIO_STREAM_TTS) {
2381 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002382 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002383 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002384 return INVALID_OPERATION;
2385 } else {
2386 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2387 }
2388 } else {
2389 // some playback other than beacon starts
2390 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2391 }
2392
Eric Laurent77305a62016-07-25 16:39:22 -07002393 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002394 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002395 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002396
François Gaffie11d30102018-11-02 16:09:09 +01002397 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002398 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002399 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002400 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002401 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002402 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002403 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002404 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002405 } else {
2406 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002407 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002408 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2409 AUDIO_FORMAT_DEFAULT);
2410 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2411 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002412 }
2413
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002414 // requiresMuteCheck is false when we can bypass mute strategy.
2415 // It covers a common case when there is no materially active audio
2416 // and muting would result in unnecessary delay and dropped audio.
2417 const uint32_t outputLatencyMs = outputDesc->latency();
2418 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002419 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002420
Eric Laurente552edb2014-03-10 17:42:56 -07002421 // increment usage count for this stream on the requested output:
2422 // NOTE that the usage count is the same for duplicated output and hardware output which is
2423 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002424 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002425
2426 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002427 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002428 // Preferred device may be exclusive, use only if no other active clients on this output
2429 devices = DeviceVector(
2430 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2431 } else {
2432 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2433 }
François Gaffie11d30102018-11-02 16:09:09 +01002434 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002435 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002436 }
2437 }
Eric Laurente552edb2014-03-10 17:42:56 -07002438
François Gaffiec005e562018-11-06 15:04:49 +01002439 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002440 selectOutputForMusicEffects();
2441 }
2442
François Gaffie1c878552018-11-22 16:53:21 +01002443 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002444 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002445 if (devices.isEmpty()) {
2446 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002447 }
François Gaffiec005e562018-11-06 15:04:49 +01002448 bool shouldWait =
2449 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2450 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2451 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002452 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002453 const bool needToCloseBitPerfectOutput =
2454 (com::android::media::audioserver::
2455 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2456 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2457 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002458 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002460 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461 // An output has a shared device if
2462 // - managed by the same hw module
2463 // - supports the currently selected device
2464 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002465 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002466
Eric Laurent77305a62016-07-25 16:39:22 -07002467 // force a device change if any other output is:
2468 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002469 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002470 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002471 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002472 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002473 // change the device currently selected by the other output.
2474 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002475 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002476 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002477 force = true;
2478 }
2479 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002480 // a notification so that audio focus effect can propagate, or that a mute/unmute
2481 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002482 const uint32_t latencyMs = desc->latency();
2483 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2484
2485 if (shouldWait && isActive && (waitMs < latencyMs)) {
2486 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002487 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002488
2489 // Require mute check if another output is on a shared device
2490 // and currently active to have proper drain and avoid pops.
2491 // Note restoring AudioTracks onto this output needs to invoke
2492 // a volume ramp if there is no mute.
2493 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002494
2495 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2496 outputsToReopen.push_back(desc);
2497 }
Eric Laurente552edb2014-03-10 17:42:56 -07002498 }
2499 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002500
jiabin220eea12024-05-17 17:55:20 +00002501 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002502 // If the output is open with preferred mixer attributes, but the routed device is
2503 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2504 // changed.
2505 return DEAD_OBJECT;
2506 }
jiabin220eea12024-05-17 17:55:20 +00002507 for (auto& outputToReopen : outputsToReopen) {
2508 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2509 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002510 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302511 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2512 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002513
Eric Laurente552edb2014-03-10 17:42:56 -07002514 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002515 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002516 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002517 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002518 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002519 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002520 outputDesc->useHwGain() /*force*/)) {
2521 // request AudioService to reinitialize the volume curves asynchronously
2522 ALOGE("checkAndSetVolume failed, requesting volume range init");
2523 mpClientInterface->onVolumeRangeInitRequest();
2524 };
Eric Laurente552edb2014-03-10 17:42:56 -07002525
2526 // update the outputs if starting an output with a stream that can affect notification
2527 // routing
2528 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002529
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002530 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002531 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002532 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002533 }
Eric Laurentdc462862016-07-19 12:29:53 -07002534
2535 if (waitMs > muteWaitMs) {
2536 *delayMs = waitMs - muteWaitMs;
2537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538
2539 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2540 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2541 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2542 // change occurs after the MixerThread starts and causes a stream volume
2543 // glitch.
2544 //
2545 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002546 }
Eric Laurentdc462862016-07-19 12:29:53 -07002547
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002548 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002549 mEngine->getForceUse(
2550 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002551 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002552 }
2553
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 // Automatically enable the remote submix input when output is started on a re routing mix
2555 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002556 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2557 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2559 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2560 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002561 "remote-submix",
2562 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002563 }
2564
Eric Laurent96d1dda2022-03-14 17:14:19 +01002565 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2566
Eric Laurente552edb2014-03-10 17:42:56 -07002567 return NO_ERROR;
2568}
2569
Eric Laurent96d1dda2022-03-14 17:14:19 +01002570void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2571 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2572 bool isUnicastActive = isLeUnicastActive();
2573
2574 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002575 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002576 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2577 for (size_t i = 0; i < mOutputs.size(); i++) {
2578 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2579 if (desc != ignoredOutput && desc->isActive()
2580 && ((isUnicastActive &&
2581 !desc->devices().
2582 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2583 || (wasUnicastActive &&
2584 !desc->devices().getDevicesFromTypes(
2585 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2586 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2587 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002588 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002589 // If the device is using preferred mixer attributes, the output need to reopen
2590 // with default configuration when the new selected devices are different from
2591 // current routing devices.
2592 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2593 continue;
2594 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302595 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002596 // re-apply device specific volume if not done by setOutputDevice()
2597 if (!force) {
2598 applyStreamVolumes(desc, newDevices.types(), delayMs);
2599 }
2600 }
2601 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002602 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002603 }
2604}
2605
Eric Laurent8fc147b2018-07-22 19:13:55 -07002606status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002607{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002608 ALOGV("%s portId %d", __FUNCTION__, portId);
2609
2610 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2611 if (outputDesc == 0) {
2612 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 return BAD_VALUE;
2614 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002615 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002616
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002617 if (client->hasPreferredDevice(true)) {
2618 // playback activity with preferred device impacts routing occurred, inform upper layers
2619 mpClientInterface->onRoutingUpdated();
2620 }
2621
Eric Laurent97ac8712018-07-27 18:59:02 -07002622 ALOGV("stopOutput() output %d, stream %d, session %d",
2623 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002624
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002626
Eric Laurent733ce942017-12-07 12:18:25 -08002627 if (status == NO_ERROR ) {
2628 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002629 } else {
2630 return status;
2631 }
2632
2633 if (outputDesc->devices().size() == 1) {
2634 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2635 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002636 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002637 if (info != nullptr && info->getUid() == client->uid()) {
2638 info->decreaseActiveClient();
2639 if (info->getActiveClientCount() == 0) {
2640 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002641 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002642 }
2643 }
jiabin220eea12024-05-17 17:55:20 +00002644 if (com::android::media::audioserver::
2645 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2646 !outputReopened && outputDesc->isBitPerfect()) {
2647 // Only need to update the clients' internal mute when the output is bit-perfect and it
2648 // is not reopened.
2649 updateClientsInternalMute(outputDesc);
2650 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002651 }
2652 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002653}
2654
Eric Laurent97ac8712018-07-27 18:59:02 -07002655status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2656 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002657{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002658 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002659 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002660 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002661 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002662
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002663 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2664
François Gaffie1c878552018-11-22 16:53:21 +01002665 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2666 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002667 // Automatically disable the remote submix input when output is stopped on a
2668 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002669 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002670 if (isSingleDeviceType(
2671 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002672 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002673 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002674 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2675 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002676 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002677 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002678 }
2679 }
2680 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002681 if (client->hasPreferredDevice(true) &&
2682 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002683 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002684 forceDeviceUpdate = true;
2685 }
2686
Eric Laurente552edb2014-03-10 17:42:56 -07002687 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002688 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002689
Eric Laurente552edb2014-03-10 17:42:56 -07002690 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002691 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002692 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002693 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002694
2695 // If the routing does not change, if an output is routed on a device using HwGain
2696 // (aka setAudioPortConfig) and there are still active clients following different
2697 // volume group(s), force reapply volume
2698 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2699 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2700
Eric Laurente552edb2014-03-10 17:42:56 -07002701 // delay the device switch by twice the latency because stopOutput() is executed when
2702 // the track stop() command is received and at that time the audio track buffer can
2703 // still contain data that needs to be drained. The latency only covers the audio HAL
2704 // and kernel buffers. Also the latency does not always include additional delay in the
2705 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302706 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002707 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002708
2709 // force restoring the device selection on other active outputs if it differs from the
2710 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002711 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002712 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002713 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002714 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002715 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002716 desc->isActive() &&
2717 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002718 (newDevices != desc->devices())) {
2719 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2720 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002721
jiabin220eea12024-05-17 17:55:20 +00002722 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002723 // If the device is using preferred mixer attributes, the output need to
2724 // reopen with default configuration when the new selected devices are
2725 // different from current routing devices.
2726 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2727 continue;
2728 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302729 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002730
Eric Laurent57de36c2016-09-28 16:59:11 -07002731 // re-apply device specific volume if not done by setOutputDevice()
2732 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002733 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002734 }
Eric Laurente552edb2014-03-10 17:42:56 -07002735 }
2736 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002737 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002738 // update the outputs if stopping one with a stream that can affect notification routing
2739 handleNotificationRoutingForStream(stream);
2740 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002741
2742 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2743 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002744 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002745 }
2746
François Gaffiec005e562018-11-06 15:04:49 +01002747 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002748 selectOutputForMusicEffects();
2749 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002750
2751 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2752
Eric Laurente552edb2014-03-10 17:42:56 -07002753 return NO_ERROR;
2754 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002755 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002756 return INVALID_OPERATION;
2757 }
2758}
2759
jiabinbce0c1d2020-10-05 11:20:18 -07002760bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002761{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002762 ALOGV("%s portId %d", __FUNCTION__, portId);
2763
2764 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2765 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002766 // If an output descriptor is closed due to a device routing change,
2767 // then there are race conditions with releaseOutput from tracks
2768 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2769 // destroyed shortly thereafter.
2770 //
2771 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002772 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002773 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002774 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002775
2776 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002777
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302778 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2779 if (outputDesc->isClientActive(client)) {
2780 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2781 stopOutput(portId);
2782 }
2783
Eric Laurent8fc147b2018-07-22 19:13:55 -07002784 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2785 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002786 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002787 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002788 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002789 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002790 if (--outputDesc->mDirectOpenCount == 0) {
2791 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002792 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002793 }
2794 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302795
Andy Hung39efb7a2018-09-26 15:39:28 -07002796 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002797 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2798 // The output is pending reopened to query dynamic profiles and
2799 // there is no active clients
2800 closeOutput(outputDesc->mIoHandle);
2801 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2802 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2803 if (newOutputDesc == nullptr) {
2804 ALOGE("%s failed to open output", __func__);
2805 }
2806 return true;
2807 }
2808 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002809}
2810
Eric Laurentcaf7f482014-11-25 17:50:47 -08002811status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2812 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002813 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002814 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002815 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002816 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002817 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002818 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002819 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002820 audio_port_handle_t *portId,
2821 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002822{
François Gaffiec005e562018-11-06 15:04:49 +01002823 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002824 "flags %#x attributes=%s requested device ID %d",
2825 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2826 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002827
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002829 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002830 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002831 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002833 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 sp<RecordClientDescriptor> clientDesc;
2835 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002836 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002838
2839 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2840 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2841 return INVALID_OPERATION;
2842 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002843
Francois Gaffie716e1432019-01-14 16:58:59 +01002844 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2845 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002846 }
2847
Paul McLean466dc8e2015-04-17 13:15:36 -06002848 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002849 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002850 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002851
Eric Laurentad2e7b92017-09-14 20:06:42 -07002852 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2853 // possible
2854 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2855 *input != AUDIO_IO_HANDLE_NONE) {
2856 ssize_t index = mInputs.indexOfKey(*input);
2857 if (index < 0) {
2858 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2859 status = BAD_VALUE;
2860 goto error;
2861 }
2862 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002863 RecordClientVector clients = inputDesc->getClientsForSession(session);
2864 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002865 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2866 status = BAD_VALUE;
2867 goto error;
2868 }
2869 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2870 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002871 // corresponds to a new client and is only permitted from the same UID.
2872 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 if (clients.size() > 1) {
2874 for (const auto& client : clients) {
2875 // The client map is ordered by key values (portId) and portIds are allocated
2876 // incrementaly. So the first client in this list is the one opened by audio flinger
2877 // when the mmap stream is created and should be ignored as it does not correspond
2878 // to an actual client
2879 if (client == *clients.cbegin()) {
2880 continue;
2881 }
2882 if (uid != client->uid() && !client->isSilenced()) {
2883 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2884 uid, client->portId(), client->uid());
2885 status = INVALID_OPERATION;
2886 goto error;
2887 }
Eric Laurent331679c2018-04-16 17:03:16 -07002888 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002889 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002890 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002891 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002892
Eric Laurentfecbceb2021-02-09 14:46:43 +01002893 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002895 }
2896
2897 *input = AUDIO_IO_HANDLE_NONE;
2898 *inputType = API_INPUT_INVALID;
2899
Francois Gaffie716e1432019-01-14 16:58:59 +01002900 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002901 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002902 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002903 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002904 ALOGW("%s could not find input mix for attr %s",
2905 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002907 }
jiabinc1de2df2019-05-07 14:26:40 -07002908 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2909 String8(attr->tags + strlen("addr=")),
2910 AUDIO_FORMAT_DEFAULT);
2911 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002912 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002913 __func__, attributes.source, attributes.tags);
2914 status = BAD_VALUE;
2915 goto error;
2916 }
2917
Kevin Rocard25f9b052019-02-27 15:08:54 -08002918 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2919 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2920 } else {
2921 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2922 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002923 if (virtualDeviceId) {
2924 *virtualDeviceId = policyMix->mVirtualDeviceId;
2925 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002926 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002927 if (explicitRoutingDevice != nullptr) {
2928 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002929 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002930 // Prevent from storing invalid requested device id in clients
2931 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002932 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002933 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2934 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002935 }
François Gaffie11d30102018-11-02 16:09:09 +01002936 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002937 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002938 status = BAD_VALUE;
2939 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002940 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002941 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2942 *inputType = API_INPUT_MIX_CAPTURE;
2943 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002944 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2945 // there is an external policy, but this input is attached to a mix of recorders,
2946 // meaning it receives audio injected into the framework, so the recorder doesn't
2947 // know about it and is therefore considered "legacy"
2948 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002949
2950 if (virtualDeviceId) {
2951 *virtualDeviceId = policyMix->mVirtualDeviceId;
2952 }
François Gaffie11d30102018-11-02 16:09:09 +01002953 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002954 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002955 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002956 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002957 } else {
2958 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002959 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002960
Eric Laurent599c7582015-12-07 18:05:55 -08002961 }
2962
François Gaffiec005e562018-11-06 15:04:49 +01002963 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002964 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002965 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002966 AudioProfileVector profiles;
2967 status_t ret = getProfilesForDevices(
2968 DeviceVector(device), profiles, flags, true /*isInput*/);
2969 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002970 const auto channels = profiles[0]->getChannels();
2971 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2972 config->channel_mask = *channels.begin();
2973 }
2974 const auto sampleRates = profiles[0]->getSampleRates();
2975 if (!sampleRates.empty() &&
2976 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2977 config->sample_rate = *sampleRates.begin();
2978 }
jiabinf1c73972022-04-14 16:28:52 -07002979 config->format = profiles[0]->getFormat();
2980 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002981 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002982 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002983
Marvin Ramine5a122d2023-12-07 13:57:59 +01002984
2985 if (policyMix != nullptr && virtualDeviceId != nullptr) {
2986 *virtualDeviceId = policyMix->mVirtualDeviceId;
2987 }
2988
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989exit:
2990
François Gaffiec005e562018-11-06 15:04:49 +01002991 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2992 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002993
Francois Gaffie716e1432019-01-14 16:58:59 +01002994 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002995 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002996 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997
Mikhail Naganov2996f672019-04-18 12:29:59 -07002998 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002999 requestedDeviceId, attributes.source, flags,
3000 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003002 // Move (if found) effect for the client session to its input
3003 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003004 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003005
3006 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3007 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003008
Eric Laurent599c7582015-12-07 18:05:55 -08003009 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003010
3011error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003013}
3014
3015
François Gaffie11d30102018-11-02 16:09:09 +01003016audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003017 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003018 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003019 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003020 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003021 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003022{
3023 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003024 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003025 bool isSoundTrigger = false;
3026
François Gaffiec005e562018-11-06 15:04:49 +01003027 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003028 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3029 if (index >= 0) {
3030 input = mSoundTriggerSessions.valueFor(session);
3031 isSoundTrigger = true;
3032 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3033 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3034 } else {
3035 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003036 }
François Gaffiec005e562018-11-06 15:04:49 +01003037 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003038 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003039 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003040 }
3041
Carter Hsua3abb402021-10-26 11:11:20 +08003042 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3043 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3044 }
3045
Eric Laurentfe231122017-11-17 17:48:06 -08003046 // sampling rate and flags may be updated by getInputProfile
3047 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3048 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003049 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003050 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003051 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003052 // find a compatible input profile (not necessarily identical in parameters)
3053 sp<IOProfile> profile = getInputProfile(
3054 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3055 if (profile == nullptr) {
3056 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003057 }
jiabin2fd710d2022-05-02 23:20:22 +00003058
Glenn Kasten05ddca52016-02-11 08:17:12 -08003059 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003060 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003061 if (samplingRate == 0) {
3062 samplingRate = profileSamplingRate;
3063 }
Eric Laurente552edb2014-03-10 17:42:56 -07003064
Eric Laurent322b4d22015-04-03 15:57:54 -07003065 if (profile->getModuleHandle() == 0) {
3066 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003067 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003068 }
3069
Eric Laurentec376dc2021-04-08 20:41:22 +02003070 // Reuse an already opened input if a client with the same session ID already exists
3071 // on that input
3072 for (size_t i = 0; i < mInputs.size(); i++) {
3073 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3074 if (desc->mProfile != profile) {
3075 continue;
3076 }
3077 RecordClientVector clients = desc->clientsList();
3078 for (const auto &client : clients) {
3079 if (session == client->session()) {
3080 return desc->mIoHandle;
3081 }
3082 }
3083 }
3084
Eric Laurent3974e3b2017-12-07 17:58:43 -08003085 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003086 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003087 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003088 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003089 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003090 continue;
3091 }
3092 // if sound trigger, reuse input if used by other sound trigger on same session
3093 // else
3094 // reuse input if active client app is not in IDLE state
3095 //
3096 RecordClientVector clients = desc->clientsList();
3097 bool doClose = false;
3098 for (const auto& client : clients) {
3099 if (isSoundTrigger != client->isSoundTrigger()) {
3100 continue;
3101 }
3102 if (client->isSoundTrigger()) {
3103 if (session == client->session()) {
3104 return desc->mIoHandle;
3105 }
3106 continue;
3107 }
3108 if (client->active() && client->appState() != APP_STATE_IDLE) {
3109 return desc->mIoHandle;
3110 }
3111 doClose = true;
3112 }
3113 if (doClose) {
3114 closeInput(desc->mIoHandle);
3115 } else {
3116 i++;
3117 }
3118 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003119 }
3120
Eric Laurentfe231122017-11-17 17:48:06 -08003121 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003122
Eric Laurentfe231122017-11-17 17:48:06 -08003123 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3124 lConfig.sample_rate = profileSamplingRate;
3125 lConfig.channel_mask = profileChannelMask;
3126 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003127
François Gaffie11d30102018-11-02 16:09:09 +01003128 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003129
3130 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003131 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003132 (profileSamplingRate != lConfig.sample_rate) ||
3133 !audio_formats_match(profileFormat, lConfig.format) ||
3134 (profileChannelMask != lConfig.channel_mask)) {
3135 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003136 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003137 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003138 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003139 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003140 }
Eric Laurent599c7582015-12-07 18:05:55 -08003141 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003142 }
3143
Eric Laurentc722f302014-12-10 11:21:49 -08003144 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003145
Eric Laurent599c7582015-12-07 18:05:55 -08003146 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003147 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003148
Eric Laurent599c7582015-12-07 18:05:55 -08003149 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003150}
3151
Eric Laurent4eb58f12018-12-07 16:41:02 -08003152status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003153{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003154 ALOGV("%s portId %d", __FUNCTION__, portId);
3155
3156 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3157 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003158 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003159 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003160 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003161 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003162 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 if (client->active()) {
3164 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3165 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003166 }
3167
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168 audio_session_t session = client->session();
3169
Eric Laurent4eb58f12018-12-07 16:41:02 -08003170 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003171
Eric Laurent4eb58f12018-12-07 16:41:02 -08003172 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003173
Eric Laurent4eb58f12018-12-07 16:41:02 -08003174 status_t status = inputDesc->start();
3175 if (status != NO_ERROR) {
3176 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003177 }
Eric Laurente552edb2014-03-10 17:42:56 -07003178
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003179 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003180 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003182
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 // indicate active capture to sound trigger service if starting capture from a mic on
3184 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003185 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003186 if (device != nullptr) {
3187 status = setInputDevice(input, device, true /* force */);
3188 } else {
3189 ALOGW("%s no new input device can be found for descriptor %d",
3190 __FUNCTION__, inputDesc->getId());
3191 status = BAD_VALUE;
3192 }
Eric Laurente552edb2014-03-10 17:42:56 -07003193
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003194 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003195 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003197 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003198 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3199 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003200 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003201 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003202
François Gaffie11d30102018-11-02 16:09:09 +01003203 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3204 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003206 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003207 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003208
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 // automatically enable the remote submix output when input is started if not
3210 // used by a policy mix of type MIX_TYPE_RECORDERS
3211 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003212 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003213 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003214 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003215 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003216 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3217 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003218 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003219 if (address != "") {
3220 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3221 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003222 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003223 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003224 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003225 } else if (status != NO_ERROR) {
3226 // Restore client activity state.
3227 inputDesc->setClientActive(client, false);
3228 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003229 }
3230
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003231 ALOGV("%s input %d source = %d status = %d exit",
3232 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003233
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003234 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003235}
3236
Eric Laurent8fc147b2018-07-22 19:13:55 -07003237status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003238{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003239 ALOGV("%s portId %d", __FUNCTION__, portId);
3240
3241 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3242 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003243 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003244 return BAD_VALUE;
3245 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003246 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003247 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003248 if (!client->active()) {
3249 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003250 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003251 }
Carter Hsue6139d52021-07-08 10:30:20 +08003252 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003253 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003254
Eric Laurent8f42ea12018-08-08 09:08:25 -07003255 inputDesc->stop();
3256 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003257 auto current_source = inputDesc->source();
3258 setInputDevice(input, getNewInputDevice(inputDesc),
3259 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003260 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003261 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003262 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003263 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003264 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3265 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003266 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003267 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003268
3269 // automatically disable the remote submix output when input is stopped if not
3270 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003271 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003272 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003273 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003274 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003275 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3276 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003277 }
3278 if (address != "") {
3279 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3280 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003281 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003282 }
3283 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 resetInputDevice(input);
3285
3286 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3287 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003288 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3289 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003291 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003292 }
3293 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003295 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003296}
3297
Eric Laurent8fc147b2018-07-22 19:13:55 -07003298void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003299{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003300 ALOGV("%s portId %d", __FUNCTION__, portId);
3301
3302 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3303 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003304 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003305 return;
3306 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003307 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003308 audio_io_handle_t input = inputDesc->mIoHandle;
3309
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003311
Andy Hung39efb7a2018-09-26 15:39:28 -07003312 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003313
3314 // If no more clients are present in this session, park effects to an orphan chain
3315 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3316 if (clientsOnSession.size() == 0) {
3317 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3318 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003319 if (inputDesc->getClientCount() > 0) {
3320 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003321 return;
3322 }
3323
Eric Laurent05b90f82014-08-27 15:32:29 -07003324 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003325 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003327}
3328
Eric Laurent8f42ea12018-08-08 09:08:25 -07003329void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003330{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003332
3333 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003335 }
3336}
3337
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3339{
3340 stopInput(portId);
3341 releaseInput(portId);
3342}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003343
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003344bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3345 if (input->clientsList().size() == 0
3346 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3347 return true;
3348 }
3349 for (const auto& client : input->clientsList()) {
3350 sp<DeviceDescriptor> device =
3351 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3352 client->session());
3353 if (!input->supportedDevices().contains(device)) {
3354 return true;
3355 }
3356 }
3357 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3358 return false;
3359}
3360
Eric Laurent0dd51852019-04-19 18:18:58 -07003361void AudioPolicyManager::checkCloseInputs() {
3362 // After connecting or disconnecting an input device, close input if:
3363 // - it has no client (was just opened to check profile) OR
3364 // - none of its supported devices are connected anymore OR
3365 // - one of its clients cannot be routed to one of its supported
3366 // devices anymore. Otherwise update device selection
3367 std::vector<audio_io_handle_t> inputsToClose;
3368 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003369 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003370 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003371 }
3372 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003373 for (const audio_io_handle_t handle : inputsToClose) {
3374 ALOGV("%s closing input %d", __func__, handle);
3375 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003376 }
Eric Laurentd4692962014-05-05 18:13:44 -07003377}
3378
François Gaffie251c7f02018-11-07 10:41:08 +01003379void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003380{
3381 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003382 if (indexMin < 0 || indexMax < 0) {
3383 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3384 return;
3385 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003386 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003387
3388 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003389 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3390 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003391 continue;
3392 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003393 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003394 }
Eric Laurente552edb2014-03-10 17:42:56 -07003395}
3396
Eric Laurente0720872014-03-11 09:30:41 -07003397status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003398 int index,
3399 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003400{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003401 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003402 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3403 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3404 return NO_ERROR;
3405 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003406 ALOGV("%s: stream %s attributes=%s", __func__,
3407 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003408 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003409}
3410
Eric Laurente0720872014-03-11 09:30:41 -07003411status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003412 int *index,
3413 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003414{
François Gaffiec005e562018-11-06 15:04:49 +01003415 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3416 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003417 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003418 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003419 deviceTypes = mEngine->getOutputDevicesForStream(
3420 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003421 }
jiabin9a3361e2019-10-01 09:38:30 -07003422 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003423}
3424
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003425status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003426 int index,
3427 audio_devices_t device)
3428{
3429 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003430 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3431 if (group == VOLUME_GROUP_NONE) {
3432 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003433 return BAD_VALUE;
3434 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003435 ALOGV("%s: group %d matching with %s index %d",
3436 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003437 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003438 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003439 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003440 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3441 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3442 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3443 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003444 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3445
3446 status = setVolumeCurveIndex(index, device, curves);
3447 if (status != NO_ERROR) {
3448 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3449 return status;
3450 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003451
jiabin9a3361e2019-10-01 09:38:30 -07003452 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003453 auto curCurvAttrs = curves.getAttributes();
3454 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3455 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003456 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003457 } else if (!curves.getStreamTypes().empty()) {
3458 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003459 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003460 } else {
3461 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3462 return BAD_VALUE;
3463 }
jiabin9a3361e2019-10-01 09:38:30 -07003464 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3465 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003466
François Gaffiecfe17322018-11-07 13:41:29 +01003467 // update volume on all outputs and streams matching the following:
3468 // - The requested stream (or a stream matching for volume control) is active on the output
3469 // - The device (or devices) selected by the engine for this stream includes
3470 // the requested device
3471 // - For non default requested device, currently selected device on the output is either the
3472 // requested device or one of the devices selected by the engine for this stream
3473 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3474 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003475 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003476 for (size_t i = 0; i < mOutputs.size(); i++) {
3477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003478 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003479
jiabin9a3361e2019-10-01 09:38:30 -07003480 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3481 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003482 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003483
3484 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003485 continue;
3486 }
3487 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3488 curDevices.find(device) == curDevices.end()) {
3489 continue;
3490 }
3491 bool applyVolume = false;
3492 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3493 curSrcDevices.insert(device);
3494 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003495 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3496 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003497 } else {
3498 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3499 }
3500 if (!applyVolume) {
3501 continue; // next output
3502 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003503 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3504 // If a higher priority strategy is active, and the output is routed to a device with a
3505 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003506 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003507 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003508 // If the volume source is active with higher priority source, ensure at least Sw Muted
3509 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003510 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3511 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3512 false /*preferredDevice*/);
3513 if (activeClients.empty()) {
3514 continue;
3515 }
3516 bool isPreempted = false;
3517 bool isHigherPriority = productStrategy < strategy;
3518 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003519 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003520 ALOGV("%s: Strategy=%d (\nrequester:\n"
3521 " group %d, volumeGroup=%d attributes=%s)\n"
3522 " higher priority source active:\n"
3523 " volumeGroup=%d attributes=%s) \n"
3524 " on output %zu, bailing out", __func__, productStrategy,
3525 group, group, toString(attributes).c_str(),
3526 client->volumeSource(), toString(client->attributes()).c_str(), i);
3527 applyVolume = false;
3528 isPreempted = true;
3529 break;
3530 }
3531 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003532 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003533 applyVolume = true;
3534 }
3535 }
3536 if (isPreempted || applyVolume) {
3537 break;
3538 }
3539 }
3540 if (!applyVolume) {
3541 continue; // next output
3542 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003543 }
François Gaffieed91f582020-01-31 10:35:37 +01003544 //FIXME: workaround for truncated touch sounds
3545 // delayed volume change for system stream to be removed when the problem is
3546 // handled by system UI
3547 status_t volStatus = checkAndSetVolume(
3548 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003549 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003550 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3551 if (volStatus != NO_ERROR) {
3552 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003553 }
3554 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003555
3556 // update voice volume if the an active call route exists
3557 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3558 && (curSrcDevices.find(
3559 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3560 != curSrcDevices.end())) {
3561 bool isVoiceVolSrc;
3562 bool isBtScoVolSrc;
3563 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3564 isVoiceVolSrc, isBtScoVolSrc, __func__)
3565 && (isVoiceVolSrc || isBtScoVolSrc)) {
3566 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3567 }
3568 }
3569
François Gaffiecfe17322018-11-07 13:41:29 +01003570 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3571 return status;
3572}
3573
François Gaffieaaac0fd2018-11-22 17:56:39 +01003574status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003575 audio_devices_t device,
3576 IVolumeCurves &volumeCurves)
3577{
3578 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3579 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003580 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3581 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003582 (index > volumeCurves.getVolumeIndexMax())) {
3583 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3584 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3585 return BAD_VALUE;
3586 }
3587 if (!audio_is_output_device(device)) {
3588 return BAD_VALUE;
3589 }
3590
3591 // Force max volume if stream cannot be muted
3592 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3593
François Gaffieaaac0fd2018-11-22 17:56:39 +01003594 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003595 volumeCurves.addCurrentVolumeIndex(device, index);
3596 return NO_ERROR;
3597}
3598
3599status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3600 int &index,
3601 audio_devices_t device)
3602{
3603 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3604 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003605 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003606 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003607 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003608 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003609 }
jiabin9a3361e2019-10-01 09:38:30 -07003610 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003611}
3612
3613status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3614 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003615 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003616{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003617 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003618 return BAD_VALUE;
3619 }
jiabin9a3361e2019-10-01 09:38:30 -07003620 index = curves.getVolumeIndex(deviceTypes);
3621 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003622 return NO_ERROR;
3623}
3624
3625status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3626 int &index)
3627{
3628 index = getVolumeCurves(attr).getVolumeIndexMin();
3629 return NO_ERROR;
3630}
3631
3632status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3633 int &index)
3634{
3635 index = getVolumeCurves(attr).getVolumeIndexMax();
3636 return NO_ERROR;
3637}
3638
Eric Laurent36829f92017-04-07 19:04:42 -07003639audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003640{
3641 // select one output among several suitable for global effects.
3642 // The priority is as follows:
3643 // 1: An offloaded output. If the effect ends up not being offloadable,
3644 // AudioFlinger will invalidate the track and the offloaded output
3645 // will be closed causing the effect to be moved to a PCM output.
3646 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003647 // 3: The primary output
3648 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003649
François Gaffiec005e562018-11-06 15:04:49 +01003650 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3651 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003652 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003653
Eric Laurent36829f92017-04-07 19:04:42 -07003654 if (outputs.size() == 0) {
3655 return AUDIO_IO_HANDLE_NONE;
3656 }
Eric Laurente552edb2014-03-10 17:42:56 -07003657
Eric Laurent36829f92017-04-07 19:04:42 -07003658 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3659 bool activeOnly = true;
3660
3661 while (output == AUDIO_IO_HANDLE_NONE) {
3662 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3663 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3664 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3665
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003666 for (audio_io_handle_t output : outputs) {
3667 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003668 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003669 continue;
3670 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003671 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3672 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003673 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003674 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003675 }
3676 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003677 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003678 }
3679 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003680 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003681 }
3682 }
3683 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3684 output = outputOffloaded;
3685 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3686 output = outputDeepBuffer;
3687 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3688 output = outputPrimary;
3689 } else {
3690 output = outputs[0];
3691 }
3692 activeOnly = false;
3693 }
3694
3695 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003696 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3697 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003698 mMusicEffectOutput = output;
3699 }
3700
3701 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003702 return output;
3703}
3704
Eric Laurent36829f92017-04-07 19:04:42 -07003705audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3706{
3707 return selectOutputForMusicEffects();
3708}
3709
Eric Laurente0720872014-03-11 09:30:41 -07003710status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003711 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003712 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003713 int session,
3714 int id)
3715{
Shunkai Yao29d10572024-03-19 04:31:47 +00003716 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003717 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003718 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003719 index = mInputs.indexOfKey(io);
3720 if (index < 0) {
3721 ALOGW("registerEffect() unknown io %d", io);
3722 return INVALID_OPERATION;
3723 }
Eric Laurente552edb2014-03-10 17:42:56 -07003724 }
3725 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003726 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3727 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3728 || strategy == PRODUCT_STRATEGY_NONE));
3729 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003730}
3731
Eric Laurentc241b0d2018-11-28 09:08:49 -08003732status_t AudioPolicyManager::unregisterEffect(int id)
3733{
3734 if (mEffects.getEffect(id) == nullptr) {
3735 return INVALID_OPERATION;
3736 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003737 if (mEffects.isEffectEnabled(id)) {
3738 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3739 setEffectEnabled(id, false);
3740 }
3741 return mEffects.unregisterEffect(id);
3742}
3743
3744status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3745{
3746 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3747 if (effect == nullptr) {
3748 return INVALID_OPERATION;
3749 }
3750
3751 status_t status = mEffects.setEffectEnabled(id, enabled);
3752 if (status == NO_ERROR) {
3753 mInputs.trackEffectEnabled(effect, enabled);
3754 }
3755 return status;
3756}
3757
Eric Laurent6c796322019-04-09 14:13:17 -07003758
3759status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3760{
3761 mEffects.moveEffects(ids, io);
3762 return NO_ERROR;
3763}
3764
Eric Laurentc75307b2015-03-17 15:29:32 -07003765bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3766{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003767 auto vs = toVolumeSource(stream, false);
3768 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003769}
3770
3771bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3772{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003773 auto vs = toVolumeSource(stream, false);
3774 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003775}
3776
Eric Laurente0720872014-03-11 09:30:41 -07003777bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003778{
3779 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003780 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003781 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003782 return true;
3783 }
3784 }
3785 return false;
3786}
3787
Eric Laurent275e8e92014-11-30 15:14:47 -08003788// Register a list of custom mixes with their attributes and format.
3789// When a mix is registered, corresponding input and output profiles are
3790// added to the remote submix hw module. The profile contains only the
3791// parameters (sampling rate, format...) specified by the mix.
3792// The corresponding input remote submix device is also connected.
3793//
3794// When a remote submix device is connected, the address is checked to select the
3795// appropriate profile and the corresponding input or output stream is opened.
3796//
3797// When capture starts, getInputForAttr() will:
3798// - 1 look for a mix matching the address passed in attribtutes tags if any
3799// - 2 if none found, getDeviceForInputSource() will:
3800// - 2.1 look for a mix matching the attributes source
3801// - 2.2 if none found, default to device selection by policy rules
3802// At this time, the corresponding output remote submix device is also connected
3803// and active playback use cases can be transferred to this mix if needed when reconnecting
3804// after AudioTracks are invalidated
3805//
3806// When playback starts, getOutputForAttr() will:
3807// - 1 look for a mix matching the address passed in attribtutes tags if any
3808// - 2 if none found, look for a mix matching the attributes usage
3809// - 3 if none found, default to device and output selection by policy rules.
3810
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003811status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003812{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003813 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3814 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003815 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003817 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003818 // examine each mix's route type
3819 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003820 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003821 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3822 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3823 ALOGE("Unsupported Policy Mix %zu of %zu: "
3824 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3825 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003826 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003827 break;
3828 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003829 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3830 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003831 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003832 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3833 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003834 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003835 rSubmixModule = mHwModules.getModuleFromName(
3836 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3837 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003838 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003839 i);
3840 res = INVALID_OPERATION;
3841 break;
3842 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003843 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003844
Eric Laurent97ac8712018-07-27 18:59:02 -07003845 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003846 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003847 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003848 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003849 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3850 } else {
3851 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3852 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003853 }
François Gaffie036e1e92015-03-19 10:16:24 +01003854
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003855 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003856 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003857 res = INVALID_OPERATION;
3858 break;
3859 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003860 audio_config_t outputConfig = mix.mFormat;
3861 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003862 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3863 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003864 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3865 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003866 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003867 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3868 audio_is_linear_pcm(outputConfig.format)
3869 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003870 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003871 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3872 audio_is_linear_pcm(inputConfig.format)
3873 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003874
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003875 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003876 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003877 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003878 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003879 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003880 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003881 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003882 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3883 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003884 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003885 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003886 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003887
3888 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3889 mix.mDeviceType, mix.mDeviceAddress,
3890 String8(), AUDIO_FORMAT_DEFAULT);
3891 if (device == nullptr) {
3892 res = INVALID_OPERATION;
3893 break;
3894 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003895
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003896 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003897 // First try to find an already opened output supporting the device
3898 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003899 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003900
Eric Laurentc529cf62020-04-17 18:19:10 -07003901 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003902 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003903 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003904 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003905 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003906 } else {
3907 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003908 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003909 }
3910 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003911 // If no output found, try to find a direct output profile supporting the device
3912 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3913 sp<HwModule> module = mHwModules[i];
3914 for (size_t j = 0;
3915 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3916 j++) {
3917 sp<IOProfile> profile = module->getOutputProfiles()[j];
3918 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3919 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3920 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003921 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003922 res = INVALID_OPERATION;
3923 } else {
3924 foundOutput = true;
3925 }
3926 }
3927 }
3928 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003929 if (res != NO_ERROR) {
3930 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003931 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003932 res = INVALID_OPERATION;
3933 break;
3934 } else if (!foundOutput) {
3935 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003936 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003937 res = INVALID_OPERATION;
3938 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003939 } else {
3940 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003941 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003942 }
Eric Laurentc722f302014-12-10 11:21:49 -08003943 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003944 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003945 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003946 if (audio_flags::audio_mix_ownership()) {
3947 // Only unregister mixes that were actually registered to not accidentally unregister
3948 // mixes that already existed previously.
3949 unregisterPolicyMixes(registeredMixes);
3950 registeredMixes.clear();
3951 } else {
3952 unregisterPolicyMixes(mixes);
3953 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003954 } else if (checkOutputs) {
3955 checkForDeviceAndOutputChanges();
3956 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003957 }
3958 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003959}
3960
3961status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3962{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003963 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003964 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003965 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003966 sp<HwModule> rSubmixModule;
3967 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003968 for (const auto& mix : mixes) {
3969 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003970
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003971 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003972 rSubmixModule = mHwModules.getModuleFromName(
3973 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3974 if (rSubmixModule == 0) {
3975 res = INVALID_OPERATION;
3976 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003977 }
3978 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003979
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003980 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003981
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003982 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003983 res = INVALID_OPERATION;
3984 continue;
3985 }
3986
Marvin Ramin0783e202024-03-05 12:45:50 +01003987 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003988 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01003989 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3990 status_t currentRes =
3991 setDeviceConnectionStateInt(device,
3992 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3993 address.c_str(),
3994 "remote-submix",
3995 AUDIO_FORMAT_DEFAULT);
3996 if (!audio_flags::audio_mix_ownership()) {
3997 res = currentRes;
3998 }
3999 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004000 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004001 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004002 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004003 }
4004 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004005 }
jiabin5740f082019-08-19 15:08:30 -07004006 rSubmixModule->removeOutputProfile(address.c_str());
4007 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004008
Kevin Rocard153f92d2018-12-18 18:33:28 -08004009 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004010 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004011 res = INVALID_OPERATION;
4012 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004013 } else {
4014 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004015 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004016 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004017 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004018
4019 if (res == NO_ERROR && checkOutputs) {
4020 checkForDeviceAndOutputChanges();
4021 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004022 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004023 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004024}
4025
Marvin Raminbdefaf02023-11-01 09:10:32 +01004026status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4027 if (!audio_flags::audio_mix_test_api()) {
4028 return INVALID_OPERATION;
4029 }
4030
4031 _aidl_return.clear();
4032 _aidl_return.reserve(mPolicyMixes.size());
4033 for (const auto &policyMix: mPolicyMixes) {
4034 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4035 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4036 policyMix->mCbFlags);
4037 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004038 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004039 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004040 }
4041
Vlad Popaa5d73f32024-03-08 16:05:38 -08004042 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004043 return OK;
4044}
4045
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004046status_t AudioPolicyManager::updatePolicyMix(
4047 const AudioMix& mix,
4048 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4049 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4050 if (res == NO_ERROR) {
4051 checkForDeviceAndOutputChanges();
4052 updateCallAndOutputRouting();
4053 }
4054 return res;
4055}
4056
Mikhail Naganov100f0122018-11-29 11:22:16 -08004057void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4058{
4059 size_t i = 0;
4060 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4061 for (const auto& fmt : mManualSurroundFormats) {
4062 if (i++ != 0) dst->append(", ");
4063 std::string sfmt;
4064 FormatConverter::toString(fmt, sfmt);
4065 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4066 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4067 }
4068}
4069
Eric Laurentc529cf62020-04-17 18:19:10 -07004070// Returns true if all devices types match the predicate and are supported by one HW module
4071bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004072 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004073 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004074 const char *context,
4075 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004076 for (size_t i = 0; i < devices.size(); i++) {
4077 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004078 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004079 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004080 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004081 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004082 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004083 return false;
4084 }
4085 }
4086 return true;
4087}
4088
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004089void AudioPolicyManager::changeOutputDevicesMuteState(
4090 const AudioDeviceTypeAddrVector& devices) {
4091 ALOGVV("%s() num devices %zu", __func__, devices.size());
4092
4093 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4094 getSoftwareOutputsForDevices(devices);
4095
4096 for (size_t i = 0; i < outputs.size(); i++) {
4097 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4098 DeviceVector prevDevices = outputDesc->devices();
4099 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4100 }
4101}
4102
4103std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4104 const AudioDeviceTypeAddrVector& devices) const
4105{
4106 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4107 DeviceVector deviceDescriptors;
4108 for (size_t j = 0; j < devices.size(); j++) {
4109 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4110 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4111 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4112 ALOGE("%s: device type %#x address %s not supported or not an output device",
4113 __func__, devices[j].mType, devices[j].getAddress());
4114 continue;
4115 }
4116 deviceDescriptors.add(desc);
4117 }
4118 for (size_t i = 0; i < mOutputs.size(); i++) {
4119 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4120 continue;
4121 }
4122 outputs.push_back(mOutputs.valueAt(i));
4123 }
4124 return outputs;
4125}
4126
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004127status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004128 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004129 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004130 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4131 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004132 }
4133 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004134 if (res != NO_ERROR) {
4135 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4136 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004137 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004138
4139 checkForDeviceAndOutputChanges();
4140 updateCallAndOutputRouting();
4141
4142 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004143}
4144
4145status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4146 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004147 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4148 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004149 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004150 __FUNCTION__, uid);
4151 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004152 }
4153
Eric Laurentc529cf62020-04-17 18:19:10 -07004154 checkForDeviceAndOutputChanges();
4155 updateCallAndOutputRouting();
4156
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004157 return res;
4158}
4159
Eric Laurent2517af32020-11-25 15:31:27 +01004160
jiabin0a488932020-08-07 17:32:40 -07004161status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4162 device_role_t role,
4163 const AudioDeviceTypeAddrVector &devices) {
4164 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4165 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004166
Eric Laurentc529cf62020-04-17 18:19:10 -07004167 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004168 return BAD_VALUE;
4169 }
jiabin0a488932020-08-07 17:32:40 -07004170 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004171 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004172 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4173 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004174 return status;
4175 }
4176
4177 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004178
4179 bool forceVolumeReeval = false;
4180 // FIXME: workaround for truncated touch sounds
4181 // to be removed when the problem is handled by system UI
4182 uint32_t delayMs = 0;
4183 if (strategy == mCommunnicationStrategy) {
4184 forceVolumeReeval = true;
4185 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4186 updateInputRouting();
4187 }
4188 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004189
4190 return NO_ERROR;
4191}
4192
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004193void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4194 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004195{
4196 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004197 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004198 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004199 // Only apply special touch sound delay once
4200 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004201 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004202 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004203 for (size_t i = 0; i < mOutputs.size(); i++) {
4204 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4205 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004206 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4207 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004208 // As done in setDeviceConnectionState, we could also fix default device issue by
4209 // preventing the force re-routing in case of default dev that distinguishes on address.
4210 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004211 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004212 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004213 // If the device is using preferred mixer attributes, the output need to reopen
4214 // with default configuration when the new selected devices are different from
4215 // current routing devices.
4216 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4217 continue;
4218 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304219
4220 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4221 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004222 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004223 // Only apply special touch sound delay once
4224 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004225 }
4226 if (forceVolumeReeval && !newDevices.isEmpty()) {
4227 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4228 }
4229 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004230 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004231 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004232}
4233
Eric Laurent2517af32020-11-25 15:31:27 +01004234void AudioPolicyManager::updateInputRouting() {
4235 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304236 // Skip for hotword recording as the input device switch
4237 // is handled within sound trigger HAL
4238 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4239 continue;
4240 }
Eric Laurent2517af32020-11-25 15:31:27 +01004241 auto newDevice = getNewInputDevice(activeDesc);
4242 // Force new input selection if the new device can not be reached via current input
4243 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4244 setInputDevice(activeDesc->mIoHandle, newDevice);
4245 } else {
4246 closeInput(activeDesc->mIoHandle);
4247 }
4248 }
4249}
4250
Paul Wang5d7cdb52022-11-22 09:45:06 +00004251status_t
4252AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4253 device_role_t role,
4254 const AudioDeviceTypeAddrVector &devices) {
4255 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4256 dumpAudioDeviceTypeAddrVector(devices).c_str());
4257
Eric Laurent78fedbf2023-03-09 14:40:44 +01004258 if (!areAllDevicesSupported(
4259 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004260 return BAD_VALUE;
4261 }
4262 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4263 if (status != NO_ERROR) {
4264 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4265 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4266 return status;
4267 }
4268
4269 checkForDeviceAndOutputChanges();
4270
4271 bool forceVolumeReeval = false;
4272 // TODO(b/263479999): workaround for truncated touch sounds
4273 // to be removed when the problem is handled by system UI
4274 uint32_t delayMs = 0;
4275 if (strategy == mCommunnicationStrategy) {
4276 forceVolumeReeval = true;
4277 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4278 updateInputRouting();
4279 }
4280 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4281
4282 return NO_ERROR;
4283}
4284
4285status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4286 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004287{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004288 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004289
Paul Wang5d7cdb52022-11-22 09:45:06 +00004290 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004291 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004292 ALOGW_IF(status != NAME_NOT_FOUND,
4293 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004294 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004295 return status;
4296 }
4297
4298 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004299
4300 bool forceVolumeReeval = false;
4301 // FIXME: workaround for truncated touch sounds
4302 // to be removed when the problem is handled by system UI
4303 uint32_t delayMs = 0;
4304 if (strategy == mCommunnicationStrategy) {
4305 forceVolumeReeval = true;
4306 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4307 updateInputRouting();
4308 }
4309 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004310
4311 return NO_ERROR;
4312}
4313
jiabin0a488932020-08-07 17:32:40 -07004314status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4315 device_role_t role,
4316 AudioDeviceTypeAddrVector &devices) {
4317 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004318}
4319
Jiabin Huang3b98d322020-09-03 17:54:16 +00004320status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4321 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4322 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4323 dumpAudioDeviceTypeAddrVector(devices).c_str());
4324
Mikhail Naganov55773032020-10-01 15:08:13 -07004325 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004326 return BAD_VALUE;
4327 }
4328 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4329 ALOGW_IF(status != NO_ERROR,
4330 "Engine could not set preferred devices %s for audio source %d role %d",
4331 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4332
4333 return status;
4334}
4335
4336status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4337 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4338 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4339 dumpAudioDeviceTypeAddrVector(devices).c_str());
4340
Mikhail Naganov55773032020-10-01 15:08:13 -07004341 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004342 return BAD_VALUE;
4343 }
4344 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4345 ALOGW_IF(status != NO_ERROR,
4346 "Engine could not add preferred devices %s for audio source %d role %d",
4347 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4348
Eric Laurent2517af32020-11-25 15:31:27 +01004349 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004350 return status;
4351}
4352
4353status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4354 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4355{
4356 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4357 dumpAudioDeviceTypeAddrVector(devices).c_str());
4358
Eric Laurent78fedbf2023-03-09 14:40:44 +01004359 if (!areAllDevicesSupported(
4360 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004361 return BAD_VALUE;
4362 }
4363
4364 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4365 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004366 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004367 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004368 if (status == NO_ERROR) {
4369 updateInputRouting();
4370 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004371 return status;
4372}
4373
4374status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4375 device_role_t role) {
4376 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4377
4378 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004379 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004380 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004381 if (status == NO_ERROR) {
4382 updateInputRouting();
4383 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004384 return status;
4385}
4386
4387status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4388 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4389 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4390}
4391
Oscar Azucena90e77632019-11-27 17:12:28 -08004392status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004393 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004394 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004395 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4396 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004397 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004398 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4399 if (status != NO_ERROR) {
4400 ALOGE("%s() could not set device affinity for userId %d",
4401 __FUNCTION__, userId);
4402 return status;
4403 }
4404
4405 // reevaluate outputs for all devices
4406 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004407 changeOutputDevicesMuteState(devices);
4408 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4409 true /* skipDelays */);
4410 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004411
4412 return NO_ERROR;
4413}
4414
4415status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004416 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004417 AudioDeviceTypeAddrVector devices;
4418 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004419 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4420 if (status != NO_ERROR) {
4421 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4422 __FUNCTION__, userId);
4423 return status;
4424 }
4425
4426 // reevaluate outputs for all devices
4427 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004428 changeOutputDevicesMuteState(devices);
4429 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4430 true /* skipDelays */);
4431 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004432
4433 return NO_ERROR;
4434}
4435
Andy Hungc29d82b2018-10-05 12:23:17 -07004436void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004437{
Andy Hungc29d82b2018-10-05 12:23:17 -07004438 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004439 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004440 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004441 std::string stateLiteral;
4442 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004443 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004444 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4445 "communications", "media", "record", "dock", "system",
4446 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4447 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4448 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004449 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4450 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4451 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4452 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4453 dst->append(" (MANUAL: ");
4454 dumpManualSurroundFormats(dst);
4455 dst->append(")");
4456 }
4457 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004458 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004459 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4460 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004461 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004462 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004463
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004464 dst->append("\n");
4465 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4466 dst->append("\n");
4467 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004468 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004469 mOutputs.dump(dst);
4470 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004471 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004472 mAudioPatches.dump(dst);
4473 mPolicyMixes.dump(dst);
4474 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004475
Kevin Rocardb99cc752019-03-21 20:52:24 -07004476 dst->appendFormat(" AllowedCapturePolicies:\n");
4477 for (auto& policy : mAllowedCapturePolicies) {
4478 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4479 }
4480
jiabina84c3d32022-12-02 18:59:55 +00004481 dst->appendFormat(" Preferred mixer audio configuration:\n");
4482 for (const auto it : mPreferredMixerAttrInfos) {
4483 dst->appendFormat(" - device port id: %d\n", it.first);
4484 for (const auto preferredMixerInfoIt : it.second) {
4485 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4486 preferredMixerInfoIt.second->dump(dst);
4487 }
4488 }
4489
François Gaffiec005e562018-11-06 15:04:49 +01004490 dst->appendFormat("\nPolicy Engine dump:\n");
4491 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004492}
4493
4494status_t AudioPolicyManager::dump(int fd)
4495{
4496 String8 result;
4497 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004498 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004499 return NO_ERROR;
4500}
4501
Kevin Rocardb99cc752019-03-21 20:52:24 -07004502status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4503{
4504 mAllowedCapturePolicies[uid] = capturePolicy;
4505 return NO_ERROR;
4506}
4507
Eric Laurente552edb2014-03-10 17:42:56 -07004508// This function checks for the parameters which can be offloaded.
4509// This can be enhanced depending on the capability of the DSP and policy
4510// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004511audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004512{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004513 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004514 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004515 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004516 offloadInfo.format,
4517 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4518 offloadInfo.has_video);
4519
jiabin2b9d5a12021-12-10 01:06:29 +00004520 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004521 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004522 }
4523
4524 // See if there is a profile to support this.
4525 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004526 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004527 offloadInfo.sample_rate,
4528 offloadInfo.format,
4529 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004530 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4531 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004532 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4533 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4534 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004535 if (profile == nullptr) {
4536 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4537 }
4538 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4539 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4540 }
4541 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004542}
4543
Michael Chana94fbb22018-04-24 14:31:19 +10004544bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4545 const audio_attributes_t& attributes) {
4546 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004547 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004548 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4549 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004550 config.sample_rate,
4551 config.format,
4552 config.channel_mask,
4553 output_flags,
4554 true /* directOnly */);
4555 ALOGV("%s() profile %sfound with name: %s, "
4556 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4557 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004558 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004559 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004560
4561 // also try the MSD module if compatible profile not found
4562 if (profile == nullptr) {
4563 profile = getMsdProfileForOutput(outputDevices,
4564 config.sample_rate,
4565 config.format,
4566 config.channel_mask,
4567 output_flags,
4568 true /* directOnly */);
4569 ALOGV("%s() MSD profile %sfound with name: %s, "
4570 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4571 __FUNCTION__, profile != 0 ? "" : "NOT ",
4572 (profile != 0 ? profile->getTagName().c_str() : "null"),
4573 config.sample_rate, config.format, config.channel_mask, output_flags);
4574 }
4575 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004576}
4577
jiabin2b9d5a12021-12-10 01:06:29 +00004578bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4579 bool durationIgnored) {
4580 if (mMasterMono) {
4581 return false; // no offloading if mono is set.
4582 }
4583
4584 // Check if offload has been disabled
4585 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4586 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4587 return false;
4588 }
4589
4590 // Check if stream type is music, then only allow offload as of now.
4591 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4592 {
4593 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4594 return false;
4595 }
4596
4597 //TODO: enable audio offloading with video when ready
4598 const bool allowOffloadWithVideo =
4599 property_get_bool("audio.offload.video", false /* default_value */);
4600 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4601 ALOGV("%s: has_video == true, returning false", __func__);
4602 return false;
4603 }
4604
4605 //If duration is less than minimum value defined in property, return false
4606 const int min_duration_secs = property_get_int32(
4607 "audio.offload.min.duration.secs", -1 /* default_value */);
4608 if (!durationIgnored) {
4609 if (min_duration_secs >= 0) {
4610 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4611 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4612 __func__, min_duration_secs);
4613 return false;
4614 }
4615 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4616 ALOGV("%s: Offload denied by duration < default min(=%u)",
4617 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4618 return false;
4619 }
4620 }
4621
4622 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4623 // creating an offloaded track and tearing it down immediately after start when audioflinger
4624 // detects there is an active non offloadable effect.
4625 // FIXME: We should check the audio session here but we do not have it in this context.
4626 // This may prevent offloading in rare situations where effects are left active by apps
4627 // in the background.
4628 if (mEffects.isNonOffloadableEffectEnabled()) {
4629 return false;
4630 }
4631
4632 return true;
4633}
4634
4635audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4636 const audio_config_t *config) {
4637 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4638 offloadInfo.format = config->format;
4639 offloadInfo.sample_rate = config->sample_rate;
4640 offloadInfo.channel_mask = config->channel_mask;
4641 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4642 offloadInfo.has_video = false;
4643 offloadInfo.is_streaming = false;
4644 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4645
4646 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4647 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4648 audio_flags_to_audio_output_flags(attr->flags, &flags);
4649 // only retain flags that will drive compressed offload or passthrough
4650 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4651 if (offloadPossible) {
4652 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4653 }
4654 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4655
Dorin Drimusfae3c642022-03-17 18:36:30 +01004656 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004657 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004658 DeviceVector outputDevices = engineOutputDevices;
4659 // the MSD module checks for different conditions and output devices
4660 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4661 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4662 continue;
4663 }
4664 outputDevices = getMsdAudioOutDevices();
4665 }
jiabin2b9d5a12021-12-10 01:06:29 +00004666 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004667 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004668 config->sample_rate, nullptr /*updatedSamplingRate*/,
4669 config->format, nullptr /*updatedFormat*/,
4670 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004671 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004672 continue;
4673 }
4674 // reject profiles not corresponding to a device currently available
4675 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4676 continue;
4677 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004678 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4679 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004680 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004681 != AUDIO_DIRECT_NOT_SUPPORTED) {
4682 // Already reports offload gapless supported. No need to report offload support.
4683 continue;
4684 }
4685 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4686 != AUDIO_OUTPUT_FLAG_NONE) {
4687 // If offload gapless is reported, no need to report offload support.
4688 directMode = (audio_direct_mode_t) ((directMode &
4689 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4690 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4691 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004692 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004693 }
4694 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004695 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004696 }
4697 }
4698 }
4699 return directMode;
4700}
4701
Dorin Drimusf2196d82022-01-03 12:11:18 +01004702status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4703 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004704 if (mEffects.isNonOffloadableEffectEnabled()) {
4705 return OK;
4706 }
jiabinf1c73972022-04-14 16:28:52 -07004707 DeviceVector devices;
4708 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004709 if (status != OK) {
4710 return status;
4711 }
4712 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4713 if (devices.empty()) {
4714 return OK; // no output devices for the attributes
4715 }
jiabinf1c73972022-04-14 16:28:52 -07004716 return getProfilesForDevices(devices, audioProfilesVector,
4717 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004718}
4719
jiabina84c3d32022-12-02 18:59:55 +00004720status_t AudioPolicyManager::getSupportedMixerAttributes(
4721 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4722 ALOGV("%s, portId=%d", __func__, portId);
4723 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4724 if (deviceDescriptor == nullptr) {
4725 ALOGE("%s the requested device is currently unavailable", __func__);
4726 return BAD_VALUE;
4727 }
jiabin96daffc2023-05-11 17:51:55 +00004728 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4729 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4730 deviceDescriptor->type());
4731 return BAD_VALUE;
4732 }
jiabina84c3d32022-12-02 18:59:55 +00004733 for (const auto& hwModule : mHwModules) {
4734 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4735 if (curProfile->supportsDevice(deviceDescriptor)) {
4736 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4737 }
4738 }
4739 }
4740 return NO_ERROR;
4741}
4742
4743status_t AudioPolicyManager::setPreferredMixerAttributes(
4744 const audio_attributes_t *attr,
4745 audio_port_handle_t portId,
4746 uid_t uid,
4747 const audio_mixer_attributes_t *mixerAttributes) {
4748 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4749 "mixerBehavior=%d}, uid=%d, portId=%u",
4750 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4751 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4752 mixerAttributes->mixer_behavior, uid, portId);
4753 if (attr->usage != AUDIO_USAGE_MEDIA) {
4754 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4755 return BAD_VALUE;
4756 }
4757 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4758 if (deviceDescriptor == nullptr) {
4759 ALOGE("%s the requested device is currently unavailable", __func__);
4760 return BAD_VALUE;
4761 }
4762 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4763 ALOGE("%s(%d), type=%d, is not a usb output device",
4764 __func__, portId, deviceDescriptor->type());
4765 return BAD_VALUE;
4766 }
4767
4768 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4769 audio_flags_to_audio_output_flags(attr->flags, &flags);
4770 flags = (audio_output_flags_t) (flags |
4771 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4772 sp<IOProfile> profile = nullptr;
4773 DeviceVector devices(deviceDescriptor);
4774 for (const auto& hwModule : mHwModules) {
4775 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4776 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004777 && curProfile->getCompatibilityScore(
4778 devices,
4779 mixerAttributes->config.sample_rate,
4780 nullptr /*updatedSamplingRate*/,
4781 mixerAttributes->config.format,
4782 nullptr /*updatedFormat*/,
4783 mixerAttributes->config.channel_mask,
4784 nullptr /*updatedChannelMask*/,
4785 flags,
4786 false /*exactMatchRequiredForInputFlags*/)
4787 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004788 profile = curProfile;
4789 break;
4790 }
4791 }
4792 }
4793 if (profile == nullptr) {
4794 ALOGE("%s, there is no compatible profile found", __func__);
4795 return BAD_VALUE;
4796 }
4797
4798 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4799 sp<PreferredMixerAttributesInfo>::make(
4800 uid, portId, profile, flags, *mixerAttributes);
4801 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4802 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4803
4804 // If 1) there is any client from the preferred mixer configuration owner that is currently
4805 // active and matches the strategy and 2) current output is on the preferred device and the
4806 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4807 // configuration.
4808 std::vector<audio_io_handle_t> outputsToReopen;
4809 for (size_t i = 0; i < mOutputs.size(); i++) {
4810 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004811 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4812 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004813 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004814 } else {
4815 for (const auto &client: output->getActiveClients()) {
4816 if (client->uid() == uid && client->strategy() == strategy) {
4817 client->setIsInvalid();
4818 outputsToReopen.push_back(output->mIoHandle);
4819 }
jiabina84c3d32022-12-02 18:59:55 +00004820 }
4821 }
4822 }
4823 }
4824 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4825 config.sample_rate = mixerAttributes->config.sample_rate;
4826 config.channel_mask = mixerAttributes->config.channel_mask;
4827 config.format = mixerAttributes->config.format;
4828 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004829 sp<SwAudioOutputDescriptor> desc =
4830 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4831 if (desc == nullptr) {
4832 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4833 continue;
4834 }
jiabin220eea12024-05-17 17:55:20 +00004835 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004836 }
4837
4838 return NO_ERROR;
4839}
4840
4841sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004842 audio_port_handle_t devicePortId,
4843 product_strategy_t strategy,
4844 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004845 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4846 if (it == mPreferredMixerAttrInfos.end()) {
4847 return nullptr;
4848 }
jiabind9a58d32023-06-01 17:57:30 +00004849 if (activeBitPerfectPreferred) {
4850 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004851 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004852 return info;
4853 }
4854 }
jiabina84c3d32022-12-02 18:59:55 +00004855 }
jiabind9a58d32023-06-01 17:57:30 +00004856 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4857 return strategyMatchedMixerAttrInfoIt == it->second.end()
4858 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004859}
4860
4861status_t AudioPolicyManager::getPreferredMixerAttributes(
4862 const audio_attributes_t *attr,
4863 audio_port_handle_t portId,
4864 audio_mixer_attributes_t* mixerAttributes) {
4865 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4866 portId, mEngine->getProductStrategyForAttributes(*attr));
4867 if (info == nullptr) {
4868 return NAME_NOT_FOUND;
4869 }
4870 *mixerAttributes = info->getMixerAttributes();
4871 return NO_ERROR;
4872}
4873
4874status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4875 audio_port_handle_t portId,
4876 uid_t uid) {
4877 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4878 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4879 if (preferredMixerAttrInfo == nullptr) {
4880 return NAME_NOT_FOUND;
4881 }
4882 if (preferredMixerAttrInfo->getUid() != uid) {
4883 ALOGE("%s, requested uid=%d, owned uid=%d",
4884 __func__, uid, preferredMixerAttrInfo->getUid());
4885 return PERMISSION_DENIED;
4886 }
4887 mPreferredMixerAttrInfos[portId].erase(strategy);
4888 if (mPreferredMixerAttrInfos[portId].empty()) {
4889 mPreferredMixerAttrInfos.erase(portId);
4890 }
4891
4892 // Reconfig existing output
4893 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4894 for (size_t i = 0; i < mOutputs.size(); i++) {
4895 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4896 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4897 }
4898 }
4899 for (const auto output : potentialOutputsToReopen) {
4900 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4901 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4902 preferredMixerAttrInfo->getFlags())) {
4903 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4904 }
4905 }
4906 return NO_ERROR;
4907}
4908
Eric Laurent6a94d692014-05-20 11:18:06 -07004909status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4910 audio_port_type_t type,
4911 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004912 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 unsigned int *generation)
4914{
jiabin19cdba52020-11-24 11:28:58 -08004915 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4916 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 return BAD_VALUE;
4918 }
4919 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004920 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 *num_ports = 0;
4922 }
4923
4924 size_t portsWritten = 0;
4925 size_t portsMax = *num_ports;
4926 *num_ports = 0;
4927 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004928 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4929 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004931 for (const auto& dev : mAvailableOutputDevices) {
4932 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004933 continue;
4934 }
4935 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004936 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004937 }
4938 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004939 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004940 }
4941 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004942 for (const auto& dev : mAvailableInputDevices) {
4943 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004944 continue;
4945 }
4946 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004947 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004948 }
4949 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 }
4952 }
4953 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4954 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4955 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4956 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4957 }
4958 *num_ports += mInputs.size();
4959 }
4960 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004961 size_t numOutputs = 0;
4962 for (size_t i = 0; i < mOutputs.size(); i++) {
4963 if (!mOutputs[i]->isDuplicated()) {
4964 numOutputs++;
4965 if (portsWritten < portsMax) {
4966 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4967 }
4968 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 }
Eric Laurent84c70242014-06-23 08:46:27 -07004970 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 }
4972 }
jiabina84c3d32022-12-02 18:59:55 +00004973
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004975 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 return NO_ERROR;
4977}
4978
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004979status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4980 std::vector<media::AudioPortFw>* _aidl_return) {
4981 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4982 audio_port_v7 port;
4983 dev->toAudioPort(&port);
4984 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4985 _aidl_return->push_back(std::move(aidlPort));
4986 return OK;
4987 };
4988
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004989 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004990 for (const auto& dev : module->getDeclaredDevices()) {
4991 if (role == media::AudioPortRole::NONE ||
4992 ((role == media::AudioPortRole::SOURCE)
4993 == audio_is_input_device(dev->type()))) {
4994 RETURN_STATUS_IF_ERROR(pushPort(dev));
4995 }
4996 }
4997 }
4998 return OK;
4999}
5000
jiabin19cdba52020-11-24 11:28:58 -08005001status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005002{
Eric Laurent99fcae42018-05-17 16:59:18 -07005003 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5004 return BAD_VALUE;
5005 }
5006 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5007 if (dev != 0) {
5008 dev->toAudioPort(port);
5009 return NO_ERROR;
5010 }
5011 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5012 if (dev != 0) {
5013 dev->toAudioPort(port);
5014 return NO_ERROR;
5015 }
5016 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5017 if (out != 0) {
5018 out->toAudioPort(port);
5019 return NO_ERROR;
5020 }
5021 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5022 if (in != 0) {
5023 in->toAudioPort(port);
5024 return NO_ERROR;
5025 }
5026 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005027}
5028
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005029status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5030 audio_patch_handle_t *handle,
5031 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005032{
François Gaffieafd4cea2019-11-18 15:50:22 +01005033 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 if (handle == NULL || patch == NULL) {
5035 return BAD_VALUE;
5036 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005038 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005039 return BAD_VALUE;
5040 }
5041 // only one source per audio patch supported for now
5042 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 return INVALID_OPERATION;
5044 }
Eric Laurent874c42872014-08-08 15:13:39 -07005045 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 return INVALID_OPERATION;
5047 }
Eric Laurent874c42872014-08-08 15:13:39 -07005048 for (size_t i = 0; i < patch->num_sinks; i++) {
5049 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5050 return INVALID_OPERATION;
5051 }
5052 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005053
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005054 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5055 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5056 if (srcDevice == nullptr || sinkDevice == nullptr) {
5057 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5058 return BAD_VALUE;
5059 }
5060 ALOGV("%s between source %s and sink %s", __func__,
5061 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5062 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5063 // Default attributes, default volume priority, not to infer with non raw audio patches.
5064 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5065 const struct audio_port_config *source = &patch->sources[0];
5066 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005067 new SourceClientDescriptor(
5068 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5069 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
5070 true);
5071 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005072
5073 status_t status =
5074 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5075
5076 if (status != NO_ERROR) {
5077 return INVALID_OPERATION;
5078 }
5079 mAudioSources.add(portId, sourceDesc);
5080 return NO_ERROR;
5081}
5082
5083status_t AudioPolicyManager::connectAudioSourceToSink(
5084 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5085 const struct audio_patch *patch,
5086 audio_patch_handle_t &handle,
5087 uid_t uid, uint32_t delayMs)
5088{
5089 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5090 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5091 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5092 return INVALID_OPERATION;
5093 }
5094 sourceDesc->connect(handle, sinkDevice);
5095 if (isMsdPatch(handle)) {
5096 return NO_ERROR;
5097 }
5098 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5099 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5100 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5101 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5102 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5103 goto FailurePatchAdded;
5104 }
5105 status = swOutput->start();
5106 if (status != NO_ERROR) {
5107 goto FailureSourceAdded;
5108 }
5109 swOutput->addClient(sourceDesc);
5110 status = startSource(swOutput, sourceDesc, &delayMs);
5111 if (status != NO_ERROR) {
5112 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5113 goto FailureSourceActive;
5114 }
5115 if (delayMs != 0) {
5116 usleep(delayMs * 1000);
5117 }
5118 return NO_ERROR;
5119
5120FailureSourceActive:
5121 swOutput->stop();
5122 releaseOutput(sourceDesc->portId());
5123FailureSourceAdded:
5124 sourceDesc->setSwOutput(nullptr);
5125FailurePatchAdded:
5126 releaseAudioPatchInternal(handle);
5127 return INVALID_OPERATION;
5128}
5129
5130status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5131 audio_patch_handle_t *handle,
5132 uid_t uid, uint32_t delayMs,
5133 const sp<SourceClientDescriptor>& sourceDesc)
5134{
5135 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005136 sp<AudioPatch> patchDesc;
5137 ssize_t index = mAudioPatches.indexOfKey(*handle);
5138
François Gaffieafd4cea2019-11-18 15:50:22 +01005139 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5140 patch->sources[0].role,
5141 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005142#if LOG_NDEBUG == 0
5143 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005144 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5145 patch->sinks[i].role,
5146 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005147 }
5148#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005149
5150 if (index >= 0) {
5151 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005152 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5153 __func__, mUidCached, patchDesc->getUid(), uid);
5154 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005155 return INVALID_OPERATION;
5156 }
5157 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005158 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 }
5160
5161 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005162 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005163 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005164 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005165 return BAD_VALUE;
5166 }
Eric Laurent84c70242014-06-23 08:46:27 -07005167 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5168 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005169 if (patchDesc != 0) {
5170 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005171 ALOGV("%s source id differs for patch current id %d new id %d",
5172 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005173 return BAD_VALUE;
5174 }
5175 }
Eric Laurent874c42872014-08-08 15:13:39 -07005176 DeviceVector devices;
5177 for (size_t i = 0; i < patch->num_sinks; i++) {
5178 // Only support mix to devices connection
5179 // TODO add support for mix to mix connection
5180 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005181 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005182 return INVALID_OPERATION;
5183 }
5184 sp<DeviceDescriptor> devDesc =
5185 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5186 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005187 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005188 return BAD_VALUE;
5189 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005190
jiabin66acc432024-02-06 00:57:36 +00005191 if (outputDesc->mProfile->getCompatibilityScore(
5192 DeviceVector(devDesc),
5193 patch->sources[0].sample_rate,
5194 nullptr, // updatedSamplingRate
5195 patch->sources[0].format,
5196 nullptr, // updatedFormat
5197 patch->sources[0].channel_mask,
5198 nullptr, // updatedChannelMask
5199 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005200 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005201 return INVALID_OPERATION;
5202 }
5203 devices.add(devDesc);
5204 }
5205 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 return INVALID_OPERATION;
5207 }
Eric Laurent874c42872014-08-08 15:13:39 -07005208
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s setting device %s on output %d",
5211 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305212 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 index = mAudioPatches.indexOfKey(*handle);
5214 if (index >= 0) {
5215 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005216 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 }
5218 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 patchDesc->setUid(uid);
5220 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005222 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 return INVALID_OPERATION;
5224 }
5225 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5226 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5227 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005228 // only one sink supported when connecting an input device to a mix
5229 if (patch->num_sinks > 1) {
5230 return INVALID_OPERATION;
5231 }
François Gaffie53615e22015-03-19 09:24:12 +01005232 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 if (inputDesc == NULL) {
5234 return BAD_VALUE;
5235 }
5236 if (patchDesc != 0) {
5237 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5238 return BAD_VALUE;
5239 }
5240 }
François Gaffie11d30102018-11-02 16:09:09 +01005241 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005243 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 return BAD_VALUE;
5245 }
5246
jiabin66acc432024-02-06 00:57:36 +00005247 if (inputDesc->mProfile->getCompatibilityScore(
5248 DeviceVector(device),
5249 patch->sinks[0].sample_rate,
5250 nullptr, /*updatedSampleRate*/
5251 patch->sinks[0].format,
5252 nullptr, /*updatedFormat*/
5253 patch->sinks[0].channel_mask,
5254 nullptr, /*updatedChannelMask*/
5255 // FIXME for the parameter type,
5256 // and the NONE
5257 (audio_output_flags_t)
5258 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 return INVALID_OPERATION;
5260 }
5261 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005262 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005263 device->toString().c_str(), inputDesc->mIoHandle);
5264 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 index = mAudioPatches.indexOfKey(*handle);
5266 if (index >= 0) {
5267 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005268 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 }
5270 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005271 patchDesc->setUid(uid);
5272 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005274 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 return INVALID_OPERATION;
5276 }
5277 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5278 // device to device connection
5279 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005280 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 return BAD_VALUE;
5282 }
5283 }
François Gaffie11d30102018-11-02 16:09:09 +01005284 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005286 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005287 return BAD_VALUE;
5288 }
Eric Laurent874c42872014-08-08 15:13:39 -07005289
Eric Laurent6a94d692014-05-20 11:18:06 -07005290 //update source and sink with our own data as the data passed in the patch may
5291 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 PatchBuilder patchBuilder;
5293 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005294
5295 // if first sink is to MSD, establish single MSD patch
5296 if (getMsdAudioOutDevices().contains(
5297 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5298 ALOGV("%s patching to MSD", __FUNCTION__);
5299 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5300 goto installPatch;
5301 }
5302
François Gaffieafd4cea2019-11-18 15:50:22 +01005303 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5304 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005305
Eric Laurent874c42872014-08-08 15:13:39 -07005306 for (size_t i = 0; i < patch->num_sinks; i++) {
5307 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005308 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005309 return INVALID_OPERATION;
5310 }
François Gaffie11d30102018-11-02 16:09:09 +01005311 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005312 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005313 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005314 return BAD_VALUE;
5315 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 audio_port_config sinkPortConfig = {};
5317 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5318 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005319
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005320 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5321 // volume management purpose (tracking activity)
5322 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5323 // in config XML to reach the sink so that is can be declared as available.
5324 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005325 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005326 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005327 // take care of dynamic routing for SwOutput selection,
5328 audio_attributes_t attributes = sourceDesc->attributes();
5329 audio_stream_type_t stream = sourceDesc->stream();
5330 audio_attributes_t resultAttr;
5331 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5332 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005333 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5334 config.channel_mask =
5335 (audio_channel_mask_get_representation(sourceMask)
5336 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5337 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005338 config.format = sourceDesc->config().format;
5339 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5340 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5341 bool isRequestedDeviceForExclusiveUse = false;
5342 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005343 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005344 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005345 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5346 &stream, sourceDesc->uid(), &config, &flags,
5347 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005348 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005349 if (output == AUDIO_IO_HANDLE_NONE) {
5350 ALOGV("%s no output for device %s",
5351 __FUNCTION__, sinkDevice->toString().c_str());
5352 return INVALID_OPERATION;
5353 }
5354 outputDesc = mOutputs.valueFor(output);
5355 if (outputDesc->isDuplicated()) {
5356 ALOGE("%s output is duplicated", __func__);
5357 return INVALID_OPERATION;
5358 }
François Gaffie7e39df22022-04-26 12:48:49 +02005359 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5360 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005361 } else {
5362 // Same for "raw patches" aka created from createAudioPatch API
5363 SortedVector<audio_io_handle_t> outputs =
5364 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5365 // if the sink device is reachable via an opened output stream, request to
5366 // go via this output stream by adding a second source to the patch
5367 // description
5368 output = selectOutput(outputs);
5369 if (output == AUDIO_IO_HANDLE_NONE) {
5370 ALOGE("%s no output available for internal patch sink", __func__);
5371 return INVALID_OPERATION;
5372 }
5373 outputDesc = mOutputs.valueFor(output);
5374 if (outputDesc->isDuplicated()) {
5375 ALOGV("%s output for device %s is duplicated",
5376 __func__, sinkDevice->toString().c_str());
5377 return INVALID_OPERATION;
5378 }
François Gaffie7e39df22022-04-26 12:48:49 +02005379 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005380 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005381 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005382 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005383 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005384 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005385 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5386 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005387 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5388 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005389 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005390 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005391 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005392 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005393 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005394 return INVALID_OPERATION;
5395 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005396 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005397 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005398 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005399 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005400 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005401 srcMixPortConfig.ext.mix.usecase.stream =
5402 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005403 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5404 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005405 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005406 }
Eric Laurent83b88082014-06-20 18:31:16 -07005407 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 }
5409 // TODO: check from routing capabilities in config file and other conflicting patches
5410
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005411installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005412 status_t status = installPatch(
5413 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005414 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005415 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005416 return INVALID_OPERATION;
5417 }
5418 } else {
5419 return BAD_VALUE;
5420 }
5421 } else {
5422 return BAD_VALUE;
5423 }
5424 return NO_ERROR;
5425}
5426
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005427status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005428{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005429 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 ssize_t index = mAudioPatches.indexOfKey(handle);
5431
5432 if (index < 0) {
5433 return BAD_VALUE;
5434 }
5435 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005436 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5437 __func__, mUidCached, patchDesc->getUid(), uid);
5438 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005439 return INVALID_OPERATION;
5440 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005441 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5442 for (size_t i = 0; i < mAudioSources.size(); i++) {
5443 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5444 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5445 portId = sourceDesc->portId();
5446 break;
5447 }
5448 }
5449 return portId != AUDIO_PORT_HANDLE_NONE ?
5450 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005451}
Eric Laurent6a94d692014-05-20 11:18:06 -07005452
François Gaffieafd4cea2019-11-18 15:50:22 +01005453status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005454 uint32_t delayMs,
5455 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005456{
5457 ALOGV("%s patch %d", __func__, handle);
5458 if (mAudioPatches.indexOfKey(handle) < 0) {
5459 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5460 return BAD_VALUE;
5461 }
5462 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005466 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005468 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005469 return BAD_VALUE;
5470 }
5471
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305472 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005473 getNewOutputDevices(outputDesc, true /*fromCache*/),
5474 true,
5475 0,
5476 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005477 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5478 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005479 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005480 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005481 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005482 return BAD_VALUE;
5483 }
5484 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005485 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005486 true,
5487 NULL);
5488 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005489 status_t status =
5490 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5491 ALOGV("%s patch panel returned %d patchHandle %d",
5492 __func__, status, patchDesc->getAfHandle());
5493 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005494 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005495 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005496 // SW or HW Bridge
5497 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5498 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005499 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005500 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5501 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5502 outputDesc = sourceDesc->swOutput().promote();
5503 }
5504 if (outputDesc == nullptr) {
5505 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5506 // releaseOutput has already called closeOutput in case of direct output
5507 return NO_ERROR;
5508 }
François Gaffie7e39df22022-04-26 12:48:49 +02005509 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005510 // While using a HwBridge, force reconsidering device only if not reusing an existing
5511 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005512 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005513 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5514 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5515 // Reconsider device only for cases:
5516 // 1 / Active Output
5517 // 2 / Inactive Output previously hosting HwBridge
5518 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5519 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5520 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305521 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005522 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5523 outputDesc->devices(),
5524 force,
5525 0,
5526 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 } else {
5528 return BAD_VALUE;
5529 }
5530 } else {
5531 return BAD_VALUE;
5532 }
5533 return NO_ERROR;
5534}
5535
5536status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5537 struct audio_patch *patches,
5538 unsigned int *generation)
5539{
François Gaffie53615e22015-03-19 09:24:12 +01005540 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 return BAD_VALUE;
5542 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005543 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005544 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005545}
5546
Eric Laurente1715a42014-05-20 11:30:42 -07005547status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005548{
Eric Laurente1715a42014-05-20 11:30:42 -07005549 ALOGV("setAudioPortConfig()");
5550
5551 if (config == NULL) {
5552 return BAD_VALUE;
5553 }
5554 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5555 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005556 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5557 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005558 }
5559
Eric Laurenta121f902014-06-03 13:32:54 -07005560 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005561 if (config->type == AUDIO_PORT_TYPE_MIX) {
5562 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005563 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005564 if (outputDesc == NULL) {
5565 return BAD_VALUE;
5566 }
Eric Laurent84c70242014-06-23 08:46:27 -07005567 ALOG_ASSERT(!outputDesc->isDuplicated(),
5568 "setAudioPortConfig() called on duplicated output %d",
5569 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005570 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005571 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005572 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005573 if (inputDesc == NULL) {
5574 return BAD_VALUE;
5575 }
Eric Laurenta121f902014-06-03 13:32:54 -07005576 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005577 } else {
5578 return BAD_VALUE;
5579 }
5580 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5581 sp<DeviceDescriptor> deviceDesc;
5582 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5583 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5584 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5585 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5586 } else {
5587 return BAD_VALUE;
5588 }
5589 if (deviceDesc == NULL) {
5590 return BAD_VALUE;
5591 }
Eric Laurenta121f902014-06-03 13:32:54 -07005592 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005593 } else {
5594 return BAD_VALUE;
5595 }
5596
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005597 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005598 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5599 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005600 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005601 audioPortConfig->toAudioPortConfig(&newConfig, config);
5602 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005603 }
Eric Laurenta121f902014-06-03 13:32:54 -07005604 if (status != NO_ERROR) {
5605 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005606 }
Eric Laurente1715a42014-05-20 11:30:42 -07005607
5608 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005609}
5610
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005611void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5612{
Eric Laurentd60560a2015-04-10 11:31:20 -07005613 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005614 clearAudioPatches(uid);
5615 clearSessionRoutes(uid);
5616}
5617
Eric Laurent6a94d692014-05-20 11:18:06 -07005618void AudioPolicyManager::clearAudioPatches(uid_t uid)
5619{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005620 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005621 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005622 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005623 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005624 }
5625 }
5626}
5627
François Gaffiec005e562018-11-06 15:04:49 +01005628void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005629{
François Gaffiec005e562018-11-06 15:04:49 +01005630 // Take the first attributes following the product strategy as it is used to retrieve the routed
5631 // device. All attributes wihin a strategy follows the same "routing strategy"
5632 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5633 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005634 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005635 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005636 for (size_t j = 0; j < mOutputs.size(); j++) {
5637 if (mOutputs.keyAt(j) == ouptutToSkip) {
5638 continue;
5639 }
5640 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005641 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005642 continue;
5643 }
5644 // If the default device for this strategy is on another output mix,
5645 // invalidate all tracks in this strategy to force re connection.
5646 // Otherwise select new device on the output mix.
5647 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005648 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005649 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005650 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005651 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005652 // If the device is using preferred mixer attributes, the output need to reopen
5653 // with default configuration when the new selected devices are different from
5654 // current routing devices.
5655 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5656 continue;
5657 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305658 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005659 }
5660 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005661 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005662}
5663
5664void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5665{
5666 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005667 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005668 for (size_t i = 0; i < mOutputs.size(); i++) {
5669 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005670 for (const auto& client : outputDesc->getClientIterable()) {
5671 if (client->hasPreferredDevice() && client->uid() == uid) {
5672 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005673 auto clientStrategy = client->strategy();
5674 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5675 end(affectedStrategies)) {
5676 continue;
5677 }
5678 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005679 }
5680 }
5681 }
5682 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005683 for (const auto& strategy : affectedStrategies) {
5684 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005685 }
5686
5687 // remove input routes associated with this uid
5688 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005689 for (size_t i = 0; i < mInputs.size(); i++) {
5690 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005691 for (const auto& client : inputDesc->getClientIterable()) {
5692 if (client->hasPreferredDevice() && client->uid() == uid) {
5693 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5694 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005695 }
5696 }
5697 }
5698 // reroute inputs if necessary
5699 SortedVector<audio_io_handle_t> inputsToClose;
5700 for (size_t i = 0; i < mInputs.size(); i++) {
5701 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005702 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005703 inputsToClose.add(inputDesc->mIoHandle);
5704 }
5705 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005706 for (const auto& input : inputsToClose) {
5707 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005708 }
5709}
5710
Eric Laurentd60560a2015-04-10 11:31:20 -07005711void AudioPolicyManager::clearAudioSources(uid_t uid)
5712{
5713 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005714 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5715 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005716 stopAudioSource(mAudioSources.keyAt(i));
5717 }
5718 }
5719}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005720
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005721status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5722 audio_io_handle_t *ioHandle,
5723 audio_devices_t *device)
5724{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005725 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5726 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005727 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005728 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5729 if (deviceDesc == nullptr) {
5730 return INVALID_OPERATION;
5731 }
5732 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005733
François Gaffiedf372692015-03-19 10:43:27 +01005734 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005735}
5736
Eric Laurentd60560a2015-04-10 11:31:20 -07005737status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005738 const audio_attributes_t *attributes,
5739 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005740 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005741{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005742 ALOGV("%s", __FUNCTION__);
5743 *portId = AUDIO_PORT_HANDLE_NONE;
5744
5745 if (source == NULL || attributes == NULL || portId == NULL) {
5746 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5747 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005748 return BAD_VALUE;
5749 }
5750
Eric Laurentd60560a2015-04-10 11:31:20 -07005751 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5752 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005753 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5754 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005755 return INVALID_OPERATION;
5756 }
5757
François Gaffie11d30102018-11-02 16:09:09 +01005758 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005759 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005760 String8(source->ext.device.address),
5761 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005762 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005763 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005764 return BAD_VALUE;
5765 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005766
jiabin4ef93452019-09-10 14:29:54 -07005767 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005768
François Gaffieaaac0fd2018-11-22 17:56:39 +01005769 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005770 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005771 mEngine->getStreamTypeForAttributes(*attributes),
5772 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005773 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005774
5775 status_t status = connectAudioSource(sourceDesc);
5776 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005777 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005778 }
5779 return status;
5780}
5781
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005782status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005783{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005784 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005785
5786 // make sure we only have one patch per source.
5787 disconnectAudioSource(sourceDesc);
5788
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005789 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005790 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5791 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5792 sourceDesc->srcDevice()->type(),
5793 String8(sourceDesc->srcDevice()->address().c_str()),
5794 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005795 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005796 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005797 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005798 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005799 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5800 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5801 return INVALID_OPERATION;
5802 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005803 PatchBuilder patchBuilder;
5804 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5805 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005806
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005807 return connectAudioSourceToSink(
5808 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005809}
5810
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005811status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005812{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005813 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5814 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005815 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005816 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005817 return BAD_VALUE;
5818 }
5819 status_t status = disconnectAudioSource(sourceDesc);
5820
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005821 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005822 return status;
5823}
5824
Andy Hung2ddee192015-12-18 17:34:44 -08005825status_t AudioPolicyManager::setMasterMono(bool mono)
5826{
5827 if (mMasterMono == mono) {
5828 return NO_ERROR;
5829 }
5830 mMasterMono = mono;
5831 // if enabling mono we close all offloaded devices, which will invalidate the
5832 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5833 // for recreating the new AudioTrack as non-offloaded PCM.
5834 //
5835 // If disabling mono, we leave all tracks as is: we don't know which clients
5836 // and tracks are able to be recreated as offloaded. The next "song" should
5837 // play back offloaded.
5838 if (mMasterMono) {
5839 Vector<audio_io_handle_t> offloaded;
5840 for (size_t i = 0; i < mOutputs.size(); ++i) {
5841 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5842 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5843 offloaded.push(desc->mIoHandle);
5844 }
5845 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005846 for (const auto& handle : offloaded) {
5847 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005848 }
5849 }
5850 // update master mono for all remaining outputs
5851 for (size_t i = 0; i < mOutputs.size(); ++i) {
5852 updateMono(mOutputs.keyAt(i));
5853 }
5854 return NO_ERROR;
5855}
5856
5857status_t AudioPolicyManager::getMasterMono(bool *mono)
5858{
5859 *mono = mMasterMono;
5860 return NO_ERROR;
5861}
5862
Eric Laurentac9cef52017-06-09 15:46:26 -07005863float AudioPolicyManager::getStreamVolumeDB(
5864 audio_stream_type_t stream, int index, audio_devices_t device)
5865{
jiabin9a3361e2019-10-01 09:38:30 -07005866 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005867}
5868
jiabin81772902018-04-02 17:52:27 -07005869status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5870 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005871 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005872{
Kriti Dang6537def2021-03-02 13:46:59 +01005873 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5874 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005875 return BAD_VALUE;
5876 }
Kriti Dang6537def2021-03-02 13:46:59 +01005877 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5878 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005879
5880 size_t formatsWritten = 0;
5881 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005882
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005883 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005884 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5885 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005886 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005887 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005888 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005889 bool formatEnabled = true;
5890 switch (forceUse) {
5891 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005892 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005893 break;
5894 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5895 formatEnabled = false;
5896 break;
5897 default: // AUTO or ALWAYS => true
5898 break;
jiabin81772902018-04-02 17:52:27 -07005899 }
5900 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5901 }
jiabin81772902018-04-02 17:52:27 -07005902 }
5903 return NO_ERROR;
5904}
5905
Kriti Dang6537def2021-03-02 13:46:59 +01005906status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5907 audio_format_t *surroundFormats) {
5908 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5909 return BAD_VALUE;
5910 }
5911 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5912 __func__, *numSurroundFormats, surroundFormats);
5913
5914 size_t formatsWritten = 0;
5915 size_t formatsMax = *numSurroundFormats;
5916 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5917
5918 // Return formats from all device profiles that have already been resolved by
5919 // checkOutputsForDevice().
5920 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5921 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5922 audio_devices_t deviceType = device->type();
5923 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5924 // returns formats reported by HDMI devices.
5925 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5926 continue;
5927 }
5928 // Formats reported by sink devices
5929 std::unordered_set<audio_format_t> formatset;
5930 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5931 formatset.insert(it->second.begin(), it->second.end());
5932 }
5933
5934 // Formats hard-coded in the in policy configuration file (if any).
5935 FormatVector encodedFormats = device->encodedFormats();
5936 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5937 // Filter the formats which are supported by the vendor hardware.
5938 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005939 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005940 formats.insert(*it);
5941 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005942 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005943 if (pair.second.count(*it) != 0) {
5944 formats.insert(pair.first);
5945 break;
5946 }
5947 }
5948 }
5949 }
5950 }
5951 *numSurroundFormats = formats.size();
5952 for (const auto& format: formats) {
5953 if (formatsWritten < formatsMax) {
5954 surroundFormats[formatsWritten++] = format;
5955 }
5956 }
5957 return NO_ERROR;
5958}
5959
jiabin81772902018-04-02 17:52:27 -07005960status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5961{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005962 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005963 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5964 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005965 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005966 return BAD_VALUE;
5967 }
5968
Mikhail Naganov100f0122018-11-29 11:22:16 -08005969 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5970 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005971 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005972 return INVALID_OPERATION;
5973 }
5974
Mikhail Naganov100f0122018-11-29 11:22:16 -08005975 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005976 return NO_ERROR;
5977 }
5978
Mikhail Naganov100f0122018-11-29 11:22:16 -08005979 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005980 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005981 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005982 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005983 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005984 }
5985 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005986 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005987 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005988 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005989 }
5990 }
5991
5992 sp<SwAudioOutputDescriptor> outputDesc;
5993 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005994 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5995 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005996 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5997 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005998 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005999 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006000 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6001 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6002 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006003 name.c_str(),
6004 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006005 if (status != NO_ERROR) {
6006 continue;
6007 }
6008 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6009 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6010 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006011 name.c_str(),
6012 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006013 profileUpdated |= (status == NO_ERROR);
6014 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006015 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006016 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006017 AUDIO_DEVICE_IN_HDMI);
6018 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6019 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006020 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006021 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006022 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6023 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6024 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006025 name.c_str(),
6026 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006027 if (status != NO_ERROR) {
6028 continue;
6029 }
6030 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6031 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6032 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006033 name.c_str(),
6034 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006035 profileUpdated |= (status == NO_ERROR);
6036 }
6037
jiabin81772902018-04-02 17:52:27 -07006038 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006039 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006040 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006041 }
6042
6043 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6044}
6045
Eric Laurent5ada82e2019-08-29 17:53:54 -07006046void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006047{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006048 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006049 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006050 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006051 }
6052}
6053
jiabin6012f912018-11-02 17:06:30 -07006054bool AudioPolicyManager::isHapticPlaybackSupported()
6055{
6056 for (const auto& hwModule : mHwModules) {
6057 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6058 for (const auto &outProfile : outputProfiles) {
6059 struct audio_port audioPort;
6060 outProfile->toAudioPort(&audioPort);
6061 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6062 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6063 return true;
6064 }
6065 }
6066 }
6067 }
6068 return false;
6069}
6070
Carter Hsu325a8eb2022-01-19 19:56:51 +08006071bool AudioPolicyManager::isUltrasoundSupported()
6072{
6073 bool hasUltrasoundOutput = false;
6074 bool hasUltrasoundInput = false;
6075 for (const auto& hwModule : mHwModules) {
6076 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6077 if (!hasUltrasoundOutput) {
6078 for (const auto &outProfile : outputProfiles) {
6079 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6080 hasUltrasoundOutput = true;
6081 break;
6082 }
6083 }
6084 }
6085
6086 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6087 if (!hasUltrasoundInput) {
6088 for (const auto &inputProfile : inputProfiles) {
6089 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6090 hasUltrasoundInput = true;
6091 break;
6092 }
6093 }
6094 }
6095
6096 if (hasUltrasoundOutput && hasUltrasoundInput)
6097 return true;
6098 }
6099 return false;
6100}
6101
Atneya Nair698f5ef2022-12-15 16:15:09 -08006102bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6103{
6104 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6105 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6106 for (const auto& hwModule : mHwModules) {
6107 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6108 for (const auto &inputProfile : inputProfiles) {
6109 if ((inputProfile->getFlags() & mask) == mask) {
6110 return true;
6111 }
6112 }
6113 }
6114 return false;
6115}
6116
Eric Laurent8340e672019-11-06 11:01:08 -08006117bool AudioPolicyManager::isCallScreenModeSupported()
6118{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006119 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006120}
6121
6122
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006123status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006124{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006125 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006126 if (!sourceDesc->isConnected()) {
6127 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6128 return NO_ERROR;
6129 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006130 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6131 if (swOutput != 0) {
6132 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006133 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006134 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006135 }
jiabinbce0c1d2020-10-05 11:20:18 -07006136 if (releaseOutput(sourceDesc->portId())) {
6137 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6138 // no need to release audio patch here but just return NO_ERROR.
6139 return NO_ERROR;
6140 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006141 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006142 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006143 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006144 // close Hwoutput and remove from mHwOutputs
6145 } else {
6146 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6147 }
6148 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006149 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006150 sourceDesc->disconnect();
6151 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006152}
6153
François Gaffiec005e562018-11-06 15:04:49 +01006154sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6155 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006156{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006157 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006158 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006159 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006160 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006161 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6162 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006163 source = sourceDesc;
6164 break;
6165 }
6166 }
6167 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006168}
6169
Eric Laurentb4f42a92022-01-17 17:37:31 +01006170bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006171 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006172 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006173{
6174 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6175 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006176 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006177 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006178 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6179 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6180 return false;
6181 }
6182 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6183 return false;
6184 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006185 }
6186
Eric Laurentd332bc82023-08-04 11:45:23 +02006187 // The caller can have the audio config criteria ignored by either passing a null ptr or
6188 // the AUDIO_CONFIG_INITIALIZER value.
6189 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006190 // some positional channel masks and PCM format and for stereo if low latency performance
6191 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006192
6193 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006194 static const bool stereo_spatialization_enabled =
6195 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006196 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006197 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006198 ? audio_channel_mask_contains_stereo(config->channel_mask)
6199 : audio_is_channel_mask_spatialized(config->channel_mask);
6200 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006201 return false;
6202 }
6203 if (!audio_is_linear_pcm(config->format)) {
6204 return false;
6205 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006206 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6207 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6208 return false;
6209 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006210 }
6211
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006212 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006213 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006214 if (profile == nullptr) {
6215 return false;
6216 }
6217
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006218 return true;
6219}
6220
Shunkai Yao4c3af932024-04-26 04:12:21 +00006221// The Spatializer output is compatible with Haptic use cases if:
6222// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6223// with client if client haptic channel bits were set, or
6224// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6225// including the haptic bits or creating the HapticGenerator effect for same session.
6226bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6227 const audio_config_t* config, audio_session_t sessionId) const {
6228 const auto clientHapticChannel =
6229 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6230 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6231 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6232
6233 if (threadOutputHapticChannel) {
6234 // check format and sampleRate match if client haptic channel mask exist
6235 if (clientHapticChannel) {
6236 return mSpatializerOutput->getFormat() == config->format &&
6237 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6238 }
6239 return true;
6240 } else {
6241 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6242 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6243 // HapticGenerator effect for this session) are not supported.
6244 return clientHapticChannel == 0 &&
6245 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6246 }
6247}
6248
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006249void AudioPolicyManager::checkVirtualizerClientRoutes() {
6250 std::set<audio_stream_type_t> streamsToInvalidate;
6251 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006252 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6253 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006254 audio_attributes_t attr = client->attributes();
6255 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6256 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6257 audio_config_base_t clientConfig = client->config();
6258 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006259 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006260 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006261 streamsToInvalidate.insert(client->stream());
6262 }
6263 }
6264 }
6265
jiabinc44b3462022-12-08 12:52:31 -08006266 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006267}
6268
Eric Laurente191d1b2022-04-15 11:59:25 +02006269
6270bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6271 const sp<SwAudioOutputDescriptor>& outputDesc) {
6272 if (outputDesc->isDuplicated()) {
6273 return false;
6274 }
6275 DeviceVector devices = outputDesc->supportedDevices();
6276 for (size_t i = 0; i < mOutputs.size(); i++) {
6277 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6278 if (desc == outputDesc || desc->isDuplicated()) {
6279 continue;
6280 }
6281 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6282 if (!sharedDevices.isEmpty()
6283 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6284 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6285 return false;
6286 }
6287 }
6288 return true;
6289}
6290
6291
Eric Laurentfa0f6742021-08-17 18:39:44 +02006292status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006293 const audio_attributes_t *attr,
6294 audio_io_handle_t *output) {
6295 *output = AUDIO_IO_HANDLE_NONE;
6296
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006297 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6298 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6299 audio_config_t *configPtr = nullptr;
6300 audio_config_t config;
6301 if (mixerConfig != nullptr) {
6302 config = audio_config_initializer(mixerConfig);
6303 configPtr = &config;
6304 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006305 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006306 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006307 return BAD_VALUE;
6308 }
6309
6310 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006311 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006312 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006313 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006314 return BAD_VALUE;
6315 }
6316
Eric Laurente191d1b2022-04-15 11:59:25 +02006317 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006318 for (size_t i = 0; i < mOutputs.size(); i++) {
6319 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006320 if (!desc->isDuplicated()
6321 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6322 spatializerOutputs.push_back(desc);
6323 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006324 }
6325 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006326 mSpatializerOutput.clear();
6327 bool outputsChanged = false;
6328 for (const auto& desc : spatializerOutputs) {
6329 if (desc->mProfile == profile
6330 && (configPtr == nullptr
6331 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6332 mSpatializerOutput = desc;
6333 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6334 } else {
6335 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6336 " and devices %s", __func__, desc->mIoHandle,
6337 configPtr != nullptr ? configPtr->channel_mask : 0,
6338 devices.toString().c_str());
6339 closeOutput(desc->mIoHandle);
6340 outputsChanged = true;
6341 }
Eric Laurent39095982021-08-24 18:29:27 +02006342 }
6343
Eric Laurente191d1b2022-04-15 11:59:25 +02006344 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006345 sp<SwAudioOutputDescriptor> desc =
6346 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006347 if (desc != nullptr) {
6348 mSpatializerOutput = desc;
6349 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006350 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006351 }
6352
6353 checkVirtualizerClientRoutes();
6354
Eric Laurente191d1b2022-04-15 11:59:25 +02006355 if (outputsChanged) {
6356 mPreviousOutputs = mOutputs;
6357 mpClientInterface->onAudioPortListUpdate();
6358 }
6359
6360 if (mSpatializerOutput == nullptr) {
6361 ALOGV("%s could not open spatializer output with requested config", __func__);
6362 return BAD_VALUE;
6363 }
Eric Laurent39095982021-08-24 18:29:27 +02006364 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006365 ALOGV("%s returning new spatializer output %d", __func__, *output);
6366 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006367}
6368
Eric Laurentfa0f6742021-08-17 18:39:44 +02006369status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6370 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006371 return INVALID_OPERATION;
6372 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006373 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006374 return BAD_VALUE;
6375 }
Eric Laurent39095982021-08-24 18:29:27 +02006376
Eric Laurente191d1b2022-04-15 11:59:25 +02006377 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6378 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6379 closeOutput(mSpatializerOutput->mIoHandle);
6380 //from now on mSpatializerOutput is null
6381 checkVirtualizerClientRoutes();
6382 }
Eric Laurent39095982021-08-24 18:29:27 +02006383
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006384 return NO_ERROR;
6385}
6386
Eric Laurente552edb2014-03-10 17:42:56 -07006387// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006388// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006389// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006390uint32_t AudioPolicyManager::nextAudioPortGeneration()
6391{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006392 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006393}
6394
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006395AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006396 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006397 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006398 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006399 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006400 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006401 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006402 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006403 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006404 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006405 mAudioPortGeneration(1),
6406 mBeaconMuteRefCount(0),
6407 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006408 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006409 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006410 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006411 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006412{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006413}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006414
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006415status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006416 if (mEngine == nullptr) {
6417 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006418 }
6419 mEngine->setObserver(this);
6420 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006421 if (status != NO_ERROR) {
6422 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6423 return status;
6424 }
François Gaffie2110e042015-03-24 08:41:51 +01006425
jiabin29230182023-04-04 21:02:36 +00006426 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6427 // at the end of this function.
6428 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006429 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6430 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6431
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006432 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006433 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006434 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006435
Eric Laurent3a4311c2014-03-17 12:00:47 -07006436 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006437 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6438 defaultOutputDevice == nullptr ||
6439 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6440 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6441 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006442 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006443 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006444 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006445
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006446 // Silence ALOGV statements
6447 property_set("log.tag." LOG_TAG, "D");
6448
Eric Laurente552edb2014-03-10 17:42:56 -07006449 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006450 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006451}
6452
Eric Laurente0720872014-03-11 09:30:41 -07006453AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006454{
Eric Laurente552edb2014-03-10 17:42:56 -07006455 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006456 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006457 }
6458 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006459 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006460 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006461 mAvailableOutputDevices.clear();
6462 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006463 mOutputs.clear();
6464 mInputs.clear();
6465 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006466 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006467 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006468}
6469
Eric Laurente0720872014-03-11 09:30:41 -07006470status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006471{
Eric Laurent87ffa392015-05-22 10:32:38 -07006472 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006473}
6474
Eric Laurente552edb2014-03-10 17:42:56 -07006475// ---
6476
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006477void AudioPolicyManager::onNewAudioModulesAvailable()
6478{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006479 DeviceVector newDevices;
6480 onNewAudioModulesAvailableInt(&newDevices);
6481 if (!newDevices.empty()) {
6482 nextAudioPortGeneration();
6483 mpClientInterface->onAudioPortListUpdate();
6484 }
6485}
6486
6487void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6488{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006489 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006490 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6491 continue;
6492 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006493 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006494 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6495 handle != AUDIO_MODULE_HANDLE_NONE) {
6496 hwModule->setHandle(handle);
6497 } else {
6498 ALOGW("could not load HW module %s", hwModule->getName());
6499 continue;
6500 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006501 }
6502 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006503 // open all output streams needed to access attached devices.
6504 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006505 // This also validates mAvailableOutputDevices list
6506 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6507 if (!outProfile->canOpenNewIo()) {
6508 ALOGE("Invalid Output profile max open count %u for profile %s",
6509 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6510 continue;
6511 }
6512 if (!outProfile->hasSupportedDevices()) {
6513 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6514 continue;
6515 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006516 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6517 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006518 mTtsOutputAvailable = true;
6519 }
6520
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006521 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006522 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006523 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006524 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6525 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006526 } else {
6527 // choose first device present in profile's SupportedDevices also part of
6528 // mAvailableOutputDevices.
6529 if (availProfileDevices.isEmpty()) {
6530 continue;
6531 }
6532 supportedDevice = availProfileDevices.itemAt(0);
6533 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006534 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006535 continue;
6536 }
6537 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6538 mpClientInterface);
6539 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006540 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6541 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006542 AUDIO_STREAM_DEFAULT,
6543 AUDIO_OUTPUT_FLAG_NONE, &output);
6544 if (status != NO_ERROR) {
6545 ALOGW("Cannot open output stream for devices %s on hw module %s",
6546 supportedDevice->toString().c_str(), hwModule->getName());
6547 continue;
6548 }
6549 for (const auto &device : availProfileDevices) {
6550 // give a valid ID to an attached device once confirmed it is reachable
6551 if (!device->isAttached()) {
6552 device->attach(hwModule);
6553 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006554 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006555 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006556 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6557 }
6558 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006559 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006560 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6561 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006562 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006563 }
Eric Laurent39095982021-08-24 18:29:27 +02006564 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006565 outputDesc->close();
6566 } else {
6567 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306568 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006569 DeviceVector(supportedDevice),
6570 true,
6571 0,
6572 NULL);
6573 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006574 }
6575 // open input streams needed to access attached devices to validate
6576 // mAvailableInputDevices list
6577 for (const auto& inProfile : hwModule->getInputProfiles()) {
6578 if (!inProfile->canOpenNewIo()) {
6579 ALOGE("Invalid Input profile max open count %u for profile %s",
6580 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6581 continue;
6582 }
6583 if (!inProfile->hasSupportedDevices()) {
6584 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6585 continue;
6586 }
6587 // chose first device present in profile's SupportedDevices also part of
6588 // available input devices
6589 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006590 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006591 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006592 ALOGV("%s: Input device list is empty! for profile %s",
6593 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006594 continue;
6595 }
6596 sp<AudioInputDescriptor> inputDesc =
6597 new AudioInputDescriptor(inProfile, mpClientInterface);
6598
6599 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6600 status_t status = inputDesc->open(nullptr,
6601 availProfileDevices.itemAt(0),
6602 AUDIO_SOURCE_MIC,
6603 AUDIO_INPUT_FLAG_NONE,
6604 &input);
6605 if (status != NO_ERROR) {
6606 ALOGW("Cannot open input stream for device %s on hw module %s",
6607 availProfileDevices.toString().c_str(),
6608 hwModule->getName());
6609 continue;
6610 }
6611 for (const auto &device : availProfileDevices) {
6612 // give a valid ID to an attached device once confirmed it is reachable
6613 if (!device->isAttached()) {
6614 device->attach(hwModule);
6615 device->importAudioPortAndPickAudioProfile(inProfile, true);
6616 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006617 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006618 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6619 }
6620 }
6621 inputDesc->close();
6622 }
6623 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006624
6625 // Check if spatializer outputs can be closed until used.
6626 // mOutputs vector never contains duplicated outputs at this point.
6627 std::vector<audio_io_handle_t> outputsClosed;
6628 for (size_t i = 0; i < mOutputs.size(); i++) {
6629 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6630 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6631 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6632 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006633 nextAudioPortGeneration();
6634 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6635 if (index >= 0) {
6636 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6637 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6638 patchDesc->getAfHandle(), 0);
6639 mAudioPatches.removeItemsAt(index);
6640 mpClientInterface->onAudioPatchListUpdate();
6641 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006642 desc->close();
6643 }
6644 }
6645 for (auto output : outputsClosed) {
6646 removeOutput(output);
6647 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006648}
6649
Eric Laurent98e38192018-02-15 18:31:53 -08006650void AudioPolicyManager::addOutput(audio_io_handle_t output,
6651 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006652{
Eric Laurent1c333e22014-05-20 10:48:17 -07006653 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006654 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006655 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006656 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006657 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006658}
6659
François Gaffie53615e22015-03-19 09:24:12 +01006660void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6661{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006662 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6663 ALOGV("%s: removing primary output", __func__);
6664 mPrimaryOutput = nullptr;
6665 }
François Gaffie53615e22015-03-19 09:24:12 +01006666 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006667 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006668}
6669
Eric Laurent98e38192018-02-15 18:31:53 -08006670void AudioPolicyManager::addInput(audio_io_handle_t input,
6671 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006672{
Eric Laurent1c333e22014-05-20 10:48:17 -07006673 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006674 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006675}
Eric Laurente552edb2014-03-10 17:42:56 -07006676
François Gaffie11d30102018-11-02 16:09:09 +01006677status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006678 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006679 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006680{
François Gaffie11d30102018-11-02 16:09:09 +01006681 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006682 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006683 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006684
François Gaffie11d30102018-11-02 16:09:09 +01006685 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006686 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006687 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006688 }
Eric Laurente552edb2014-03-10 17:42:56 -07006689
Eric Laurent3b73df72014-03-11 09:06:29 -07006690 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006691 // first call getAudioPort to get the supported attributes from the HAL
6692 struct audio_port_v7 port = {};
6693 device->toAudioPort(&port);
6694 status_t status = mpClientInterface->getAudioPort(&port);
6695 if (status == NO_ERROR) {
6696 device->importAudioPort(port);
6697 }
6698
6699 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006700 for (size_t i = 0; i < mOutputs.size(); i++) {
6701 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006702 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006703 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006704 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6705 mOutputs.keyAt(i), device->toString().c_str());
6706 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006707 }
6708 }
6709 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006710 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006711 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006712 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6713 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006714 if (profile->supportsDevice(device)) {
6715 profiles.add(profile);
6716 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6717 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006718 }
6719 }
6720 }
6721
Eric Laurent7b279bb2015-12-14 10:18:23 -08006722 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006723
Eric Laurente552edb2014-03-10 17:42:56 -07006724 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006725 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006726 return BAD_VALUE;
6727 }
6728
6729 // open outputs for matching profiles if needed. Direct outputs are also opened to
6730 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6731 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006732 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006733
6734 // nothing to do if one output is already opened for this profile
6735 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006736 for (j = 0; j < outputs.size(); j++) {
6737 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006738 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006739 // matching profile: save the sample rates, format and channel masks supported
6740 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006741 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006742 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006743 }
Eric Laurente552edb2014-03-10 17:42:56 -07006744 break;
6745 }
6746 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006747 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006748 continue;
6749 }
6750
Eric Laurent3974e3b2017-12-07 17:58:43 -08006751 if (!profile->canOpenNewIo()) {
6752 ALOGW("Max Output number %u already opened for this profile %s",
6753 profile->maxOpenCount, profile->getTagName().c_str());
6754 continue;
6755 }
6756
Eric Laurent83efe1c2017-07-09 16:51:08 -07006757 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006758 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006759 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6760 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006761 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006762 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006763 profiles.removeAt(profile_index);
6764 profile_index--;
6765 } else {
6766 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006767 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006768 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006769 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6770 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006771 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006772 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006773
François Gaffie11d30102018-11-02 16:09:09 +01006774 if (device_distinguishes_on_address(deviceType)) {
6775 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6776 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306777 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6778 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006779 }
Eric Laurente552edb2014-03-10 17:42:56 -07006780 ALOGV("checkOutputsForDevice(): adding output %d", output);
6781 }
6782 }
6783
6784 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006785 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006786 return BAD_VALUE;
6787 }
Eric Laurentd4692962014-05-05 18:13:44 -07006788 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006789 // check if one opened output is not needed any more after disconnecting one device
6790 for (size_t i = 0; i < mOutputs.size(); i++) {
6791 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006792 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006793 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006794 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006795 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006796 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006797 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006798 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6799 mOutputs.keyAt(i));
6800 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006801 }
Eric Laurente552edb2014-03-10 17:42:56 -07006802 }
6803 }
Eric Laurentd4692962014-05-05 18:13:44 -07006804 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006805 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006806 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6807 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006808 if (!profile->supportsDevice(device)) {
6809 continue;
6810 }
6811 ALOGV("checkOutputsForDevice(): "
6812 "clearing direct output profile %zu on module %s",
6813 j, hwModule->getName());
6814 profile->clearAudioProfiles();
6815 if (!profile->hasDynamicAudioProfile()) {
6816 continue;
6817 }
6818 // When a device is disconnected, if there is an IOProfile that contains dynamic
6819 // profiles and supports the disconnected device, call getAudioPort to repopulate
6820 // the capabilities of the devices that is supported by the IOProfile.
6821 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6822 if (supportedDevice == device ||
6823 !mAvailableOutputDevices.contains(supportedDevice)) {
6824 continue;
6825 }
6826 struct audio_port_v7 port;
6827 supportedDevice->toAudioPort(&port);
6828 status_t status = mpClientInterface->getAudioPort(&port);
6829 if (status == NO_ERROR) {
6830 supportedDevice->importAudioPort(port);
6831 }
Eric Laurente552edb2014-03-10 17:42:56 -07006832 }
6833 }
6834 }
6835 }
6836 return NO_ERROR;
6837}
6838
François Gaffie11d30102018-11-02 16:09:09 +01006839status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006840 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006841{
François Gaffie11d30102018-11-02 16:09:09 +01006842 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006843 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006844 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006845 }
6846
Eric Laurentd4692962014-05-05 18:13:44 -07006847 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006848 sp<AudioInputDescriptor> desc;
6849
jiabinbf5f4262023-04-12 21:48:34 +00006850 // first call getAudioPort to get the supported attributes from the HAL
6851 struct audio_port_v7 port = {};
6852 device->toAudioPort(&port);
6853 status_t status = mpClientInterface->getAudioPort(&port);
6854 if (status == NO_ERROR) {
6855 device->importAudioPort(port);
6856 }
6857
Eric Laurent0dd51852019-04-19 18:18:58 -07006858 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006859 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006860 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006861 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006862 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006863 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006864 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006865
François Gaffie11d30102018-11-02 16:09:09 +01006866 if (profile->supportsDevice(device)) {
6867 profiles.add(profile);
6868 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6869 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006870 }
6871 }
6872 }
6873
Eric Laurent0dd51852019-04-19 18:18:58 -07006874 if (profiles.isEmpty()) {
6875 ALOGW("%s: No input profile available for device %s",
6876 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006877 return BAD_VALUE;
6878 }
6879
6880 // open inputs for matching profiles if needed. Direct inputs are also opened to
6881 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6882 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6883
Eric Laurent1c333e22014-05-20 10:48:17 -07006884 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006885
Eric Laurentd4692962014-05-05 18:13:44 -07006886 // nothing to do if one input is already opened for this profile
6887 size_t input_index;
6888 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6889 desc = mInputs.valueAt(input_index);
6890 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006891 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006892 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006893 }
Eric Laurentd4692962014-05-05 18:13:44 -07006894 break;
6895 }
6896 }
6897 if (input_index != mInputs.size()) {
6898 continue;
6899 }
6900
Eric Laurent3974e3b2017-12-07 17:58:43 -08006901 if (!profile->canOpenNewIo()) {
6902 ALOGW("Max Input number %u already opened for this profile %s",
6903 profile->maxOpenCount, profile->getTagName().c_str());
6904 continue;
6905 }
6906
Eric Laurentfe231122017-11-17 17:48:06 -08006907 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006908 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006909 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006910
Eric Laurentcf2c0212014-07-25 16:20:43 -07006911 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006912 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006913 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006914 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006915 mpClientInterface->setParameters(input, String8(param));
6916 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006917 }
jiabin12537fc2023-10-12 17:56:08 +00006918 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006919 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006920 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006921 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006922 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006923 }
6924
Eric Laurent0dd51852019-04-19 18:18:58 -07006925 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006926 addInput(input, desc);
6927 }
6928 } // endif input != 0
6929
Eric Laurentcf2c0212014-07-25 16:20:43 -07006930 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006931 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006932 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006933 profiles.removeAt(profile_index);
6934 profile_index--;
6935 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006936 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006937 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006938 }
Eric Laurentd4692962014-05-05 18:13:44 -07006939 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07006940
6941 if (checkCloseInput(desc)) {
6942 ALOGV("%s closing input %d", __func__, input);
6943 closeInput(input);
6944 }
Eric Laurentd4692962014-05-05 18:13:44 -07006945 }
6946 } // end scan profiles
6947
6948 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006949 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006950 return BAD_VALUE;
6951 }
6952 } else {
6953 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006954 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006955 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006956 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006957 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006958 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006959 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006960 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006961 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6962 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006963 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006964 }
6965 }
6966 }
6967 } // end disconnect
6968
6969 return NO_ERROR;
6970}
6971
6972
Eric Laurente0720872014-03-11 09:30:41 -07006973void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006974{
6975 ALOGV("closeOutput(%d)", output);
6976
François Gaffie1c878552018-11-22 16:53:21 +01006977 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6978 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006979 ALOGW("closeOutput() unknown output %d", output);
6980 return;
6981 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006982 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006983 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006984
Eric Laurente552edb2014-03-10 17:42:56 -07006985 // look for duplicated outputs connected to the output being removed.
6986 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006987 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6988 if (dupOutput->isDuplicated() &&
6989 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6990 sp<SwAudioOutputDescriptor> remainingOutput =
6991 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006992 // As all active tracks on duplicated output will be deleted,
6993 // and as they were also referenced on the other output, the reference
6994 // count for their stream type must be adjusted accordingly on
6995 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006996 const bool wasActive = remainingOutput->isActive();
6997 // Note: no-op on the closing output where all clients has already been set inactive
6998 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006999 // stop() will be a no op if the output is still active but is needed in case all
7000 // active streams refcounts where cleared above
7001 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007002 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007003 }
Eric Laurente552edb2014-03-10 17:42:56 -07007004 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7005 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7006
7007 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007008 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007009 }
7010 }
7011
Eric Laurent05b90f82014-08-27 15:32:29 -07007012 nextAudioPortGeneration();
7013
François Gaffie1c878552018-11-22 16:53:21 +01007014 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007015 if (index >= 0) {
7016 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007017 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7018 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007019 mAudioPatches.removeItemsAt(index);
7020 mpClientInterface->onAudioPatchListUpdate();
7021 }
7022
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007023 if (closingOutputWasActive) {
7024 closingOutput->stop();
7025 }
François Gaffie1c878552018-11-22 16:53:21 +01007026 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007027 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007028 for (const auto device : closingOutput->devices()) {
7029 device->setPreferredConfig(nullptr);
7030 }
7031 }
Eric Laurente552edb2014-03-10 17:42:56 -07007032
François Gaffie53615e22015-03-19 09:24:12 +01007033 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007034 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007035 if (closingOutput == mSpatializerOutput) {
7036 mSpatializerOutput.clear();
7037 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007038
7039 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7040 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007041 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007042 bool directOutputOpen = false;
7043 for (size_t i = 0; i < mOutputs.size(); i++) {
7044 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7045 directOutputOpen = true;
7046 break;
7047 }
7048 }
7049 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007050 ALOGV("no direct outputs open, reset MSD patches");
7051 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7052 // how output devices for patching are resolved. Avoid by caching and reusing the
7053 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7054 // devices to patch to. This may be complicated by the fact that devices may become
7055 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007056 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007057 }
7058 }
jiabin220eea12024-05-17 17:55:20 +00007059
7060 if (closingOutput->mPreferredAttrInfo != nullptr) {
7061 closingOutput->mPreferredAttrInfo->resetActiveClient();
7062 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007063}
7064
7065void AudioPolicyManager::closeInput(audio_io_handle_t input)
7066{
7067 ALOGV("closeInput(%d)", input);
7068
7069 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7070 if (inputDesc == NULL) {
7071 ALOGW("closeInput() unknown input %d", input);
7072 return;
7073 }
7074
Eric Laurent6a94d692014-05-20 11:18:06 -07007075 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007076
François Gaffie11d30102018-11-02 16:09:09 +01007077 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007078 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007079 if (index >= 0) {
7080 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007081 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7082 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007083 mAudioPatches.removeItemsAt(index);
7084 mpClientInterface->onAudioPatchListUpdate();
7085 }
7086
François Gaffie6ebbce02023-07-19 13:27:53 +02007087 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007088 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007089 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007090
François Gaffie11d30102018-11-02 16:09:09 +01007091 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7092 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007093 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007094 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007095 }
Eric Laurente552edb2014-03-10 17:42:56 -07007096}
7097
François Gaffie11d30102018-11-02 16:09:09 +01007098SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7099 const DeviceVector &devices,
7100 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007101{
7102 SortedVector<audio_io_handle_t> outputs;
7103
François Gaffie11d30102018-11-02 16:09:09 +01007104 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007105 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007106 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007107 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007108 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007109 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007110 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007111 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007112 outputs.add(openOutputs.keyAt(i));
7113 }
7114 }
7115 return outputs;
7116}
7117
Mikhail Naganov37977152018-07-11 15:54:44 -07007118void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7119{
7120 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7121 // output is suspended before any tracks are moved to it
7122 checkA2dpSuspend();
7123 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007124 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007125 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007126 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007127 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007128 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7129 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7130 // configuration changes will ultimately be rerouted correctly. We can still avoid
7131 // unnecessary rerouting by caching and reusing the arguments to
7132 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7133 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007134 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007135 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007136 // an event that changed routing likely occurred, inform upper layers
7137 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007138}
7139
François Gaffiec005e562018-11-06 15:04:49 +01007140bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7141 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007142{
François Gaffiec005e562018-11-06 15:04:49 +01007143 return mEngine->getProductStrategyForAttributes(lAttr) ==
7144 mEngine->getProductStrategyForAttributes(rAttr);
7145}
7146
Francois Gaffieff1eb522020-05-06 18:37:04 +02007147void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7148{
7149 for (size_t i = 0; i < mAudioSources.size(); i++) {
7150 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7151 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007152 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007153 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007154 connectAudioSource(sourceDesc);
7155 }
7156 }
7157}
7158
7159void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7160{
7161 for (size_t i = 0; i < mAudioSources.size(); i++) {
7162 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7163 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7164 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7165 disconnectAudioSource(sourceDesc);
7166 }
7167 }
7168}
7169
François Gaffiec005e562018-11-06 15:04:49 +01007170void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7171{
7172 auto psId = mEngine->getProductStrategyForAttributes(attr);
7173
7174 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7175 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007176
François Gaffie11d30102018-11-02 16:09:09 +01007177 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7178 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007179
Eric Laurentc209fe42020-06-05 18:11:23 -07007180 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007181 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007182 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007183 // take into account dynamic audio policies related changes: if a client is now associated
7184 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007185 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007186 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7187 if (desc->isDuplicated()) {
7188 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007189 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007190 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7191 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7192 continue;
7193 }
7194 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007195 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007196 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7197 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7198 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007199 if (status != OK) {
7200 continue;
7201 }
yucliuf4de36d2020-09-14 14:57:56 -07007202 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007203 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007204 maxLatency = desc->latency();
7205 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007206 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007207 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007208 }
7209 }
7210
Eric Laurent56ed8842022-11-15 16:04:41 +01007211 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007212 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7213 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007214 for (audio_io_handle_t srcOut : srcOutputs) {
7215 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007216 if (desc == nullptr) continue;
7217
7218 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007219 maxLatency = desc->latency();
7220 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007221
Eric Laurent56ed8842022-11-15 16:04:41 +01007222 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007223 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007224 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007225 // a client on a non direct outputs has necessarily a linear PCM format
7226 // so we can call selectOutput() safely
7227 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7228 client->flags(),
7229 client->config().format,
7230 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007231 client->config().sample_rate,
7232 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007233 if (newOutput != srcOut) {
7234 invalidate = true;
7235 break;
7236 }
7237 } else {
7238 sp<IOProfile> profile = getProfileForOutput(newDevices,
7239 client->config().sample_rate,
7240 client->config().format,
7241 client->config().channel_mask,
7242 client->flags(),
7243 true /* directOnly */);
7244 if (profile != desc->mProfile) {
7245 invalidate = true;
7246 break;
7247 }
7248 }
7249 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007250 // mute strategy while moving tracks from one output to another
7251 if (invalidate) {
7252 invalidatedOutputs.push_back(desc);
7253 if (desc->isStrategyActive(psId)) {
7254 setStrategyMute(psId, true, desc);
7255 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7256 newDevices.types());
7257 }
Eric Laurente552edb2014-03-10 17:42:56 -07007258 }
François Gaffiec005e562018-11-06 15:04:49 +01007259 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007260 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007261 connectAudioSource(source);
7262 }
Eric Laurente552edb2014-03-10 17:42:56 -07007263 }
7264
Eric Laurent56ed8842022-11-15 16:04:41 +01007265 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7266 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7267 std::to_string(srcOutputs[0]).c_str(),
7268 std::to_string(dstOutputs[0]).c_str());
7269
François Gaffiec005e562018-11-06 15:04:49 +01007270 // Move effects associated to this stream from previous output to new output
7271 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007272 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007273 }
François Gaffiec005e562018-11-06 15:04:49 +01007274 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007275 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007276 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007277 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007278 desc->setTracksInvalidatedStatusByStrategy(psId);
7279 }
Eric Laurente552edb2014-03-10 17:42:56 -07007280 }
7281 }
7282}
7283
Eric Laurente0720872014-03-11 09:30:41 -07007284void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007285{
François Gaffiec005e562018-11-06 15:04:49 +01007286 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7287 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7288 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007289 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007290 }
Eric Laurente552edb2014-03-10 17:42:56 -07007291}
7292
Kevin Rocard153f92d2018-12-18 18:33:28 -08007293void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007294 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007295 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007296 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007297 for (size_t i = 0; i < mOutputs.size(); i++) {
7298 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7299 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007300 sp<AudioPolicyMix> primaryMix;
7301 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007302 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007303 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7304 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7305 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007306 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7307 for (auto &secondaryMix : secondaryMixes) {
7308 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7309 if (outputDesc != nullptr &&
7310 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7311 secondaryDescs.push_back(outputDesc);
7312 }
7313 }
7314
jiabinc44b3462022-12-08 12:52:31 -08007315 if (status != OK &&
7316 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7317 // When it failed to query secondary output, only invalidate the client that is not
7318 // MMAP. The reason is that MMAP stream will not support secondary output.
7319 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007320 } else if (!std::equal(
7321 client->getSecondaryOutputs().begin(),
7322 client->getSecondaryOutputs().end(),
7323 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007324 if (!audio_is_linear_pcm(client->config().format)) {
7325 // If the format is not PCM, the tracks should be invalidated to get correct
7326 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007327 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007328 } else {
7329 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7330 std::vector<audio_io_handle_t> secondaryOutputIds;
7331 for (const auto &secondaryDesc: secondaryDescs) {
7332 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7333 weakSecondaryDescs.push_back(secondaryDesc);
7334 }
7335 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7336 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007337 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007338 }
7339 }
7340 }
jiabin10a03f12021-05-07 23:46:28 +00007341 if (!trackSecondaryOutputs.empty()) {
7342 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7343 }
jiabinc44b3462022-12-08 12:52:31 -08007344 if (!clientsToInvalidate.empty()) {
7345 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7346 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007347 }
7348}
7349
Eric Laurent2517af32020-11-25 15:31:27 +01007350bool AudioPolicyManager::isScoRequestedForComm() const {
7351 AudioDeviceTypeAddrVector devices;
7352 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7353 for (const auto &device : devices) {
7354 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7355 return true;
7356 }
7357 }
7358 return false;
7359}
7360
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007361bool AudioPolicyManager::isHearingAidUsedForComm() const {
7362 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7363 true /*fromCache*/);
7364 for (const auto &device : devices) {
7365 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7366 return true;
7367 }
7368 }
7369 return false;
7370}
7371
7372
Eric Laurente0720872014-03-11 09:30:41 -07007373void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007374{
François Gaffie53615e22015-03-19 09:24:12 +01007375 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007376 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007377 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007378 return;
7379 }
7380
Eric Laurent3a4311c2014-03-17 12:00:47 -07007381 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007382 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7383 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007384 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007385
7386 // if suspended, restore A2DP output if:
7387 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007388 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007389 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007390 //
Eric Laurentf732e072016-08-03 19:30:28 -07007391 // if not suspended, suspend A2DP output if:
7392 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007393 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007394 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007395 //
7396 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007397 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007398 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007399 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007400 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007401
7402 mpClientInterface->restoreOutput(a2dpOutput);
7403 mA2dpSuspended = false;
7404 }
7405 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007406 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007407 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007408 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007409 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007410
7411 mpClientInterface->suspendOutput(a2dpOutput);
7412 mA2dpSuspended = true;
7413 }
7414 }
7415}
7416
François Gaffie11d30102018-11-02 16:09:09 +01007417DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7418 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007419{
François Gaffiedb1755b2023-09-01 11:50:35 +02007420 if (outputDesc == nullptr) {
7421 return DeviceVector{};
7422 }
François Gaffie11d30102018-11-02 16:09:09 +01007423
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007424 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007425 if (index >= 0) {
7426 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007427 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007428 ALOGV("%s device %s forced by patch %d", __func__,
7429 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7430 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007431 }
7432 }
7433
Dean Wheatley514b4312020-06-17 21:45:00 +10007434 // Do not retrieve engine device for outputs through MSD
7435 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7436 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7437 return outputDesc->devices();
7438 }
7439
Eric Laurent97ac8712018-07-27 18:59:02 -07007440 // Honor explicit routing requests only if no client using default routing is active on this
7441 // input: a specific app can not force routing for other apps by setting a preferred device.
7442 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007443 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007444 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007445 if (device != nullptr) {
7446 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007447 }
7448
François Gaffiea807ef92018-11-05 10:44:33 +01007449 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7450 // of setForceUse / Default Bus device here
7451 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7452 if (device != nullptr) {
7453 return DeviceVector(device);
7454 }
7455
François Gaffiedb1755b2023-09-01 11:50:35 +02007456 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007457 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7458 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307459 auto hasStreamActive = [&](auto stream) {
7460 return hasStream(streams, stream) && isStreamActive(stream, 0);
7461 };
Eric Laurent484e9272018-06-07 17:29:23 -07007462
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307463 auto doGetOutputDevicesForVoice = [&]() {
7464 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007465 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307466 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007467 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7468 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307469 };
7470
7471 // With low-latency playing on speaker, music on WFD, when the first low-latency
7472 // output is stopped, getNewOutputDevices checks for a product strategy
7473 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007474 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307475 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7476 // stream is associated to the output descriptor.
7477 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7478 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7479 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7480 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007481 // Retrieval of devices for voice DL is done on primary output profile, cannot
7482 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007483 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007484 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7485 break;
7486 }
Eric Laurente552edb2014-03-10 17:42:56 -07007487 }
François Gaffiec005e562018-11-06 15:04:49 +01007488 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007489 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007490}
7491
François Gaffie11d30102018-11-02 16:09:09 +01007492sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7493 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007494{
François Gaffie11d30102018-11-02 16:09:09 +01007495 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007496
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007497 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007498 if (index >= 0) {
7499 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007500 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007501 ALOGV("getNewInputDevice() device %s forced by patch %d",
7502 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7503 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007504 }
7505 }
7506
Eric Laurent97ac8712018-07-27 18:59:02 -07007507 // Honor explicit routing requests only if no client using default routing is active on this
7508 // input: a specific app can not force routing for other apps by setting a preferred device.
7509 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007510 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7511 if (device != nullptr) {
7512 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007513 }
7514
Eric Laurentdc95a252018-04-12 12:46:56 -07007515 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007516 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007517 audio_attributes_t attributes;
7518 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007519 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007520 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7521 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007522 attributes = topClient->attributes();
7523 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007524 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007525 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007526 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7527 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007528 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007529 }
7530
Francois Gaffie716e1432019-01-14 16:58:59 +01007531 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7532 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007533 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007534 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007535 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007536 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007537
Eric Laurente552edb2014-03-10 17:42:56 -07007538 return device;
7539}
7540
Eric Laurent794fde22016-03-11 09:50:45 -08007541bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7542 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007543 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007544}
7545
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007546status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007547 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007548 if (devices == nullptr) {
7549 return BAD_VALUE;
7550 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007551
Andy Hung6d23c0f2022-02-16 09:37:15 -08007552 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007553 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7554 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007555 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007556 for (const auto& device : curDevices) {
7557 devices->push_back(device->getDeviceTypeAddr());
7558 }
7559 return NO_ERROR;
7560}
7561
Eric Laurente0720872014-03-11 09:30:41 -07007562void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007563 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007564 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007565 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007566 updateDevicesAndOutputs();
7567 break;
7568 default:
7569 break;
7570 }
7571}
7572
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007573uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007574
7575 // skip beacon mute management if a dedicated TTS output is available
7576 if (mTtsOutputAvailable) {
7577 return 0;
7578 }
7579
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007580 switch(event) {
7581 case STARTING_OUTPUT:
7582 mBeaconMuteRefCount++;
7583 break;
7584 case STOPPING_OUTPUT:
7585 if (mBeaconMuteRefCount > 0) {
7586 mBeaconMuteRefCount--;
7587 }
7588 break;
7589 case STARTING_BEACON:
7590 mBeaconPlayingRefCount++;
7591 break;
7592 case STOPPING_BEACON:
7593 if (mBeaconPlayingRefCount > 0) {
7594 mBeaconPlayingRefCount--;
7595 }
7596 break;
7597 }
7598
7599 if (mBeaconMuteRefCount > 0) {
7600 // any playback causes beacon to be muted
7601 return setBeaconMute(true);
7602 } else {
7603 // no other playback: unmute when beacon starts playing, mute when it stops
7604 return setBeaconMute(mBeaconPlayingRefCount == 0);
7605 }
7606}
7607
7608uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7609 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7610 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7611 // keep track of muted state to avoid repeating mute/unmute operations
7612 if (mBeaconMuted != mute) {
7613 // mute/unmute AUDIO_STREAM_TTS on all outputs
7614 ALOGV("\t muting %d", mute);
7615 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007616 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7617 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7618 ALOGV("\t no tts volume source available");
7619 return 0;
7620 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007621 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007622 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007623 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007624 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007625 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007626 maxLatency = latency;
7627 }
7628 }
7629 mBeaconMuted = mute;
7630 return maxLatency;
7631 }
7632 return 0;
7633}
7634
Eric Laurente0720872014-03-11 09:30:41 -07007635void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007636{
François Gaffiec005e562018-11-06 15:04:49 +01007637 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007638 mPreviousOutputs = mOutputs;
7639}
7640
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007641uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007642 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007643 uint32_t delayMs)
7644{
7645 // mute/unmute strategies using an incompatible device combination
7646 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7647 // if unmuting, unmute only after the specified delay
7648 if (outputDesc->isDuplicated()) {
7649 return 0;
7650 }
7651
7652 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007653 DeviceVector devices = outputDesc->devices();
7654 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007655
François Gaffiec005e562018-11-06 15:04:49 +01007656 auto productStrategies = mEngine->getOrderedProductStrategies();
7657 for (const auto &productStrategy : productStrategies) {
7658 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7659 DeviceVector curDevices =
7660 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7661 curDevices = curDevices.filter(outputDesc->supportedDevices());
7662 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007663 bool doMute = false;
7664
François Gaffiec005e562018-11-06 15:04:49 +01007665 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007666 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007667 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7668 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007669 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007670 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007671 }
Eric Laurent99401132014-05-07 19:48:15 -07007672 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007673 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007674 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007675 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007676 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007677 continue;
7678 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307679 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007680 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7681 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7682 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007683 if (mute) {
7684 // FIXME: should not need to double latency if volume could be applied
7685 // immediately by the audioflinger mixer. We must account for the delay
7686 // between now and the next time the audioflinger thread for this output
7687 // will process a buffer (which corresponds to one buffer size,
7688 // usually 1/2 or 1/4 of the latency).
7689 if (muteWaitMs < desc->latency() * 2) {
7690 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007691 }
7692 }
7693 }
7694 }
7695 }
7696 }
7697
Eric Laurent99401132014-05-07 19:48:15 -07007698 // temporary mute output if device selection changes to avoid volume bursts due to
7699 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007700 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007701 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007702
Eric Laurentdc462862016-07-19 12:29:53 -07007703 if (muteWaitMs < tempMuteWaitMs) {
7704 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007705 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007706
7707 // If recommended duration is defined, replace temporary mute duration to avoid
7708 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7709 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7710 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7711 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7712 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7713
François Gaffieaaac0fd2018-11-22 17:56:39 +01007714 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7715 // make sure that we do not start the temporary mute period too early in case of
7716 // delayed device change
7717 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7718 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007719 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007720 }
7721 }
7722
Eric Laurente552edb2014-03-10 17:42:56 -07007723 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7724 if (muteWaitMs > delayMs) {
7725 muteWaitMs -= delayMs;
7726 usleep(muteWaitMs * 1000);
7727 return muteWaitMs;
7728 }
7729 return 0;
7730}
7731
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307732uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7733 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007734 const DeviceVector &devices,
7735 bool force,
7736 int delayMs,
7737 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007738 bool requiresMuteCheck, bool requiresVolumeCheck,
7739 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007740{
jiabin3ff8d7d2022-12-13 06:27:44 +00007741 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307742 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7743 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7744 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007745 uint32_t muteWaitMs;
7746
7747 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307748 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007749 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307750 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007751 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007752 return muteWaitMs;
7753 }
Eric Laurente552edb2014-03-10 17:42:56 -07007754
7755 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007756 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007757 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007758 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007759
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307760 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7761 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007762
7763 if (!filteredDevices.isEmpty()) {
7764 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007765 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007766
7767 // if the outputs are not materially active, there is no need to mute.
7768 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007769 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007770 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307771 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7772 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007773 muteWaitMs = 0;
7774 }
Eric Laurente552edb2014-03-10 17:42:56 -07007775
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007776 bool outputRouted = outputDesc->isRouted();
7777
Eric Laurent79ea9582020-06-11 18:49:24 -07007778 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7779 // output profile or if new device is not supported AND previous device(s) is(are) still
7780 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007781 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307782 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7783 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007784 // restore previous device after evaluating strategy mute state
7785 outputDesc->setDevices(prevDevices);
7786 return muteWaitMs;
7787 }
7788
Eric Laurente552edb2014-03-10 17:42:56 -07007789 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007790 // the requested device is AUDIO_DEVICE_NONE
7791 // OR the requested device is the same as current device
7792 // AND force is not specified
7793 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007794 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007795 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307796 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7797 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7798 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007799 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307800 ALOGV("%s %s setting same device on routed output, force apply volumes",
7801 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007802 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7803 }
Eric Laurente552edb2014-03-10 17:42:56 -07007804 return muteWaitMs;
7805 }
7806
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307807 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7808 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007809
Eric Laurente552edb2014-03-10 17:42:56 -07007810 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007811 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007812 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007813 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007814 PatchBuilder patchBuilder;
7815 patchBuilder.addSource(outputDesc);
7816 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7817 for (const auto &filteredDevice : filteredDevices) {
7818 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007819 }
7820
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007821 // Add half reported latency to delayMs when muteWaitMs is null in order
7822 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007823 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7824 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7825 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007826 }
Eric Laurente552edb2014-03-10 17:42:56 -07007827
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007828 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7829 if (!skipMuteDelay) {
7830 // update stream volumes according to new device
7831 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7832 }
Eric Laurente552edb2014-03-10 17:42:56 -07007833
7834 return muteWaitMs;
7835}
7836
Eric Laurentc75307b2015-03-17 15:29:32 -07007837status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007838 int delayMs,
7839 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007840{
Eric Laurent6a94d692014-05-20 11:18:06 -07007841 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007842 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7843 return INVALID_OPERATION;
7844 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007845 if (patchHandle) {
7846 index = mAudioPatches.indexOfKey(*patchHandle);
7847 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007848 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007849 }
7850 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007851 return INVALID_OPERATION;
7852 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007853 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007854 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007855 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007856 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007857 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007858 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007859 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007860 return status;
7861}
7862
7863status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007864 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007865 bool force,
7866 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007867{
7868 status_t status = NO_ERROR;
7869
Eric Laurent1f2f2232014-06-02 12:01:23 -07007870 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007871 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7872 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007873
François Gaffie11d30102018-11-02 16:09:09 +01007874 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007875 PatchBuilder patchBuilder;
7876 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007877 // AUDIO_SOURCE_HOTWORD is for internal use only:
7878 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007879 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7880 auto result = usecase;
7881 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7882 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7883 }
7884 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007885 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007886 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007887 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007888 }
7889 }
7890 return status;
7891}
7892
Eric Laurent6a94d692014-05-20 11:18:06 -07007893status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7894 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007895{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007896 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007897 ssize_t index;
7898 if (patchHandle) {
7899 index = mAudioPatches.indexOfKey(*patchHandle);
7900 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007901 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007902 }
7903 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007904 return INVALID_OPERATION;
7905 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007906 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007907 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007908 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007909 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007910 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007911 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007912 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007913 return status;
7914}
7915
François Gaffie11d30102018-11-02 16:09:09 +01007916sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007917 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007918 audio_format_t& format,
7919 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007920 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007921{
7922 // Choose an input profile based on the requested capture parameters: select the first available
7923 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007924 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007925
Atneya Nair0f0a8032022-12-12 16:20:12 -08007926 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7927 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7928 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7929
7930 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007931
jiabin2fd710d2022-05-02 23:20:22 +00007932 for (;;) {
7933 sp<IOProfile> firstInexact = nullptr;
7934 uint32_t updatedSamplingRate = 0;
7935 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7936 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7937 for (const auto& hwModule : mHwModules) {
7938 for (const auto& profile : hwModule->getInputProfiles()) {
7939 // profile->log();
7940 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007941 if (profile->getCompatibilityScore(
7942 DeviceVector(device),
7943 samplingRate,
7944 &updatedSamplingRate,
7945 format,
7946 &updatedFormat,
7947 channelMask,
7948 &updatedChannelMask,
7949 // FIXME ugly cast
7950 (audio_output_flags_t) flags,
7951 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7952 samplingRate = updatedSamplingRate;
7953 format = updatedFormat;
7954 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007955 return profile;
7956 }
jiabin66acc432024-02-06 00:57:36 +00007957 if (firstInexact == nullptr
7958 && profile->getCompatibilityScore(
7959 DeviceVector(device),
7960 samplingRate,
7961 &updatedSamplingRate,
7962 format,
7963 &updatedFormat,
7964 channelMask,
7965 &updatedChannelMask,
7966 // FIXME ugly cast
7967 (audio_output_flags_t) flags,
7968 false /*exactMatchRequiredForInputFlags*/)
7969 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007970 firstInexact = profile;
7971 }
7972 }
7973 }
7974
7975 if (firstInexact != nullptr) {
7976 samplingRate = updatedSamplingRate;
7977 format = updatedFormat;
7978 channelMask = updatedChannelMask;
7979 return firstInexact;
7980 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7981 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7982 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7983 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7984 flags = AUDIO_INPUT_FLAG_NONE;
7985 } else { // fail
7986 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7987 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7988 samplingRate, format, channelMask, oriFlags);
7989 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007990 }
7991 }
jiabin2fd710d2022-05-02 23:20:22 +00007992
7993 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007994}
7995
François Gaffieaaac0fd2018-11-22 17:56:39 +01007996float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7997 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007998 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07007999 const DeviceTypeSet& deviceTypes,
8000 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008001{
jiabin9a3361e2019-10-01 09:38:30 -07008002 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008003
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008004 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8005 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8006
8007 if (!computeInternalInteraction) {
8008 return volumeDb;
8009 }
8010
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008011 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8012 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8013 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8014 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008015 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8016 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8017 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8018 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8019 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008020 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008021 mOutputs.isActive(ringVolumeSrc, 0)) {
8022 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008023 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8024 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008025 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008026 }
8027
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008028 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008029 if ((volumeSource != callVolumeSrc && (isInCall() ||
8030 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008031 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008032 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8033 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008034 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8035 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8036 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008037 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008038 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008039 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008040 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008041 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8042 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008043 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008044 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8045 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8046 // programmatically muted.
8047 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8048 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8049 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008050 bool exemptFromCapping =
8051 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8052 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008053 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8054 volumeSource, volumeDb);
8055 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008056 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8057 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8058 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008059 }
8060 }
Eric Laurente552edb2014-03-10 17:42:56 -07008061 // if a headset is connected, apply the following rules to ring tones and notifications
8062 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008063 // - always attenuate notifications volume by 6dB
8064 // - attenuate ring tones volume by 6dB unless music is not playing and
8065 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008066 // - if music is playing, always limit the volume to current music volume,
8067 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008068 if (!Intersection(deviceTypes,
8069 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8070 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008071 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8072 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008073 ((volumeSource == alarmVolumeSrc ||
8074 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008075 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8076 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8077 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008078 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8079 curves.canBeMuted()) {
8080
Eric Laurente552edb2014-03-10 17:42:56 -07008081 // when the phone is ringing we must consider that music could have been paused just before
8082 // by the music application and behave as if music was active if the last music track was
8083 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008084 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8085 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008086 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008087 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008088 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8089 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008090 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008091 float musicVolDb = computeVolume(musicCurves,
8092 musicVolumeSrc,
8093 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008094 musicDevice,
8095 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008096 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8097 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8098 if (volumeDb > minVolDb) {
8099 volumeDb = minVolDb;
8100 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008101 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008102 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8103 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
8104 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008105 // on A2DP, also ensure notification volume is not too low compared to media when
8106 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01008107 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008108 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008109 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8110 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008111 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8112 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008113 }
8114 }
jiabin9a3361e2019-10-01 09:38:30 -07008115 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008116 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008117 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008118 }
8119 }
8120
François Gaffie43c73442018-11-08 08:21:55 +01008121 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008122}
8123
Eric Laurent3839bc02018-07-10 18:33:34 -07008124int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008125 VolumeSource fromVolumeSource,
8126 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008127{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008128 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008129 return srcIndex;
8130 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008131 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8132 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008133 float minSrc = (float)srcCurves.getVolumeIndexMin();
8134 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8135 float minDst = (float)dstCurves.getVolumeIndexMin();
8136 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008137
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008138 // preserve mute request or correct range
8139 if (srcIndex < minSrc) {
8140 if (srcIndex == 0) {
8141 return 0;
8142 }
8143 srcIndex = minSrc;
8144 } else if (srcIndex > maxSrc) {
8145 srcIndex = maxSrc;
8146 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008147 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8148}
8149
François Gaffieaaac0fd2018-11-22 17:56:39 +01008150status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8151 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008152 int index,
8153 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008154 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008155 int delayMs,
8156 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008157{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008158 // do not change actual attributes volume if the attributes is muted
8159 if (outputDesc->isMuted(volumeSource)) {
8160 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8161 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008162 return NO_ERROR;
8163 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008164
Eric Laurentae6e88c2024-01-10 14:42:57 +01008165 bool isVoiceVolSrc;
8166 bool isBtScoVolSrc;
8167 if (!isVolumeConsistentForCalls(
8168 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008169 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008170 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008171 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008172 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008173
jiabin9a3361e2019-10-01 09:38:30 -07008174 if (deviceTypes.empty()) {
8175 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008176 index = curves.getVolumeIndex(deviceTypes);
8177 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
8178 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008179 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008180
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008181 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8182 ALOGE("invalid volume index range");
8183 return BAD_VALUE;
8184 }
8185
jiabin9a3361e2019-10-01 09:38:30 -07008186 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8187 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008188 // Force VoIP volume to max for bluetooth SCO device except if muted
8189 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008190 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008191 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008192 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008193 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008194 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8195 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008196
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008197 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008198 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008199 }
Eric Laurente552edb2014-03-10 17:42:56 -07008200 return NO_ERROR;
8201}
8202
Eric Laurentae6e88c2024-01-10 14:42:57 +01008203void AudioPolicyManager::setVoiceVolume(
8204 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8205 float voiceVolume;
8206 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8207 // by the headset
8208 if (isVoiceVolSrc) {
8209 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8210 } else {
8211 voiceVolume = index == 0 ? 0.0 : 1.0;
8212 }
8213 if (voiceVolume != mLastVoiceVolume) {
8214 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8215 mLastVoiceVolume = voiceVolume;
8216 }
8217}
8218
8219bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8220 const DeviceTypeSet& deviceTypes,
8221 bool& isVoiceVolSrc,
8222 bool& isBtScoVolSrc,
8223 const char* caller) {
8224 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8225 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8226 const bool isScoRequested = isScoRequestedForComm();
8227 const bool isHAUsed = isHearingAidUsedForComm();
8228
8229 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8230 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8231
8232 if ((callVolSrc != btScoVolSrc) &&
8233 ((isVoiceVolSrc && isScoRequested) ||
8234 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8235 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8236 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8237 volumeSource, isScoRequested ? " " : " not ");
8238 return false;
8239 }
8240 return true;
8241}
8242
Eric Laurentc75307b2015-03-17 15:29:32 -07008243void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008244 const DeviceTypeSet& deviceTypes,
8245 int delayMs,
8246 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008247{
jiabincd510522020-01-22 09:40:55 -08008248 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008249 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8250 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8251 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008252 curves.getVolumeIndex(deviceTypes),
8253 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008254 }
8255}
8256
François Gaffiec005e562018-11-06 15:04:49 +01008257void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
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{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008263 std::vector<VolumeSource> sourcesToMute;
8264 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8265 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8266 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008267 VolumeSource source = toVolumeSource(attributes, false);
8268 if ((source != VOLUME_SOURCE_NONE) &&
8269 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8270 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008271 sourcesToMute.push_back(source);
8272 }
Eric Laurente552edb2014-03-10 17:42:56 -07008273 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008274 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008275 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008276 }
8277
Eric Laurente552edb2014-03-10 17:42:56 -07008278}
8279
François Gaffieaaac0fd2018-11-22 17:56:39 +01008280void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8281 bool on,
8282 const sp<AudioOutputDescriptor>& outputDesc,
8283 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008284 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008285{
jiabin9a3361e2019-10-01 09:38:30 -07008286 if (deviceTypes.empty()) {
8287 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008288 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008289 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008290 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008291 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008292 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008293 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008294 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8295 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008296 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008297 }
8298 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008299 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8300 // ignored
8301 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008302 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008303 if (!outputDesc->isMuted(volumeSource)) {
8304 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008305 return;
8306 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008307 if (outputDesc->decMuteCount(volumeSource) == 0) {
8308 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008309 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008310 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008311 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008312 delayMs);
8313 }
8314 }
8315}
8316
François Gaffie53615e22015-03-19 09:24:12 +01008317bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8318{
François Gaffiec005e562018-11-06 15:04:49 +01008319 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008320 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8321 return true;
8322 }
8323
8324 // has known usage?
8325 switch (paa->usage) {
8326 case AUDIO_USAGE_UNKNOWN:
8327 case AUDIO_USAGE_MEDIA:
8328 case AUDIO_USAGE_VOICE_COMMUNICATION:
8329 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8330 case AUDIO_USAGE_ALARM:
8331 case AUDIO_USAGE_NOTIFICATION:
8332 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8333 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8334 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8335 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8336 case AUDIO_USAGE_NOTIFICATION_EVENT:
8337 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8338 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8339 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8340 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008341 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008342 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008343 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008344 case AUDIO_USAGE_EMERGENCY:
8345 case AUDIO_USAGE_SAFETY:
8346 case AUDIO_USAGE_VEHICLE_STATUS:
8347 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008348 break;
8349 default:
8350 return false;
8351 }
8352 return true;
8353}
8354
François Gaffie2110e042015-03-24 08:41:51 +01008355audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8356{
8357 return mEngine->getForceUse(usage);
8358}
8359
Eric Laurent96d1dda2022-03-14 17:14:19 +01008360bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008361 return isStateInCall(mEngine->getPhoneState());
8362}
8363
Eric Laurent96d1dda2022-03-14 17:14:19 +01008364bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008365 return is_state_in_call(state);
8366}
8367
Eric Laurentf9cccec2022-11-16 19:12:00 +01008368bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008369 audio_mode_t mode = mEngine->getPhoneState();
8370 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008371 || (mode == AUDIO_MODE_CALL_SCREEN)
8372 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008373}
8374
Eric Laurentf9cccec2022-11-16 19:12:00 +01008375bool AudioPolicyManager::isInCallOrScreening() const {
8376 audio_mode_t mode = mEngine->getPhoneState();
8377 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8378}
8379
Eric Laurentd60560a2015-04-10 11:31:20 -07008380void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8381{
8382 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008383 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008384 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008385 sourceDesc->sinkDevice()->equals(deviceDesc))
8386 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008387 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008388 }
8389 }
8390
8391 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8392 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8393 bool release = false;
8394 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8395 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8396 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8397 source->ext.device.type == deviceDesc->type()) {
8398 release = true;
8399 }
8400 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008401 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008402 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8403 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8404 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008405 sink->ext.device.type == deviceDesc->type() &&
8406 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8407 || strncmp(sink->ext.device.address, address,
8408 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008409 release = true;
8410 }
8411 }
8412 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008413 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8414 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008415 }
8416 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008417
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008418 mInputs.clearSessionRoutesForDevice(deviceDesc);
8419
Francois Gaffie716e1432019-01-14 16:58:59 +01008420 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008421}
8422
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008423void AudioPolicyManager::modifySurroundFormats(
8424 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008425 std::unordered_set<audio_format_t> enforcedSurround(
8426 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008427 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008428 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008429 allSurround.insert(pair.first);
8430 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8431 }
Phil Burk09bc4612016-02-24 15:58:15 -08008432
8433 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8434 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008435 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008436 // This is the resulting set of formats depending on the surround mode:
8437 // 'all surround' = allSurround
8438 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8439 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8440 // 'manual surround' = mManualSurroundFormats
8441 // AUTO: formats v 'enforced surround'
8442 // ALWAYS: formats v 'all surround' v 'enforced surround'
8443 // NEVER: formats ^ 'non-surround'
8444 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008445
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008446 std::unordered_set<audio_format_t> formatSet;
8447 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8448 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008449 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008450 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008451 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008452 formatSet.insert(*formatIter);
8453 }
8454 }
8455 } else {
8456 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8457 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008458 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008459
jiabin81772902018-04-02 17:52:27 -07008460 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008461 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008462 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8463 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8464 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008465 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008466 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8467 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8468 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008469 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008470 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008471 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008472 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008473 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008474 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008475}
8476
jiabin06e4bab2019-07-29 10:13:34 -07008477void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8478 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008479 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8480 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8481
8482 // If NEVER, then remove support for channelMasks > stereo.
8483 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008484 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8485 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008486 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008487 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008488 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008489 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008490 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008491 }
8492 }
jiabin81772902018-04-02 17:52:27 -07008493 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8494 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8495 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008496 bool supports5dot1 = false;
8497 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008498 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008499 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8500 supports5dot1 = true;
8501 break;
8502 }
8503 }
8504 // If not then add 5.1 support.
8505 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008506 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008507 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008508 }
Phil Burk09bc4612016-02-24 15:58:15 -08008509 }
8510}
8511
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008512void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008513 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008514 const sp<IOProfile>& profile) {
8515 if (!profile->hasDynamicAudioProfile()) {
8516 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008517 }
François Gaffie112b0af2015-11-19 16:13:25 +01008518
jiabin12537fc2023-10-12 17:56:08 +00008519 audio_port_v7 devicePort;
8520 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008521
jiabin12537fc2023-10-12 17:56:08 +00008522 audio_port_v7 mixPort;
8523 profile->toAudioPort(&mixPort);
8524 mixPort.ext.mix.handle = ioHandle;
8525
8526 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8527 if (status != NO_ERROR) {
8528 ALOGE("%s failed to query the attributes of the mix port", __func__);
8529 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008530 }
jiabin12537fc2023-10-12 17:56:08 +00008531
8532 std::set<audio_format_t> supportedFormats;
8533 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8534 supportedFormats.insert(mixPort.audio_profiles[i].format);
8535 }
8536 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8537 mReportedFormatsMap[devDesc] = formats;
8538
8539 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8540 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8541 modifySurroundFormats(devDesc, &formats);
8542 size_t modifiedNumProfiles = 0;
8543 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8544 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8545 formats.end()) {
8546 // Skip the format that is not present after modifying surround formats.
8547 continue;
8548 }
8549 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8550 sizeof(struct audio_profile));
8551 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8552 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8553 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8554 modifySurroundChannelMasks(&channels);
8555 std::copy(channels.begin(), channels.end(),
8556 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8557 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8558 }
8559 mixPort.num_audio_profiles = modifiedNumProfiles;
8560 }
8561 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008562}
Eric Laurentd60560a2015-04-10 11:31:20 -07008563
Mikhail Naganovdc769682018-05-04 15:34:08 -07008564status_t AudioPolicyManager::installPatch(const char *caller,
8565 audio_patch_handle_t *patchHandle,
8566 AudioIODescriptorInterface *ioDescriptor,
8567 const struct audio_patch *patch,
8568 int delayMs)
8569{
8570 ssize_t index = mAudioPatches.indexOfKey(
8571 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8572 *patchHandle : ioDescriptor->getPatchHandle());
8573 sp<AudioPatch> patchDesc;
8574 status_t status = installPatch(
8575 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8576 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008577 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008578 }
8579 return status;
8580}
8581
8582status_t AudioPolicyManager::installPatch(const char *caller,
8583 ssize_t index,
8584 audio_patch_handle_t *patchHandle,
8585 const struct audio_patch *patch,
8586 int delayMs,
8587 uid_t uid,
8588 sp<AudioPatch> *patchDescPtr)
8589{
8590 sp<AudioPatch> patchDesc;
8591 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8592 if (index >= 0) {
8593 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008594 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008595 }
8596
8597 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8598 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8599 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8600 if (status == NO_ERROR) {
8601 if (index < 0) {
8602 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008603 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008604 } else {
8605 patchDesc->mPatch = *patch;
8606 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008607 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008608 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008609 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008610 }
8611 nextAudioPortGeneration();
8612 mpClientInterface->onAudioPatchListUpdate();
8613 }
8614 if (patchDescPtr) *patchDescPtr = patchDesc;
8615 return status;
8616}
8617
jiabinbce0c1d2020-10-05 11:20:18 -07008618bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8619{
8620 const TrackClientVector activeClients = output->getActiveClients();
8621 if (activeClients.empty()) {
8622 return true;
8623 }
8624 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8625 if (index < 0) {
8626 ALOGE("%s, no audio patch found while there are active clients on output %d",
8627 __func__, output->getId());
8628 return false;
8629 }
8630 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8631 DeviceVector routedDevices;
8632 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8633 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8634 patchDesc->mPatch.sinks[i].id);
8635 if (device == nullptr) {
8636 ALOGE("%s, no audio device found with id(%d)",
8637 __func__, patchDesc->mPatch.sinks[i].id);
8638 return false;
8639 }
8640 routedDevices.add(device);
8641 }
8642 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008643 if (client->isInvalid()) {
8644 // No need to take care about invalidated clients.
8645 continue;
8646 }
jiabinbce0c1d2020-10-05 11:20:18 -07008647 sp<DeviceDescriptor> preferredDevice =
8648 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8649 if (mEngine->getOutputDevicesForAttributes(
8650 client->attributes(), preferredDevice, false) == routedDevices) {
8651 return false;
8652 }
8653 }
8654 return true;
8655}
8656
8657sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008658 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008659 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8660 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008661{
8662 for (const auto& device : devices) {
8663 // TODO: This should be checking if the profile supports the device combo.
8664 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008665 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8666 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008667 return nullptr;
8668 }
8669 }
8670 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8671 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008672 status_t status = desc->open(halConfig, mixerConfig, devices,
8673 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008674 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008675 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008676 return nullptr;
8677 }
jiabin14b50cc2023-12-13 19:01:52 +00008678 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8679 auto portConfig = desc->getConfig();
8680 for (const auto& device : devices) {
8681 device->setPreferredConfig(&portConfig);
8682 }
8683 }
jiabinbce0c1d2020-10-05 11:20:18 -07008684
8685 // Here is where the out_set_parameters() for card & device gets called
8686 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8687 const audio_devices_t deviceType = device->type();
8688 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008689 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008690 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8691 mpClientInterface->setParameters(output, String8(param));
8692 free(param);
8693 }
jiabin12537fc2023-10-12 17:56:08 +00008694 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008695 if (!profile->hasValidAudioProfile()) {
8696 ALOGW("%s() missing param", __func__);
8697 desc->close();
8698 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008699 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8700 // Reopen the output with the best audio profile picked by APM when the profile supports
8701 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008702 desc->close();
8703 output = AUDIO_IO_HANDLE_NONE;
8704 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8705 profile->pickAudioProfile(
8706 config.sample_rate, config.channel_mask, config.format);
8707 config.offload_info.sample_rate = config.sample_rate;
8708 config.offload_info.channel_mask = config.channel_mask;
8709 config.offload_info.format = config.format;
8710
jiabina84c3d32022-12-02 18:59:55 +00008711 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008712 if (status != NO_ERROR) {
8713 return nullptr;
8714 }
8715 }
8716
8717 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008718 setOutputDevices(__func__, desc,
8719 devices,
8720 true,
8721 0,
8722 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008723 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8724 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8725
jiabinbce0c1d2020-10-05 11:20:18 -07008726 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8727 sp<AudioPolicyMix> policyMix;
8728 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8729 policyMix->setOutput(desc);
8730 desc->mPolicyMix = policyMix;
8731 } else {
8732 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008733 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008734 }
8735
baek.kim -61c20122022-07-27 10:05:32 +00008736 } else if (hasPrimaryOutput() && speaker != nullptr
8737 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008738 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8739 // no duplicated output for:
8740 // - direct outputs
8741 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008742 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008743 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8744
8745 //TODO: configure audio effect output stage here
8746
8747 // open a duplicating output thread for the new output and the primary output
8748 sp<SwAudioOutputDescriptor> dupOutputDesc =
8749 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8750 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8751 if (status == NO_ERROR) {
8752 // add duplicated output descriptor
8753 addOutput(duplicatedOutput, dupOutputDesc);
8754 } else {
8755 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8756 mPrimaryOutput->mIoHandle, output);
8757 desc->close();
8758 removeOutput(output);
8759 nextAudioPortGeneration();
8760 return nullptr;
8761 }
8762 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008763 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8764 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8765 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008766 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008767 }
jiabinbce0c1d2020-10-05 11:20:18 -07008768 return desc;
8769}
8770
jiabinf1c73972022-04-14 16:28:52 -07008771status_t AudioPolicyManager::getDevicesForAttributes(
8772 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8773 // Devices are determined in the following precedence:
8774 //
8775 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8776 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8777 //
8778 // If no such dynamic policy then
8779 // 2) Devices containing an active client using setPreferredDevice
8780 // with same strategy as the attributes.
8781 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8782 //
8783 // If no corresponding active client with setPreferredDevice then
8784 // 3) Devices associated with the strategy determined by the attributes
8785 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8786 //
8787 // See related getOutputForAttrInt().
8788
8789 // check dynamic policies but only for primary descriptors (secondary not used for audible
8790 // audio routing, only used for duplication for playback capture)
8791 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008792 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008793 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008794 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8795 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8796 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008797 if (status != OK) {
8798 return status;
8799 }
8800
8801 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8802 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8803 // as they are unaffected by device/stream volume
8804 // (per SwAudioOutputDescriptor::isFixedVolume()).
8805 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8806 ) {
8807 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8808 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8809 devices.add(deviceDesc);
8810 } else {
8811 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8812 // which selects setPreferredDevice if active. This means forVolume call
8813 // will take an active setPreferredDevice, if such exists.
8814
8815 devices = mEngine->getOutputDevicesForAttributes(
8816 attr, nullptr /* preferredDevice */, false /* fromCache */);
8817 }
8818
8819 if (forVolume) {
8820 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8821 // for single volume control in AudioService (such relationship should exist if
8822 // SPEAKER_SAFE is present).
8823 //
8824 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8825 DeviceVector speakerSafeDevices =
8826 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8827 if (!speakerSafeDevices.isEmpty()) {
8828 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8829 devices.remove(speakerSafeDevices);
8830 }
8831 }
8832
8833 return NO_ERROR;
8834}
8835
8836status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8837 AudioProfileVector& audioProfiles,
8838 uint32_t flags,
8839 bool isInput) {
8840 for (const auto& hwModule : mHwModules) {
8841 // the MSD module checks for different conditions
8842 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8843 continue;
8844 }
8845 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8846 : hwModule->getOutputProfiles();
8847 for (const auto& profile : ioProfiles) {
8848 if (!profile->areAllDevicesSupported(devices) ||
8849 !profile->isCompatibleProfileForFlags(
8850 flags, false /*exactMatchRequiredForInputFlags*/)) {
8851 continue;
8852 }
8853 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8854 }
8855 }
8856
8857 if (!isInput) {
8858 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8859 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8860 if (msdModule != nullptr) {
8861 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8862 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8863 for (const auto &profile: msdModule->getOutputProfiles()) {
8864 if (!profile->asAudioPort()->isDirectOutput()) {
8865 continue;
8866 }
8867 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8868 }
8869 } else {
8870 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8871 }
8872 }
8873 }
8874
8875 return NO_ERROR;
8876}
8877
jiabin3ff8d7d2022-12-13 06:27:44 +00008878sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8879 const audio_config_t *config,
8880 audio_output_flags_t flags,
8881 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008882 closeOutput(outputDesc->mIoHandle);
8883 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8884 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8885 if (preferredOutput == nullptr) {
8886 ALOGE("%s failed to reopen output device=%d, caller=%s",
8887 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008888 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008889 return preferredOutput;
8890}
8891
8892void AudioPolicyManager::reopenOutputsWithDevices(
8893 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8894 for (const auto& [output, devices] : outputsToReopen) {
8895 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8896 closeOutput(output);
8897 openOutputWithProfileAndDevice(desc->mProfile, devices);
8898 }
jiabina84c3d32022-12-02 18:59:55 +00008899}
8900
jiabinc44b3462022-12-08 12:52:31 -08008901PortHandleVector AudioPolicyManager::getClientsForStream(
8902 audio_stream_type_t streamType) const {
8903 PortHandleVector clients;
8904 for (size_t i = 0; i < mOutputs.size(); ++i) {
8905 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8906 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8907 }
8908 return clients;
8909}
8910
8911void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8912 PortHandleVector clients;
8913 for (auto stream : streams) {
8914 PortHandleVector clientsForStream = getClientsForStream(stream);
8915 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8916 }
8917 mpClientInterface->invalidateTracks(clients);
8918}
8919
jiabin220eea12024-05-17 17:55:20 +00008920void AudioPolicyManager::updateClientsInternalMute(
8921 const sp<android::SwAudioOutputDescriptor> &desc) {
8922 if (!desc->isBitPerfect() ||
8923 !com::android::media::audioserver::
8924 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
8925 // This is only used for bit perfect output now.
8926 return;
8927 }
8928 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
8929 bool bitPerfectClientInternalMute = false;
8930 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
8931 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
8932 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
8933 bitPerfectClient = client;
8934 continue;
8935 }
8936 bool muted = false;
8937 if (client->stream() == AUDIO_STREAM_SYSTEM) {
8938 // System sound is muted.
8939 muted = true;
8940 } else {
8941 bitPerfectClientInternalMute = true;
8942 }
8943 if (client->setInternalMute(muted)) {
8944 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
8945 if (!result.ok()) {
8946 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
8947 continue;
8948 }
8949 media::TrackInternalMuteInfo info;
8950 info.portId = result.value();
8951 info.muted = client->getInternalMute();
8952 clientsInternalMute.push_back(std::move(info));
8953 }
8954 }
8955 if (bitPerfectClient != nullptr &&
8956 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
8957 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
8958 if (result.ok()) {
8959 media::TrackInternalMuteInfo info;
8960 info.portId = result.value();
8961 info.muted = bitPerfectClient->getInternalMute();
8962 clientsInternalMute.push_back(std::move(info));
8963 } else {
8964 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
8965 __func__, bitPerfectClient->portId());
8966 }
8967 }
8968 if (!clientsInternalMute.empty()) {
8969 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
8970 status != NO_ERROR) {
8971 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
8972 }
8973 }
8974}
8975
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008976} // namespace android