blob: cc442997561eb60e274482d8841881b052551b4f [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganov3754b642024-04-17 18:31:04 +0000132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000341 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
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 Naganov2b61ab52024-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 Naganov2b61ab52024-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 Naganov2b61ab52024-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 Hunged722372023-09-18 22:00:21 +0000474 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);
570 for (size_t i = 0; i < mOutputs.size(); i++) {
571 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
572 // mute media strategies and delay device switch by the largest
573 // This avoid sending the music tail into the earpiece or headset.
574 setStrategyMute(musicStrategy, true, desc);
575 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
576 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
577 nullptr, true /*fromCache*/).types());
578 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800579 // Toggle the device state: UNAVAILABLE -> AVAILABLE
580 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100581 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800582 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800583 device_address, device_name,
584 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
587 status);
588 return status;
589 }
590
591 status = setDeviceConnectionState(device,
592 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800593 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800594 if (status != NO_ERROR) {
595 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
596 status);
597 return status;
598 }
599
600 return NO_ERROR;
601}
602
Pattydd807582021-11-04 21:01:03 +0800603status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
604 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800605{
Pattydd807582021-11-04 21:01:03 +0800606 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800607 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800608 std::unordered_set<audio_format_t> formatSet;
609 sp<HwModule> primaryModule =
610 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700611 if (primaryModule == nullptr) {
612 ALOGE("%s() unable to get primary module", __func__);
613 return NO_INIT;
614 }
Pattydd807582021-11-04 21:01:03 +0800615
616 DeviceTypeSet audioDeviceSet;
617
618 switch(device) {
619 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
620 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
621 break;
622 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800623 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
624 break;
625 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
626 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800627 break;
628 default:
629 ALOGE("%s() device type 0x%08x not supported", __func__, device);
630 return BAD_VALUE;
631 }
632
jiabin9a3361e2019-10-01 09:38:30 -0700633 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800634 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800635 for (const auto& device : declaredDevices) {
636 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800637 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800638 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800639 return status;
640}
641
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100642DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
643{
644 DeviceVector rxSinkdevices{};
645 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
646 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
647 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
648 auto rxSinkDevice = rxSinkdevices.itemAt(0);
649 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
650 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
651 // retrieve Rx Source device descriptor
652 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
653 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
654
655 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
656 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
657 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
658 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
659 return DeviceVector(rxSinkDevice);
660 }
661 }
662 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
663 // the device returned is not necessarily reachable via this output
664 // (filter later by setOutputDevices())
665 return getNewOutputDevices(mPrimaryOutput, fromCache);
666}
667
668status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
669{
François Gaffiedb1755b2023-09-01 11:50:35 +0200670 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100671 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
672 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
673 }
674 return INVALID_OPERATION;
675}
676
677status_t AudioPolicyManager::updateCallRoutingInternal(
678 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700679{
680 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100681 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700682 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200683 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700684 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100685 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700686 }
François Gaffie11d30102018-11-02 16:09:09 +0100687
Francois Gaffie716e1432019-01-14 16:58:59 +0100688 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100689 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200690
691 disconnectTelephonyAudioSource(mCallRxSourceClient);
692 disconnectTelephonyAudioSource(mCallTxSourceClient);
693
694 if (rxDevices.isEmpty()) {
695 ALOGW("%s() no selected output device", __func__);
696 return INVALID_OPERATION;
697 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000698 if (txSourceDevice == nullptr) {
699 ALOGE("%s() selected input device not available", __func__);
700 return INVALID_OPERATION;
701 }
François Gaffiec005e562018-11-06 15:04:49 +0100702
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100703 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100704 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700705
François Gaffie9eb18552018-11-05 10:33:26 +0100706 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700707 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100708 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700709 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100710 // retrieve Rx Source and Tx Sink device descriptors
711 sp<DeviceDescriptor> rxSourceDevice =
712 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
713 String8(),
714 AUDIO_FORMAT_DEFAULT);
715 sp<DeviceDescriptor> txSinkDevice =
716 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
717 String8(),
718 AUDIO_FORMAT_DEFAULT);
719
720 // RX and TX Telephony device are declared by Primary Audio HAL
721 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
722 (telephonyRxModule->getHalVersionMajor() >= 3)) {
723 if (rxSourceDevice == 0 || txSinkDevice == 0) {
724 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100725 ALOGE("%s() no telephony Tx and/or RX device", __func__);
726 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100727 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100728 // createAudioPatchInternal now supports both HW / SW bridging
729 createRxPatch = true;
730 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100731 } else {
732 // If the RX device is on the primary HW module, then use legacy routing method for
733 // voice calls via setOutputDevice() on primary output.
734 // Otherwise, create two audio patches for TX and RX path.
735 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
736 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700737 // If the TX device is also on the primary HW module, setOutputDevice() will take care
738 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100739 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
740 (txSinkDevice != 0);
741 }
742 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
743 // Otherwise, create two audio patches for TX and RX path.
744 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200745 if (!hasPrimaryOutput()) {
746 ALOGW("%s() no primary output available", __func__);
747 return INVALID_OPERATION;
748 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530749 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700750 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200751 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800752 // If the TX device is on the primary HW module but RX device is
753 // on other HW module, SinkMetaData of telephony input should handle it
754 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700755 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700756 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100757 // terminate active capture if on the same HW module as the call TX source device
758 // FIXME: would be better to refine to only inputs whose profile connects to the
759 // call TX device but this information is not in the audio patch and logic here must be
760 // symmetric to the one in startInput()
761 for (const auto& activeDesc : mInputs.getActiveInputs()) {
762 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
763 closeActiveClients(activeDesc);
764 }
765 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200766 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800767 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100768 if (waitMs != nullptr) {
769 *waitMs = muteWaitMs;
770 }
771 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800772}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700773
Mikhail Naganov100f0122018-11-29 11:22:16 -0800774bool AudioPolicyManager::isDeviceOfModule(
775 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
776 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
777 if (module != 0) {
778 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
779 .indexOf(devDesc) != NAME_NOT_FOUND
780 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
781 .indexOf(devDesc) != NAME_NOT_FOUND;
782 }
783 return false;
784}
785
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200786void AudioPolicyManager::connectTelephonyRxAudioSource()
787{
Francois Gaffie601801d2021-06-22 13:27:39 +0200788 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200789 const struct audio_port_config source = {
790 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
791 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
792 };
793 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100794
795 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
796 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
797 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
798 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200799 ALOGE_IF(mCallRxSourceClient == nullptr,
800 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200801}
802
Francois Gaffie601801d2021-06-22 13:27:39 +0200803void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200804{
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 if (clientDesc == nullptr) {
806 return;
807 }
808 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
809 "%s error stopping audio source", __func__);
810 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200811}
812
813void AudioPolicyManager::connectTelephonyTxAudioSource(
814 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
815 uint32_t delayMs)
816{
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200818 if (srcDevice == nullptr || sinkDevice == nullptr) {
819 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
820 return;
821 }
822 PatchBuilder patchBuilder;
823 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
824 ALOGV("%s between source %s and sink %s", __func__,
825 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200826 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200827 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
828
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200829 struct audio_port_config source = {};
830 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100831 mCallTxSourceClient = new SourceClientDescriptor(
832 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
833 mCommunnicationStrategy, toVolumeSource(aa), true);
834 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
835
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200836 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
837 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
839 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200840 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
841 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200842 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200843 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200844}
845
Eric Laurente0720872014-03-11 09:30:41 -0700846void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700847{
848 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100849 // store previous phone state for management of sonification strategy below
850 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100851 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100852
853 if (mEngine->setPhoneState(state) != NO_ERROR) {
854 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700855 return;
856 }
François Gaffie2110e042015-03-24 08:41:51 +0100857 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700858 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700859 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700860 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800861 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700862 }
863
François Gaffie2110e042015-03-24 08:41:51 +0100864 /**
865 * Switching to or from incall state or switching between telephony and VoIP lead to force
866 * routing command.
867 */
Eric Laurent74b71512019-11-06 17:21:57 -0800868 bool force = ((isStateInCall(oldState) != isStateInCall(state))
869 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700870
871 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700872 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700873
Eric Laurente552edb2014-03-10 17:42:56 -0700874 int delayMs = 0;
875 if (isStateInCall(state)) {
876 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100877 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
878 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700879 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700880 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700881 // mute media and sonification strategies and delay device switch by the largest
882 // latency of any output where either strategy is active.
883 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100884 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
885 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
886 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700887 (delayMs < (int)desc->latency()*2)) {
888 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700889 }
François Gaffiec005e562018-11-06 15:04:49 +0100890 setStrategyMute(musicStrategy, true, desc);
891 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
892 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
893 nullptr, true /*fromCache*/).types());
894 setStrategyMute(sonificationStrategy, true, desc);
895 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
896 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
897 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700898 }
899 }
900
François Gaffiedb1755b2023-09-01 11:50:35 +0200901 if (state == AUDIO_MODE_IN_CALL) {
902 (void)updateCallRouting(false /*fromCache*/, delayMs);
903 } else {
904 if (oldState == AUDIO_MODE_IN_CALL) {
905 disconnectTelephonyAudioSource(mCallRxSourceClient);
906 disconnectTelephonyAudioSource(mCallTxSourceClient);
907 }
908 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100909 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
910 // force routing command to audio hardware when ending call
911 // even if no device change is needed
912 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
913 rxDevices = mPrimaryOutput->devices();
914 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530915 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700916 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700917 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700918
jiabin3ff8d7d2022-12-13 06:27:44 +0000919 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700920 // reevaluate routing on all outputs in case tracks have been started during the call
921 for (size_t i = 0; i < mOutputs.size(); i++) {
922 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100923 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200924 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
925 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000926 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
927 // If the device is using preferred mixer attributes, the output need to reopen
928 // with default configuration when the new selected devices are different from
929 // current routing devices.
930 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
931 continue;
932 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530933 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200934 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700935 }
936 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000937 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700938
Eric Laurent96d1dda2022-03-14 17:14:19 +0100939 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
940
Eric Laurente552edb2014-03-10 17:42:56 -0700941 if (isStateInCall(state)) {
942 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700943 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800944 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700945 }
946
947 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100948 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
949 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700950}
951
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700952audio_mode_t AudioPolicyManager::getPhoneState() {
953 return mEngine->getPhoneState();
954}
955
Eric Laurente0720872014-03-11 09:30:41 -0700956void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100957 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700958{
François Gaffie2110e042015-03-24 08:41:51 +0100959 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700960 if (config == mEngine->getForceUse(usage)) {
961 return;
962 }
Eric Laurente552edb2014-03-10 17:42:56 -0700963
François Gaffie2110e042015-03-24 08:41:51 +0100964 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
965 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
966 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700967 }
François Gaffie2110e042015-03-24 08:41:51 +0100968 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
969 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
970 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700971
972 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700973 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800974
Eric Laurent22fcda22019-05-17 16:28:47 -0700975 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
976 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800977 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700978 }
979
Eric Laurentdc462862016-07-19 12:29:53 -0700980 //FIXME: workaround for truncated touch sounds
981 // to be removed when the problem is handled by system UI
982 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700983 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
984 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
985 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700986
987 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100988 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700989}
990
Eric Laurente0720872014-03-11 09:30:41 -0700991void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700992{
993 ALOGV("setSystemProperty() property %s, value %s", property, value);
994}
995
Dorin Drimusecc9f422022-03-09 17:57:40 +0100996// Find an MSD output profile compatible with the parameters passed.
997// When "directOnly" is set, restrict search to profiles for direct outputs.
998sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
999 const DeviceVector& devices,
1000 uint32_t samplingRate,
1001 audio_format_t format,
1002 audio_channel_mask_t channelMask,
1003 audio_output_flags_t flags,
1004 bool directOnly)
1005{
1006 flags = getRelevantFlags(flags, directOnly);
1007
1008 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1009 if (msdModule != nullptr) {
1010 // for the msd module check if there are patches to the output devices
1011 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1012 HwModuleCollection modules;
1013 modules.add(msdModule);
1014 return searchCompatibleProfileHwModules(
1015 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1016 flags, directOnly);
1017 }
1018 }
1019 return nullptr;
1020}
1021
Michael Chana94fbb22018-04-24 14:31:19 +10001022// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1023// search to profiles for direct outputs.
1024sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001025 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001026 uint32_t samplingRate,
1027 audio_format_t format,
1028 audio_channel_mask_t channelMask,
1029 audio_output_flags_t flags,
1030 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001031{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001032 flags = getRelevantFlags(flags, directOnly);
1033
1034 return searchCompatibleProfileHwModules(
1035 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1036}
1037
1038audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1039 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001040 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001041 // only retain flags that will drive the direct output profile selection
1042 // if explicitly requested
1043 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001044 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1046 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001047 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001048 return flags;
1049}
Eric Laurent861a6282015-05-18 15:40:16 -07001050
Dorin Drimusecc9f422022-03-09 17:57:40 +01001051sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1052 const HwModuleCollection& hwModules,
1053 const DeviceVector& devices,
1054 uint32_t samplingRate,
1055 audio_format_t format,
1056 audio_channel_mask_t channelMask,
1057 audio_output_flags_t flags,
1058 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001059 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001061 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001062 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 samplingRate, NULL /*updatedSamplingRate*/,
1064 format, NULL /*updatedFormat*/,
1065 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001066 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 continue;
1068 }
1069 // reject profiles not corresponding to a device currently available
1070 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1071 continue;
1072 }
1073 // reject profiles if connected device does not support codec
1074 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1075 continue;
1076 }
1077 if (!directOnly) {
1078 return curProfile;
1079 }
1080
1081 // when searching for direct outputs, if several profiles are compatible, give priority
1082 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001083 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001084 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001085 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001086 }
1087 profile = curProfile;
1088 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1089 break;
1090 }
Eric Laurente552edb2014-03-10 17:42:56 -07001091 }
1092 }
Eric Laurent861a6282015-05-18 15:40:16 -07001093 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001094}
1095
Eric Laurentfa0f6742021-08-17 18:39:44 +02001096sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001097 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098{
1099 for (const auto& hwModule : mHwModules) {
1100 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001101 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001102 continue;
1103 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001104 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001105 // reject profiles not corresponding to a device currently available
1106 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1107 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1108 continue;
1109 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001110 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1111 != devices.size()) {
1112 continue;
1113 }
1114 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001115 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1116 return curProfile;
1117 }
1118 }
1119 return nullptr;
1120}
1121
Eric Laurentf4e63452017-11-06 19:31:46 +00001122audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001123{
François Gaffiec005e562018-11-06 15:04:49 +01001124 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001125
1126 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1127 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1128 // format, flags, etc. This may result in some discrepancy for functions that utilize
1129 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1130 // and AudioSystem::getOutputSamplingRate().
1131
François Gaffie11d30102018-11-02 16:09:09 +01001132 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001133 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1134 if (stream == AUDIO_STREAM_MUSIC &&
1135 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1136 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1137 }
1138 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001139
François Gaffie11d30102018-11-02 16:09:09 +01001140 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1141 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001142 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001143}
1144
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001145status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1146 const audio_attributes_t *srcAttr,
1147 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001148{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 if (srcAttr != NULL) {
1150 if (!isValidAttributes(srcAttr)) {
1151 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1152 __func__,
1153 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1154 srcAttr->tags);
1155 return BAD_VALUE;
1156 }
1157 *dstAttr = *srcAttr;
1158 } else {
1159 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1160 ALOGE("%s: invalid stream type", __func__);
1161 return BAD_VALUE;
1162 }
François Gaffiec005e562018-11-06 15:04:49 +01001163 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001164 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001165
1166 // Only honor audibility enforced when required. The client will be
1167 // forced to reconnect if the forced usage changes.
1168 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001169 dstAttr->flags = static_cast<audio_flags_mask_t>(
1170 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001171 }
1172
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001173 return NO_ERROR;
1174}
1175
Kevin Rocard153f92d2018-12-18 18:33:28 -08001176status_t AudioPolicyManager::getOutputForAttrInt(
1177 audio_attributes_t *resultAttr,
1178 audio_io_handle_t *output,
1179 audio_session_t session,
1180 const audio_attributes_t *attr,
1181 audio_stream_type_t *stream,
1182 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001183 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001184 audio_output_flags_t *flags,
1185 audio_port_handle_t *selectedDeviceId,
1186 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001187 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001188 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001189 bool *isSpatialized,
1190 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001191{
François Gaffiec005e562018-11-06 15:04:49 +01001192 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001193 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001194 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001195 const sp<DeviceDescriptor> requestedDevice =
1196 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1197
Eric Laurent8a1095a2019-11-08 14:44:16 -08001198 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001199 *isSpatialized = false;
1200
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001201 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1202 if (status != NO_ERROR) {
1203 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001204 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001205 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001206 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001207 }
François Gaffiec005e562018-11-06 15:04:49 +01001208 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001209
François Gaffiec005e562018-11-06 15:04:49 +01001210 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1211 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001212
Oscar Azucena873d10f2023-01-12 18:34:42 -08001213 bool usePrimaryOutputFromPolicyMixes = false;
1214
Kevin Rocard153f92d2018-12-18 18:33:28 -08001215 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1216 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1217 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001218 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001219 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1220 .channel_mask = config->channel_mask,
1221 .format = config->format,
1222 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001223 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001224 mAvailableOutputDevices, requestedDevice, primaryMix,
1225 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001226 if (status != OK) {
1227 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001228 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001229
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001231 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1232 && !audio_is_linear_pcm(config->format)) {
1233 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001234 return BAD_VALUE;
1235 }
1236 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001237 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001238 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1239 primaryMix->mDeviceAddress,
1240 AUDIO_FORMAT_DEFAULT);
1241 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001242 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001243 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1244 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001245 // if a direct output can be opened to deliver the track's multi-channel content to the
1246 // output rather than being downmixed by the primary output, then use this direct
1247 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1248 // mix.
1249 bool tryDirectForChannelMask = policyDesc != nullptr
1250 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1251 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001252 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001253 audio_io_handle_t newOutput;
1254 status = openDirectOutput(
1255 *stream, session, config,
1256 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001257 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001258 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001259 policyDesc = mOutputs.valueFor(newOutput);
1260 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001261 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001262 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001263 policyDesc = nullptr;
1264 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001265 }
1266 if (policyDesc != nullptr) {
1267 policyDesc->mPolicyMix = primaryMix;
1268 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001269 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1270 : AUDIO_PORT_HANDLE_NONE;
1271 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1272 // Remove direct flag as it is not on a direct output.
1273 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1274 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001275
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001276 ALOGV("getOutputForAttr() returns output %d", *output);
1277 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1278 *outputType = API_OUT_MIX_PLAYBACK;
1279 } else {
1280 *outputType = API_OUTPUT_LEGACY;
1281 }
1282 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001283 } else {
1284 if (policyMixDevice != nullptr) {
1285 ALOGE("%s, try to use primary mix but no output found", __func__);
1286 return INVALID_OPERATION;
1287 }
1288 // Fallback to default engine selection as the selected primary mix device is not
1289 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001290 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001291 }
François Gaffiec005e562018-11-06 15:04:49 +01001292 // Virtual sources must always be dynamicaly or explicitly routed
1293 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1294 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1295 return BAD_VALUE;
1296 }
1297 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1298 // in order to let the choice of the order to future vendor engine
1299 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001300
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001301 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001302 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001303 }
1304
Nadav Barb2f18162018-07-18 13:01:53 +03001305 // Set incall music only if device was explicitly set, and fallback to the device which is
1306 // chosen by the engine if not.
1307 // FIXME: provide a more generic approach which is not device specific and move this back
1308 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001309 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001310 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001311 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001312 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001313 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001314 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001315 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001316 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001317 }
1318 }
1319
François Gaffiec005e562018-11-06 15:04:49 +01001320 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1321 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1322 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001323
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001324 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001325 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001326 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001327 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001328 ALOGV("%s() Using MSD devices %s instead of devices %s",
1329 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001330 } else {
1331 *output = AUDIO_IO_HANDLE_NONE;
1332 }
1333 }
1334 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001335 sp<PreferredMixerAttributesInfo> info = nullptr;
1336 if (outputDevices.size() == 1) {
1337 info = getPreferredMixerAttributesInfo(
1338 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001339 mEngine->getProductStrategyForAttributes(*resultAttr),
1340 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001341 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1342 // and it is currently active.
1343 if (info != nullptr && info->getUid() != uid &&
1344 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1345 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001346 info = nullptr;
1347 }
1348 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001349 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001350 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001351 // The client will be active if the client is currently preferred mixer owner and the
1352 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001353 *isBitPerfect = (info != nullptr
1354 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001355 && info->getUid() == uid
1356 && *output != AUDIO_IO_HANDLE_NONE
1357 // When bit-perfect output is selected for the preferred mixer attributes owner,
1358 // only need to consider the config matches.
1359 && mOutputs.valueFor(*output)->isConfigurationMatched(
1360 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001361 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001362 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001363 AudioProfileVector profiles;
1364 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1365 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001366 const auto channels = profiles[0]->getChannels();
1367 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1368 config->channel_mask = *channels.begin();
1369 }
1370 const auto sampleRates = profiles[0]->getSampleRates();
1371 if (!sampleRates.empty() &&
1372 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1373 config->sample_rate = *sampleRates.begin();
1374 }
jiabinf1c73972022-04-14 16:28:52 -07001375 config->format = profiles[0]->getFormat();
1376 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001377 return INVALID_OPERATION;
1378 }
Paul McLeanaa981192015-03-21 09:55:15 -07001379
François Gaffiec005e562018-11-06 15:04:49 +01001380 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001381 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001382 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001383 *selectedDeviceId = outputDevice->getId();
1384 break;
1385 }
1386 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001387
Eric Laurent8a1095a2019-11-08 14:44:16 -08001388 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1389 *outputType = API_OUTPUT_TELEPHONY_TX;
1390 } else {
1391 *outputType = API_OUTPUT_LEGACY;
1392 }
1393
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001394 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1395
1396 return NO_ERROR;
1397}
1398
1399status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1400 audio_io_handle_t *output,
1401 audio_session_t session,
1402 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001403 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001404 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001405 audio_output_flags_t *flags,
1406 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001407 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001408 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001409 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001410 bool *isSpatialized,
1411 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001412{
1413 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1414 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1415 return INVALID_OPERATION;
1416 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001417 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001418 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001419 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001420 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001421 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001422 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001423 const sp<DeviceDescriptor> requestedDevice =
1424 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1425
1426 // Prevent from storing invalid requested device id in clients
1427 const audio_port_handle_t sanitizedRequestedPortId =
1428 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1429 *selectedDeviceId = sanitizedRequestedPortId;
1430
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001431 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001432 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001433 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1434 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001435 if (status != NO_ERROR) {
1436 return status;
1437 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001438 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001439 if (secondaryOutputs != nullptr) {
1440 for (auto &secondaryMix : secondaryMixes) {
1441 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1442 if (outputDesc != nullptr &&
1443 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1444 secondaryOutputs->push_back(outputDesc->mIoHandle);
1445 weakSecondaryOutputDescs.push_back(outputDesc);
1446 }
1447 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001448 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001449
Eric Laurent8fc147b2018-07-22 19:13:55 -07001450 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001451 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001452 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001453 };
jiabin4ef93452019-09-10 14:29:54 -07001454 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001455
Eric Laurentc209fe42020-06-05 18:11:23 -07001456 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001457 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001458 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001459 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001460 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001461 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001462 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001463 std::move(weakSecondaryOutputDescs),
1464 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001465 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001466
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001467 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1468 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001469
Eric Laurente83b55d2014-11-14 10:06:21 -08001470 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001471}
1472
Eric Laurentc529cf62020-04-17 18:19:10 -07001473status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1474 audio_session_t session,
1475 const audio_config_t *config,
1476 audio_output_flags_t flags,
1477 const DeviceVector &devices,
1478 audio_io_handle_t *output) {
1479
1480 *output = AUDIO_IO_HANDLE_NONE;
1481
1482 // skip direct output selection if the request can obviously be attached to a mixed output
1483 // and not explicitly requested
1484 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1485 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1486 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1487 return NAME_NOT_FOUND;
1488 }
1489
1490 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1491 // This prevents creating an offloaded track and tearing it down immediately after start
1492 // when audioflinger detects there is an active non offloadable effect.
1493 // FIXME: We should check the audio session here but we do not have it in this context.
1494 // This may prevent offloading in rare situations where effects are left active by apps
1495 // in the background.
1496 sp<IOProfile> profile;
1497 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1498 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1499 profile = getProfileForOutput(
1500 devices, config->sample_rate, config->format, config->channel_mask,
1501 flags, true /* directOnly */);
1502 }
1503
1504 if (profile == nullptr) {
1505 return NAME_NOT_FOUND;
1506 }
1507
1508 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1509 for (size_t i = 0; i < mOutputs.size(); i++) {
1510 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1511 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1512 // reuse direct output if currently open by the same client
1513 // and configured with same parameters
1514 if ((config->sample_rate == desc->getSamplingRate()) &&
1515 (config->format == desc->getFormat()) &&
1516 (config->channel_mask == desc->getChannelMask()) &&
1517 (session == desc->mDirectClientSession)) {
1518 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001519 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001520 mOutputs.keyAt(i), session);
1521 *output = mOutputs.keyAt(i);
1522 return NO_ERROR;
1523 }
1524 }
1525 }
1526
1527 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001528 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1529 return NAME_NOT_FOUND;
1530 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1531 // MMAP gracefully handles lack of an exclusive track resource by mixing
1532 // above the audio framework. For AAudio to know that the limit is reached,
1533 // return an error.
1534 return NAME_NOT_FOUND;
1535 } else {
1536 // Close outputs on this profile, if available, to free resources for this request
1537 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1538 const auto desc = mOutputs.valueAt(i);
1539 if (desc->mProfile == profile) {
1540 closeOutput(desc->mIoHandle);
1541 }
1542 }
1543 }
1544 }
1545
1546 // Unable to close streams to find free resources for this request
1547 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001548 return NAME_NOT_FOUND;
1549 }
1550
Atneya Nairb16666a2023-12-11 20:18:33 -08001551 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001552
Michael Chan6fb34492020-12-08 15:44:49 +11001553 // An MSD patch may be using the only output stream that can service this request. Release
1554 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001555 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001556
Eric Laurentf1f22e72021-07-13 14:04:14 +02001557 status_t status =
1558 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001559
1560 // only accept an output with the requested parameters
1561 if (status != NO_ERROR ||
1562 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1563 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1564 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1565 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1566 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1567 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1568 config->channel_mask, outputDesc->getChannelMask());
1569 if (*output != AUDIO_IO_HANDLE_NONE) {
1570 outputDesc->close();
1571 }
1572 // fall back to mixer output if possible when the direct output could not be open
1573 if (audio_is_linear_pcm(config->format) &&
1574 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1575 return NAME_NOT_FOUND;
1576 }
1577 *output = AUDIO_IO_HANDLE_NONE;
1578 return BAD_VALUE;
1579 }
1580 outputDesc->mDirectOpenCount = 1;
1581 outputDesc->mDirectClientSession = session;
1582
1583 addOutput(*output, outputDesc);
1584 mPreviousOutputs = mOutputs;
1585 ALOGV("%s returns new direct output %d", __func__, *output);
1586 mpClientInterface->onAudioPortListUpdate();
1587 return NO_ERROR;
1588}
1589
François Gaffie11d30102018-11-02 16:09:09 +01001590audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1591 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001592 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001593 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001594 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001595 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001596 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001597 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001598 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001599{
Andy Hungc88b0642018-04-27 15:42:35 -07001600 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001601
jiabine375d412019-02-26 12:54:53 -08001602 // Discard haptic channel mask when forcing muting haptic channels.
1603 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001604 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1605 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001606
Eric Laurente552edb2014-03-10 17:42:56 -07001607 // open a direct output if required by specified parameters
1608 //force direct flag if offload flag is set: offloading implies a direct output stream
1609 // and all common behaviors are driven by checking only the direct flag
1610 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001611 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1612 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001613 }
Nadav Bar766fb022018-01-07 12:18:03 +02001614 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1615 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001616 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001617
1618 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1619
Eric Laurente83b55d2014-11-14 10:06:21 -08001620 // only allow deep buffering for music stream type
1621 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001622 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001623 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001624 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001625 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1626 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001627 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001628 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001629 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001630 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001631 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001632 audio_is_linear_pcm(config->format) &&
1633 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001634 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001635 AUDIO_OUTPUT_FLAG_DIRECT);
1636 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001637 }
Eric Laurente552edb2014-03-10 17:42:56 -07001638
Carter Hsua3abb402021-10-26 11:11:20 +08001639 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1640 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1641 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1642 }
1643
Eric Laurentf9230d52024-01-26 18:49:09 +01001644 // Use the spatializer output if the content can be spatialized, no preferred mixer
1645 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001646 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001647 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001648 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001649 && prefMixerConfigInfo == nullptr
1650 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001651 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001652 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001653 }
1654
Eric Laurentc529cf62020-04-17 18:19:10 -07001655 audio_config_t directConfig = *config;
1656 directConfig.channel_mask = channelMask;
1657 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1658 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001659 return output;
1660 }
1661
Eric Laurent14cbfca2016-03-17 09:42:16 -07001662 // A request for HW A/V sync cannot fallback to a mixed output because time
1663 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001664 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001665 return AUDIO_IO_HANDLE_NONE;
1666 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001667 // A request for Tuner cannot fallback to a mixed output
1668 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1669 return AUDIO_IO_HANDLE_NONE;
1670 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001671
Eric Laurente552edb2014-03-10 17:42:56 -07001672 // ignoring channel mask due to downmix capability in mixer
1673
1674 // open a non direct output
1675
1676 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001677 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001678 // get which output is suitable for the specified stream. The actual
1679 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001680 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001681 if (prefMixerConfigInfo != nullptr) {
1682 for (audio_io_handle_t outputHandle : outputs) {
1683 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1684 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1685 output = outputHandle;
1686 break;
1687 }
1688 }
1689 if (output == AUDIO_IO_HANDLE_NONE) {
1690 // No output open with the preferred profile. Open a new one.
1691 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1692 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1693 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1694 config.format = prefMixerConfigInfo->getConfigBase().format;
1695 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1696 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1697 &config, prefMixerConfigInfo->getFlags());
1698 if (preferredOutput == nullptr) {
1699 ALOGE("%s failed to open output with preferred mixer config", __func__);
1700 } else {
1701 output = preferredOutput->mIoHandle;
1702 }
1703 }
1704 } else {
1705 // at this stage we should ignore the DIRECT flag as no direct output could be
1706 // found earlier
1707 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1708 output = selectOutput(
1709 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1710 }
Eric Laurente552edb2014-03-10 17:42:56 -07001711 }
François Gaffie11d30102018-11-02 16:09:09 +01001712 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001713 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001714 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001715
Eric Laurente552edb2014-03-10 17:42:56 -07001716 return output;
1717}
1718
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001719sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001720 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1721 mAvailableInputDevices);
1722 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1723}
1724
1725DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1726 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1727 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728}
1729
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001730const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001731 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001732 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1733 if (msdModule != 0) {
1734 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1735 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1736 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1737 const struct audio_port_config *source = &patch->mPatch.sources[j];
1738 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1739 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001740 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001741 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 }
1743 }
1744 }
1745 return msdPatches;
1746}
1747
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001748bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1749 ssize_t index = mAudioPatches.indexOfKey(handle);
1750 if (index < 0) {
1751 return false;
1752 }
1753 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1754 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1755 if (msdModule == nullptr) {
1756 return false;
1757 }
1758 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1759 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1760 return true;
1761 }
1762 index = getMsdOutputPatches().indexOfKey(handle);
1763 if (index < 0) {
1764 return false;
1765 }
1766 return true;
1767}
1768
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001769status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1770 const InputProfileCollection &inputProfiles,
1771 const OutputProfileCollection &outputProfiles,
1772 const sp<DeviceDescriptor> &sourceDevice,
1773 const sp<DeviceDescriptor> &sinkDevice,
1774 AudioProfileVector& sourceProfiles,
1775 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001777 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001778 return NO_INIT;
1779 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001781 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001782 return NO_INIT;
1783 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001784 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001785 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1786 inProfile->supportsDevice(sourceDevice)) {
1787 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788 }
1789 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001791 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001792 outProfile->supportsDevice(sinkDevice)) {
1793 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 }
1795 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001796 return NO_ERROR;
1797}
1798
1799status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1800 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1801 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1802{
Dean Wheatley16809da2022-12-09 14:55:46 +11001803 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1804 static const std::vector<audio_format_t> formatsOrder = {{
1805 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001806 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1807 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001808 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1809 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1810 // preferred).
1811 std::vector<audio_channel_mask_t> masks = {{
1812 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1813 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1814 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1815 // insert index masks (higher counts most preferred) as preferred over position masks
1816 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1817 masks.insert(
1818 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1819 }
1820 return masks;
1821 }();
1822
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001823 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001824 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1825 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1828 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001829 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830 }
1831 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1832 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1833 sinkConfig->format = bestSinkConfig.format;
1834 // For encoded streams force direct flag to prevent downstream mixing.
1835 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1836 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001837 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1838 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001840 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1841 // raw and IEC61937 framed streams.
1842 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1843 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1844 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001845 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1846 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001847 sourceConfig->channel_mask =
1848 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1849 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1850 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001851 sourceConfig->format = bestSinkConfig.format;
1852 // Copy input stream directly without any processing (e.g. resampling).
1853 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1854 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1855 if (hwAvSync) {
1856 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1857 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1858 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1859 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1860 }
1861 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1862 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1863 sinkConfig->config_mask |= config_mask;
1864 sourceConfig->config_mask |= config_mask;
1865 return NO_ERROR;
1866}
1867
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001868PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1869 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001870{
1871 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1873 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1874 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1875 if (deviceModule == nullptr) {
1876 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1877 return patchBuilder;
1878 }
1879 const InputProfileCollection inputProfiles = msdIsSource ?
1880 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1881 const OutputProfileCollection outputProfiles = msdIsSource ?
1882 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1883
1884 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1885 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1886 device : getMsdAudioOutDevices().itemAt(0);
1887 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1888
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1890 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001891 AudioProfileVector sourceProfiles;
1892 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001893 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1894 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001895 for (auto hwAvSync : { true, false }) {
1896 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1897 sourceProfiles, sinkProfiles) != NO_ERROR) {
1898 continue;
1899 }
1900 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1901 &sinkConfig) == NO_ERROR) {
1902 // Found a matching config. Re-create PatchBuilder with this config.
1903 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1904 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001905 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001906 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 " supporting PCM format conversion.", __func__);
1908 return patchBuilder;
1909}
1910
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001911status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001912 DeviceVector devices;
1913 if (outputDevices != nullptr && outputDevices->size() > 0) {
1914 devices.add(*outputDevices);
1915 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001916 // Use media strategy for unspecified output device. This should only
1917 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1918 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001919 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001920 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001921 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001922 }
Michael Chan6fb34492020-12-08 15:44:49 +11001923 std::vector<PatchBuilder> patchesToCreate;
1924 for (auto i = 0u; i < devices.size(); ++i) {
1925 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001927 }
1928 // Retain only the MSD patches associated with outputDevices request.
1929 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001930 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001931 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1932 auto retainedPatch = false;
1933 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1934 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1935 patchesToRemove.removeItemsAt(i);
1936 retainedPatch = true;
1937 break;
1938 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001939 }
Michael Chan6fb34492020-12-08 15:44:49 +11001940 if (retainedPatch) {
1941 it = patchesToCreate.erase(it);
1942 continue;
1943 }
1944 ++it;
1945 }
1946 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1947 return NO_ERROR;
1948 }
1949 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1950 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001951 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 }
Michael Chan6fb34492020-12-08 15:44:49 +11001953 status_t status = NO_ERROR;
1954 for (const auto &p : patchesToCreate) {
1955 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1956 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1957 char message[256];
1958 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1959 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1960 currStatus == NO_ERROR ? "Success" : "Error",
1961 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1962 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1963 if (currStatus == NO_ERROR) {
1964 ALOGD("%s", message);
1965 } else {
1966 ALOGE("%s", message);
1967 if (status == NO_ERROR) {
1968 status = currStatus;
1969 }
1970 }
1971 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001972 return status;
1973}
1974
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001975void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1976 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001977 for (size_t i = 0; i < msdPatches.size(); i++) {
1978 const auto& patch = msdPatches[i];
1979 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1980 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1981 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1982 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1983 releaseAudioPatch(patch->getHandle(), mUidCached);
1984 break;
1985 }
1986 }
1987 }
1988}
1989
Dorin Drimus94d94412022-02-02 09:05:02 +01001990bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001991 DeviceVector devicesToCheck =
1992 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001993 AudioPatchCollection msdPatches = getMsdOutputPatches();
1994 for (size_t i = 0; i < msdPatches.size(); i++) {
1995 const auto& patch = msdPatches[i];
1996 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1997 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1998 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1999 const auto& foundDevice = devicesToCheck.getDevice(
2000 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2001 if (foundDevice != nullptr) {
2002 devicesToCheck.remove(foundDevice);
2003 if (devicesToCheck.isEmpty()) {
2004 return true;
2005 }
2006 }
2007 }
2008 }
2009 }
2010 return false;
2011}
2012
Eric Laurente0720872014-03-11 09:30:41 -07002013audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002014 audio_output_flags_t flags,
2015 audio_format_t format,
2016 audio_channel_mask_t channelMask,
2017 uint32_t samplingRate,
2018 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002019{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2021 "%s called with format %#x", __func__, format);
2022
jiabinebb6af42020-06-09 17:31:17 -07002023 // Return the output that haptic-generating attached to when 1) session id is specified,
2024 // 2) haptic-generating effect exists for given session id and 3) the output that
2025 // haptic-generating effect attached to is in given outputs.
2026 if (sessionId != AUDIO_SESSION_NONE) {
2027 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2028 sessionId, FX_IID_HAPTICGENERATOR);
2029 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2030 return hapticGeneratingOutput;
2031 }
2032 }
2033
Eric Laurent16c66dd2019-05-01 17:54:10 -07002034 // Flags disqualifying an output: the match must happen before calling selectOutput()
2035 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2036 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2037
2038 // Flags expressing a functional request: must be honored in priority over
2039 // other criteria
2040 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2041 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002042 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2043 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002044 // Flags expressing a performance request: have lower priority than serving
2045 // requested sampling rate or channel mask
2046 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2047 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2048 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2049
2050 const audio_output_flags_t functionalFlags =
2051 (audio_output_flags_t)(flags & kFunctionalFlags);
2052 const audio_output_flags_t performanceFlags =
2053 (audio_output_flags_t)(flags & kPerformanceFlags);
2054
2055 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2056
Eric Laurente552edb2014-03-10 17:42:56 -07002057 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002058 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002059 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002060 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002061 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002062 // with tiebreak preferring the minimum number of extra functional flags
2063 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 // 3: the output supporting the exact channel mask
2065 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002066 // 5: the output with the highest sampling rate if the requested sample rate is
2067 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002068 // 6: the output with the highest number of requested performance flags
2069 // 7: the output with the bit depth the closest to the requested one
2070 // 8: the primary output
2071 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002072
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 // matching criteria values in priority order for best matching output so far
2074 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002075
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2077 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2078 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002079
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002080 for (audio_io_handle_t output : outputs) {
2081 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002082 // matching criteria values in priority order for current output
2083 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002084
Eric Laurent16c66dd2019-05-01 17:54:10 -07002085 if (outputDesc->isDuplicated()) {
2086 continue;
2087 }
2088 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2089 continue;
2090 }
Eric Laurent8838a382014-09-08 16:44:28 -07002091
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 // If haptic channel is specified, use the haptic output if present.
2093 // When using haptic output, same audio format and sample rate are required.
2094 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002095 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002096 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2097 continue;
2098 }
2099 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002100 && format == outputDesc->getFormat()
2101 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 currentMatchCriteria[0] = outputHapticChannelCount;
2103 }
2104
2105 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002106 const int matchingFunctionalFlags =
2107 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2108 const int totalFunctionalFlags =
2109 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2110 // Prefer matching functional flags, but subtract unnecessary functional flags.
2111 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002112
2113 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002114 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2115 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002116 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2117 channelCount <= outputChannelCount) {
2118 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002119 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2120 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002122 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002123 currentMatchCriteria[3] = outputChannelCount;
2124 }
2125
2126 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002127 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002128 int diff; // avoid unsigned integer overflow.
2129 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2130
2131 // prefer the closest output sampling rate greater than or equal to target
2132 // if none exists, prefer the closest output sampling rate less than target.
2133 //
2134 // criteria is offset to make non-negative.
2135 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002136 }
2137
2138 // performance flags match
2139 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2140
2141 // format match
2142 if (format != AUDIO_FORMAT_INVALID) {
2143 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002144 PolicyAudioPort::kFormatDistanceMax -
2145 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002146 }
2147
2148 // primary output match
2149 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2150
2151 // compare match criteria by priority then value
2152 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2153 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2154 bestMatchCriteria = currentMatchCriteria;
2155 bestOutput = output;
2156
2157 std::stringstream result;
2158 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2159 std::ostream_iterator<int>(result, " "));
2160 ALOGV("%s new bestOutput %d criteria %s",
2161 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002162 }
2163 }
2164
Eric Laurent16c66dd2019-05-01 17:54:10 -07002165 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002166}
2167
Eric Laurent8fc147b2018-07-22 19:13:55 -07002168status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002169{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002170 ALOGV("%s portId %d", __FUNCTION__, portId);
2171
2172 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2173 if (outputDesc == 0) {
2174 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002175 return BAD_VALUE;
2176 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002177 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002178
Eric Laurent8fc147b2018-07-22 19:13:55 -07002179 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002180 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002181
Eric Laurent733ce942017-12-07 12:18:25 -08002182 status_t status = outputDesc->start();
2183 if (status != NO_ERROR) {
2184 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002185 }
2186
Eric Laurent97ac8712018-07-27 18:59:02 -07002187 uint32_t delayMs;
2188 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002189
2190 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002191 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002192 if (status == DEAD_OBJECT) {
2193 sp<SwAudioOutputDescriptor> desc =
2194 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2195 if (desc == nullptr) {
2196 // This is not common, it may indicate something wrong with the HAL.
2197 ALOGE("%s unable to open output with default config", __func__);
2198 return status;
2199 }
2200 desc->mUsePreferredMixerAttributes = true;
2201 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002202 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002203 }
jiabina84c3d32022-12-02 18:59:55 +00002204
2205 // If the client is the first one active on preferred mixer parameters, reopen the output
2206 // if the current mixer parameters doesn't match the preferred one.
2207 if (outputDesc->devices().size() == 1) {
2208 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2209 outputDesc->devices()[0]->getId(), client->strategy());
2210 if (info != nullptr && info->getUid() == client->uid()) {
2211 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2212 info->getConfigBase(), info->getFlags())) {
2213 stopSource(outputDesc, client);
2214 outputDesc->stop();
2215 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2216 config.channel_mask = info->getConfigBase().channel_mask;
2217 config.sample_rate = info->getConfigBase().sample_rate;
2218 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002219 sp<SwAudioOutputDescriptor> desc =
2220 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2221 if (desc == nullptr) {
2222 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002223 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002224 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002225 // Intentionally return error to let the client side resending request for
2226 // creating and starting.
2227 return DEAD_OBJECT;
2228 }
2229 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002230 if (info->getActiveClientCount() == 1 &&
2231 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2232 // If it is first bit-perfect client, reroute all clients that will be routed to
2233 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2234 PortHandleVector clientsToInvalidate;
2235 for (size_t i = 0; i < mOutputs.size(); i++) {
2236 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002237 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002238 continue;
2239 }
2240 for (const auto& c : mOutputs[i]->getClientIterable()) {
2241 clientsToInvalidate.push_back(c->portId());
2242 }
2243 }
2244 if (!clientsToInvalidate.empty()) {
2245 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2246 __func__);
2247 mpClientInterface->invalidateTracks(clientsToInvalidate);
2248 }
2249 }
jiabina84c3d32022-12-02 18:59:55 +00002250 }
2251 }
2252
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002253 if (client->hasPreferredDevice()) {
2254 // playback activity with preferred device impacts routing occurred, inform upper layers
2255 mpClientInterface->onRoutingUpdated();
2256 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002257 if (delayMs != 0) {
2258 usleep(delayMs * 1000);
2259 }
2260
2261 return status;
2262}
2263
Eric Laurent96d1dda2022-03-14 17:14:19 +01002264bool AudioPolicyManager::isLeUnicastActive() const {
2265 if (isInCall()) {
2266 return true;
2267 }
2268 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2269}
2270
2271bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2272 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2273 return false;
2274 }
2275 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2276 ALOGV("%s active %d", __func__, active);
2277 return active;
2278}
2279
Eric Laurent97ac8712018-07-27 18:59:02 -07002280status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2281 const sp<TrackClientDescriptor>& client,
2282 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002283{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002284 // cannot start playback of STREAM_TTS if any other output is being used
2285 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002286
2287 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002289 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002290 auto clientStrategy = client->strategy();
2291 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002292 if (stream == AUDIO_STREAM_TTS) {
2293 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002294 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002295 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002296 return INVALID_OPERATION;
2297 } else {
2298 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2299 }
2300 } else {
2301 // some playback other than beacon starts
2302 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2303 }
2304
Eric Laurent77305a62016-07-25 16:39:22 -07002305 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002306 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002307 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002308
François Gaffie11d30102018-11-02 16:09:09 +01002309 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002310 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002311 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002312 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002313 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002314 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002315 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002316 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002317 } else {
2318 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002319 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002320 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2321 AUDIO_FORMAT_DEFAULT);
2322 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2323 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002324 }
2325
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002326 // requiresMuteCheck is false when we can bypass mute strategy.
2327 // It covers a common case when there is no materially active audio
2328 // and muting would result in unnecessary delay and dropped audio.
2329 const uint32_t outputLatencyMs = outputDesc->latency();
2330 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002331 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002332
Eric Laurente552edb2014-03-10 17:42:56 -07002333 // increment usage count for this stream on the requested output:
2334 // NOTE that the usage count is the same for duplicated output and hardware output which is
2335 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002336 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002337
2338 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002339 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002340 // Preferred device may be exclusive, use only if no other active clients on this output
2341 devices = DeviceVector(
2342 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2343 } else {
2344 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2345 }
François Gaffie11d30102018-11-02 16:09:09 +01002346 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002347 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002348 }
2349 }
Eric Laurente552edb2014-03-10 17:42:56 -07002350
François Gaffiec005e562018-11-06 15:04:49 +01002351 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002352 selectOutputForMusicEffects();
2353 }
2354
François Gaffie1c878552018-11-22 16:53:21 +01002355 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002356 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002357 if (devices.isEmpty()) {
2358 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002359 }
François Gaffiec005e562018-11-06 15:04:49 +01002360 bool shouldWait =
2361 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2362 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2363 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002364 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002365 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002366 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002367 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002368 // An output has a shared device if
2369 // - managed by the same hw module
2370 // - supports the currently selected device
2371 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002372 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002373
Eric Laurent77305a62016-07-25 16:39:22 -07002374 // force a device change if any other output is:
2375 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002376 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002377 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002378 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002379 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002380 // change the device currently selected by the other output.
2381 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002382 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002383 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002384 force = true;
2385 }
2386 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002387 // a notification so that audio focus effect can propagate, or that a mute/unmute
2388 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002389 const uint32_t latencyMs = desc->latency();
2390 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2391
2392 if (shouldWait && isActive && (waitMs < latencyMs)) {
2393 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002394 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002395
2396 // Require mute check if another output is on a shared device
2397 // and currently active to have proper drain and avoid pops.
2398 // Note restoring AudioTracks onto this output needs to invoke
2399 // a volume ramp if there is no mute.
2400 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002401 }
2402 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002403
jiabin3ff8d7d2022-12-13 06:27:44 +00002404 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2405 // If the output is open with preferred mixer attributes, but the routed device is
2406 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2407 // changed.
2408 return DEAD_OBJECT;
2409 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002410 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302411 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2412 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002413
Eric Laurente552edb2014-03-10 17:42:56 -07002414 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002415 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002416 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002417 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002418 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002419 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002420 outputDesc->useHwGain() /*force*/)) {
2421 // request AudioService to reinitialize the volume curves asynchronously
2422 ALOGE("checkAndSetVolume failed, requesting volume range init");
2423 mpClientInterface->onVolumeRangeInitRequest();
2424 };
Eric Laurente552edb2014-03-10 17:42:56 -07002425
2426 // update the outputs if starting an output with a stream that can affect notification
2427 // routing
2428 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002429
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002430 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002431 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002432 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002433 }
Eric Laurentdc462862016-07-19 12:29:53 -07002434
2435 if (waitMs > muteWaitMs) {
2436 *delayMs = waitMs - muteWaitMs;
2437 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002438
2439 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2440 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2441 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2442 // change occurs after the MixerThread starts and causes a stream volume
2443 // glitch.
2444 //
2445 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002446 }
Eric Laurentdc462862016-07-19 12:29:53 -07002447
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002448 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002449 mEngine->getForceUse(
2450 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002451 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002452 }
2453
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 // Automatically enable the remote submix input when output is started on a re routing mix
2455 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002456 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2457 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002458 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2459 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2460 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002461 "remote-submix",
2462 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002463 }
2464
Eric Laurent96d1dda2022-03-14 17:14:19 +01002465 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2466
Eric Laurente552edb2014-03-10 17:42:56 -07002467 return NO_ERROR;
2468}
2469
Eric Laurent96d1dda2022-03-14 17:14:19 +01002470void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2471 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2472 bool isUnicastActive = isLeUnicastActive();
2473
2474 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002475 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002476 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2477 for (size_t i = 0; i < mOutputs.size(); i++) {
2478 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2479 if (desc != ignoredOutput && desc->isActive()
2480 && ((isUnicastActive &&
2481 !desc->devices().
2482 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2483 || (wasUnicastActive &&
2484 !desc->devices().getDevicesFromTypes(
2485 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2486 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2487 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002488 if (desc->mUsePreferredMixerAttributes && force) {
2489 // If the device is using preferred mixer attributes, the output need to reopen
2490 // with default configuration when the new selected devices are different from
2491 // current routing devices.
2492 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2493 continue;
2494 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302495 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002496 // re-apply device specific volume if not done by setOutputDevice()
2497 if (!force) {
2498 applyStreamVolumes(desc, newDevices.types(), delayMs);
2499 }
2500 }
2501 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002502 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002503 }
2504}
2505
Eric Laurent8fc147b2018-07-22 19:13:55 -07002506status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002507{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002508 ALOGV("%s portId %d", __FUNCTION__, portId);
2509
2510 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2511 if (outputDesc == 0) {
2512 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002513 return BAD_VALUE;
2514 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002515 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002516
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002517 if (client->hasPreferredDevice(true)) {
2518 // playback activity with preferred device impacts routing occurred, inform upper layers
2519 mpClientInterface->onRoutingUpdated();
2520 }
2521
Eric Laurent97ac8712018-07-27 18:59:02 -07002522 ALOGV("stopOutput() output %d, stream %d, session %d",
2523 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002524
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002526
Eric Laurent733ce942017-12-07 12:18:25 -08002527 if (status == NO_ERROR ) {
2528 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002529 } else {
2530 return status;
2531 }
2532
2533 if (outputDesc->devices().size() == 1) {
2534 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2535 outputDesc->devices()[0]->getId(), client->strategy());
2536 if (info != nullptr && info->getUid() == client->uid()) {
2537 info->decreaseActiveClient();
2538 if (info->getActiveClientCount() == 0) {
2539 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2540 }
2541 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002542 }
2543 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002544}
2545
Eric Laurent97ac8712018-07-27 18:59:02 -07002546status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2547 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002548{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002549 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002551 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002552 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002553
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002554 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2555
François Gaffie1c878552018-11-22 16:53:21 +01002556 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2557 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 // Automatically disable the remote submix input when output is stopped on a
2559 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002560 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002561 if (isSingleDeviceType(
2562 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002563 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002564 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002565 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2566 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002567 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002568 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002569 }
2570 }
2571 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002572 if (client->hasPreferredDevice(true) &&
2573 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002574 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002575 forceDeviceUpdate = true;
2576 }
2577
Eric Laurente552edb2014-03-10 17:42:56 -07002578 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002579 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002580
Eric Laurente552edb2014-03-10 17:42:56 -07002581 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002582 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002583 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002584 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002585
2586 // If the routing does not change, if an output is routed on a device using HwGain
2587 // (aka setAudioPortConfig) and there are still active clients following different
2588 // volume group(s), force reapply volume
2589 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2590 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2591
Eric Laurente552edb2014-03-10 17:42:56 -07002592 // delay the device switch by twice the latency because stopOutput() is executed when
2593 // the track stop() command is received and at that time the audio track buffer can
2594 // still contain data that needs to be drained. The latency only covers the audio HAL
2595 // and kernel buffers. Also the latency does not always include additional delay in the
2596 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302597 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002598 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002599
2600 // force restoring the device selection on other active outputs if it differs from the
2601 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002602 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002603 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002604 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002605 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002606 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002607 desc->isActive() &&
2608 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002609 (newDevices != desc->devices())) {
2610 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2611 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002612
jiabin3ff8d7d2022-12-13 06:27:44 +00002613 if (desc->mUsePreferredMixerAttributes && force) {
2614 // If the device is using preferred mixer attributes, the output need to
2615 // reopen with default configuration when the new selected devices are
2616 // different from current routing devices.
2617 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2618 continue;
2619 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302620 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002621
Eric Laurent57de36c2016-09-28 16:59:11 -07002622 // re-apply device specific volume if not done by setOutputDevice()
2623 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002624 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002625 }
Eric Laurente552edb2014-03-10 17:42:56 -07002626 }
2627 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002628 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002629 // update the outputs if stopping one with a stream that can affect notification routing
2630 handleNotificationRoutingForStream(stream);
2631 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002632
2633 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2634 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002635 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002636 }
2637
François Gaffiec005e562018-11-06 15:04:49 +01002638 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002639 selectOutputForMusicEffects();
2640 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002641
2642 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2643
Eric Laurente552edb2014-03-10 17:42:56 -07002644 return NO_ERROR;
2645 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002646 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002647 return INVALID_OPERATION;
2648 }
2649}
2650
jiabinbce0c1d2020-10-05 11:20:18 -07002651bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002652{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002653 ALOGV("%s portId %d", __FUNCTION__, portId);
2654
2655 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2656 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002657 // If an output descriptor is closed due to a device routing change,
2658 // then there are race conditions with releaseOutput from tracks
2659 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2660 // destroyed shortly thereafter.
2661 //
2662 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002664 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002665 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002666
2667 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002668
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302669 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2670 if (outputDesc->isClientActive(client)) {
2671 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2672 stopOutput(portId);
2673 }
2674
Eric Laurent8fc147b2018-07-22 19:13:55 -07002675 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2676 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002677 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002678 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002679 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002680 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002681 if (--outputDesc->mDirectOpenCount == 0) {
2682 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002683 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002684 }
2685 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302686
Andy Hung39efb7a2018-09-26 15:39:28 -07002687 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002688 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2689 // The output is pending reopened to query dynamic profiles and
2690 // there is no active clients
2691 closeOutput(outputDesc->mIoHandle);
2692 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2693 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2694 if (newOutputDesc == nullptr) {
2695 ALOGE("%s failed to open output", __func__);
2696 }
2697 return true;
2698 }
2699 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002700}
2701
Eric Laurentcaf7f482014-11-25 17:50:47 -08002702status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2703 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002704 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002705 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002706 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002707 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002708 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002709 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002710 input_type_t *inputType,
2711 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002712{
François Gaffiec005e562018-11-06 15:04:49 +01002713 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002714 "flags %#x attributes=%s requested device ID %d",
2715 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2716 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002717
Eric Laurentad2e7b92017-09-14 20:06:42 -07002718 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002719 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002720 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002721 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002722 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002723 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002724 sp<RecordClientDescriptor> clientDesc;
2725 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002726 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002727 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002728
2729 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2730 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2731 return INVALID_OPERATION;
2732 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002733
Francois Gaffie716e1432019-01-14 16:58:59 +01002734 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2735 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002736 }
2737
Paul McLean466dc8e2015-04-17 13:15:36 -06002738 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002739 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002740 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002741
Eric Laurentad2e7b92017-09-14 20:06:42 -07002742 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2743 // possible
2744 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2745 *input != AUDIO_IO_HANDLE_NONE) {
2746 ssize_t index = mInputs.indexOfKey(*input);
2747 if (index < 0) {
2748 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2749 status = BAD_VALUE;
2750 goto error;
2751 }
2752 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002753 RecordClientVector clients = inputDesc->getClientsForSession(session);
2754 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002755 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2756 status = BAD_VALUE;
2757 goto error;
2758 }
2759 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2760 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002761 // corresponds to a new client and is only permitted from the same UID.
2762 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763 if (clients.size() > 1) {
2764 for (const auto& client : clients) {
2765 // The client map is ordered by key values (portId) and portIds are allocated
2766 // incrementaly. So the first client in this list is the one opened by audio flinger
2767 // when the mmap stream is created and should be ignored as it does not correspond
2768 // to an actual client
2769 if (client == *clients.cbegin()) {
2770 continue;
2771 }
2772 if (uid != client->uid() && !client->isSilenced()) {
2773 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2774 uid, client->portId(), client->uid());
2775 status = INVALID_OPERATION;
2776 goto error;
2777 }
Eric Laurent331679c2018-04-16 17:03:16 -07002778 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002779 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002780 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002781 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002782
Eric Laurentfecbceb2021-02-09 14:46:43 +01002783 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002784 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002785 }
2786
2787 *input = AUDIO_IO_HANDLE_NONE;
2788 *inputType = API_INPUT_INVALID;
2789
Francois Gaffie716e1432019-01-14 16:58:59 +01002790 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002791 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002792 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002793 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002794 ALOGW("%s could not find input mix for attr %s",
2795 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002796 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002797 }
jiabinc1de2df2019-05-07 14:26:40 -07002798 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2799 String8(attr->tags + strlen("addr=")),
2800 AUDIO_FORMAT_DEFAULT);
2801 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002802 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002803 __func__, attributes.source, attributes.tags);
2804 status = BAD_VALUE;
2805 goto error;
2806 }
2807
Kevin Rocard25f9b052019-02-27 15:08:54 -08002808 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2809 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2810 } else {
2811 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2812 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002813 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002814 if (explicitRoutingDevice != nullptr) {
2815 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002816 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002817 // Prevent from storing invalid requested device id in clients
2818 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002819 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002820 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2821 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002822 }
François Gaffie11d30102018-11-02 16:09:09 +01002823 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002824 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002825 status = BAD_VALUE;
2826 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002827 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002828 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2829 *inputType = API_INPUT_MIX_CAPTURE;
2830 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002831 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2832 // there is an external policy, but this input is attached to a mix of recorders,
2833 // meaning it receives audio injected into the framework, so the recorder doesn't
2834 // know about it and is therefore considered "legacy"
2835 *inputType = API_INPUT_LEGACY;
2836 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002837 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002838 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002839 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002840 } else {
2841 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002842 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002843
Eric Laurent599c7582015-12-07 18:05:55 -08002844 }
2845
François Gaffiec005e562018-11-06 15:04:49 +01002846 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002847 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002849 AudioProfileVector profiles;
2850 status_t ret = getProfilesForDevices(
2851 DeviceVector(device), profiles, flags, true /*isInput*/);
2852 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002853 const auto channels = profiles[0]->getChannels();
2854 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2855 config->channel_mask = *channels.begin();
2856 }
2857 const auto sampleRates = profiles[0]->getSampleRates();
2858 if (!sampleRates.empty() &&
2859 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2860 config->sample_rate = *sampleRates.begin();
2861 }
jiabinf1c73972022-04-14 16:28:52 -07002862 config->format = profiles[0]->getFormat();
2863 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002864 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002865 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002866
Eric Laurent8f42ea12018-08-08 09:08:25 -07002867exit:
2868
François Gaffiec005e562018-11-06 15:04:49 +01002869 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2870 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002871
Francois Gaffie716e1432019-01-14 16:58:59 +01002872 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002873 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002874 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875
Mikhail Naganov2996f672019-04-18 12:29:59 -07002876 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002877 requestedDeviceId, attributes.source, flags,
2878 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002879 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002880 // Move (if found) effect for the client session to its input
2881 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002882 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002883
2884 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2885 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002886
Eric Laurent599c7582015-12-07 18:05:55 -08002887 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002888
2889error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002890 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002891}
2892
2893
François Gaffie11d30102018-11-02 16:09:09 +01002894audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002895 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002896 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002897 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002898 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002899 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002900{
2901 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002902 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002903 bool isSoundTrigger = false;
2904
François Gaffiec005e562018-11-06 15:04:49 +01002905 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002906 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2907 if (index >= 0) {
2908 input = mSoundTriggerSessions.valueFor(session);
2909 isSoundTrigger = true;
2910 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2911 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2912 } else {
2913 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002914 }
François Gaffiec005e562018-11-06 15:04:49 +01002915 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002916 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002917 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002918 }
2919
Carter Hsua3abb402021-10-26 11:11:20 +08002920 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2921 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2922 }
2923
Eric Laurentfe231122017-11-17 17:48:06 -08002924 // sampling rate and flags may be updated by getInputProfile
2925 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2926 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002927 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002928 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002929 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002930 // find a compatible input profile (not necessarily identical in parameters)
2931 sp<IOProfile> profile = getInputProfile(
2932 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2933 if (profile == nullptr) {
2934 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002935 }
jiabin2fd710d2022-05-02 23:20:22 +00002936
Glenn Kasten05ddca52016-02-11 08:17:12 -08002937 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002938 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002939 if (samplingRate == 0) {
2940 samplingRate = profileSamplingRate;
2941 }
Eric Laurente552edb2014-03-10 17:42:56 -07002942
Eric Laurent322b4d22015-04-03 15:57:54 -07002943 if (profile->getModuleHandle() == 0) {
2944 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002945 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002946 }
2947
Eric Laurentec376dc2021-04-08 20:41:22 +02002948 // Reuse an already opened input if a client with the same session ID already exists
2949 // on that input
2950 for (size_t i = 0; i < mInputs.size(); i++) {
2951 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2952 if (desc->mProfile != profile) {
2953 continue;
2954 }
2955 RecordClientVector clients = desc->clientsList();
2956 for (const auto &client : clients) {
2957 if (session == client->session()) {
2958 return desc->mIoHandle;
2959 }
2960 }
2961 }
2962
Eric Laurent3974e3b2017-12-07 17:58:43 -08002963 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002964 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002965 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002966 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002967 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002968 continue;
2969 }
2970 // if sound trigger, reuse input if used by other sound trigger on same session
2971 // else
2972 // reuse input if active client app is not in IDLE state
2973 //
2974 RecordClientVector clients = desc->clientsList();
2975 bool doClose = false;
2976 for (const auto& client : clients) {
2977 if (isSoundTrigger != client->isSoundTrigger()) {
2978 continue;
2979 }
2980 if (client->isSoundTrigger()) {
2981 if (session == client->session()) {
2982 return desc->mIoHandle;
2983 }
2984 continue;
2985 }
2986 if (client->active() && client->appState() != APP_STATE_IDLE) {
2987 return desc->mIoHandle;
2988 }
2989 doClose = true;
2990 }
2991 if (doClose) {
2992 closeInput(desc->mIoHandle);
2993 } else {
2994 i++;
2995 }
2996 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002997 }
2998
Eric Laurentfe231122017-11-17 17:48:06 -08002999 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003000
Eric Laurentfe231122017-11-17 17:48:06 -08003001 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3002 lConfig.sample_rate = profileSamplingRate;
3003 lConfig.channel_mask = profileChannelMask;
3004 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003005
François Gaffie11d30102018-11-02 16:09:09 +01003006 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003007
3008 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003009 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003010 (profileSamplingRate != lConfig.sample_rate) ||
3011 !audio_formats_match(profileFormat, lConfig.format) ||
3012 (profileChannelMask != lConfig.channel_mask)) {
3013 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003014 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003015 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003016 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003017 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003018 }
Eric Laurent599c7582015-12-07 18:05:55 -08003019 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003020 }
3021
Eric Laurentc722f302014-12-10 11:21:49 -08003022 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003023
Eric Laurent599c7582015-12-07 18:05:55 -08003024 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003025 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003026
Eric Laurent599c7582015-12-07 18:05:55 -08003027 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003028}
3029
Eric Laurent4eb58f12018-12-07 16:41:02 -08003030status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003031{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003032 ALOGV("%s portId %d", __FUNCTION__, portId);
3033
3034 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3035 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003037 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003038 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003039 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003040 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003041 if (client->active()) {
3042 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3043 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003044 }
3045
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 audio_session_t session = client->session();
3047
Eric Laurent4eb58f12018-12-07 16:41:02 -08003048 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003049
Eric Laurent4eb58f12018-12-07 16:41:02 -08003050 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003051
Eric Laurent4eb58f12018-12-07 16:41:02 -08003052 status_t status = inputDesc->start();
3053 if (status != NO_ERROR) {
3054 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003055 }
Eric Laurente552edb2014-03-10 17:42:56 -07003056
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003057 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003058 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003060
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 // indicate active capture to sound trigger service if starting capture from a mic on
3062 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003063 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003064 if (device != nullptr) {
3065 status = setInputDevice(input, device, true /* force */);
3066 } else {
3067 ALOGW("%s no new input device can be found for descriptor %d",
3068 __FUNCTION__, inputDesc->getId());
3069 status = BAD_VALUE;
3070 }
Eric Laurente552edb2014-03-10 17:42:56 -07003071
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003072 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003073 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003075 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003076 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3077 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003079 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003080
François Gaffie11d30102018-11-02 16:09:09 +01003081 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3082 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003083 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003084 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003086
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 // automatically enable the remote submix output when input is started if not
3088 // used by a policy mix of type MIX_TYPE_RECORDERS
3089 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003090 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003092 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003093 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003094 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3095 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003096 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003097 if (address != "") {
3098 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3099 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003100 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003101 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003102 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003103 } else if (status != NO_ERROR) {
3104 // Restore client activity state.
3105 inputDesc->setClientActive(client, false);
3106 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003107 }
3108
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003109 ALOGV("%s input %d source = %d status = %d exit",
3110 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003111
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003112 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003113}
3114
Eric Laurent8fc147b2018-07-22 19:13:55 -07003115status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003116{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003117 ALOGV("%s portId %d", __FUNCTION__, portId);
3118
3119 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3120 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003122 return BAD_VALUE;
3123 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003124 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003125 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003126 if (!client->active()) {
3127 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003128 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003129 }
Carter Hsue6139d52021-07-08 10:30:20 +08003130 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003131 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003132
Eric Laurent8f42ea12018-08-08 09:08:25 -07003133 inputDesc->stop();
3134 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003135 auto current_source = inputDesc->source();
3136 setInputDevice(input, getNewInputDevice(inputDesc),
3137 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003138 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003139 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003140 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003141 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003142 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3143 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003145 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003146
3147 // automatically disable the remote submix output when input is stopped if not
3148 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003149 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003150 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003151 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003153 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3154 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003155 }
3156 if (address != "") {
3157 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3158 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003159 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 }
3161 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003162 resetInputDevice(input);
3163
3164 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3165 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003166 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3167 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003169 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003170 }
3171 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003172 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003173 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003174}
3175
Eric Laurent8fc147b2018-07-22 19:13:55 -07003176void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003177{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003178 ALOGV("%s portId %d", __FUNCTION__, portId);
3179
3180 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3181 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003182 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003183 return;
3184 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003185 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003186 audio_io_handle_t input = inputDesc->mIoHandle;
3187
Eric Laurent8f42ea12018-08-08 09:08:25 -07003188 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003189
Andy Hung39efb7a2018-09-26 15:39:28 -07003190 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003191 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003192 if (inputDesc->getClientCount() > 0) {
3193 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003194 return;
3195 }
3196
Eric Laurent05b90f82014-08-27 15:32:29 -07003197 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003198 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003200}
3201
Eric Laurent8f42ea12018-08-08 09:08:25 -07003202void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003203{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003205
3206 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003207 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003208 }
3209}
3210
Eric Laurent8f42ea12018-08-08 09:08:25 -07003211void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3212{
3213 stopInput(portId);
3214 releaseInput(portId);
3215}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003216
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003217bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3218 if (input->clientsList().size() == 0
3219 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3220 return true;
3221 }
3222 for (const auto& client : input->clientsList()) {
3223 sp<DeviceDescriptor> device =
3224 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3225 client->session());
3226 if (!input->supportedDevices().contains(device)) {
3227 return true;
3228 }
3229 }
3230 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3231 return false;
3232}
3233
Eric Laurent0dd51852019-04-19 18:18:58 -07003234void AudioPolicyManager::checkCloseInputs() {
3235 // After connecting or disconnecting an input device, close input if:
3236 // - it has no client (was just opened to check profile) OR
3237 // - none of its supported devices are connected anymore OR
3238 // - one of its clients cannot be routed to one of its supported
3239 // devices anymore. Otherwise update device selection
3240 std::vector<audio_io_handle_t> inputsToClose;
3241 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003242 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003243 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003244 }
3245 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003246 for (const audio_io_handle_t handle : inputsToClose) {
3247 ALOGV("%s closing input %d", __func__, handle);
3248 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003249 }
Eric Laurentd4692962014-05-05 18:13:44 -07003250}
3251
François Gaffie251c7f02018-11-07 10:41:08 +01003252void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003253{
3254 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003255 if (indexMin < 0 || indexMax < 0) {
3256 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3257 return;
3258 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003259 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003260
3261 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003262 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3263 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003264 continue;
3265 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003266 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003267 }
Eric Laurente552edb2014-03-10 17:42:56 -07003268}
3269
Eric Laurente0720872014-03-11 09:30:41 -07003270status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003271 int index,
3272 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003273{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003274 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003275 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3276 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3277 return NO_ERROR;
3278 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003279 ALOGV("%s: stream %s attributes=%s", __func__,
3280 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003281 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003282}
3283
Eric Laurente0720872014-03-11 09:30:41 -07003284status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003285 int *index,
3286 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003287{
François Gaffiec005e562018-11-06 15:04:49 +01003288 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3289 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003290 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003291 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003292 deviceTypes = mEngine->getOutputDevicesForStream(
3293 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
jiabin9a3361e2019-10-01 09:38:30 -07003295 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003296}
3297
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003298status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003299 int index,
3300 audio_devices_t device)
3301{
3302 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003303 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3304 if (group == VOLUME_GROUP_NONE) {
3305 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003306 return BAD_VALUE;
3307 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003308 ALOGV("%s: group %d matching with %s index %d",
3309 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003310 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003311 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003312 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003313 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3314 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3315 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3316 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003317 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3318
3319 status = setVolumeCurveIndex(index, device, curves);
3320 if (status != NO_ERROR) {
3321 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3322 return status;
3323 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003324
jiabin9a3361e2019-10-01 09:38:30 -07003325 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003326 auto curCurvAttrs = curves.getAttributes();
3327 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3328 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003329 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003330 } else if (!curves.getStreamTypes().empty()) {
3331 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003332 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003333 } else {
3334 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3335 return BAD_VALUE;
3336 }
jiabin9a3361e2019-10-01 09:38:30 -07003337 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3338 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003339
François Gaffiecfe17322018-11-07 13:41:29 +01003340 // update volume on all outputs and streams matching the following:
3341 // - The requested stream (or a stream matching for volume control) is active on the output
3342 // - The device (or devices) selected by the engine for this stream includes
3343 // the requested device
3344 // - For non default requested device, currently selected device on the output is either the
3345 // requested device or one of the devices selected by the engine for this stream
3346 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3347 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003348 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003349 for (size_t i = 0; i < mOutputs.size(); i++) {
3350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003351 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003352
jiabin9a3361e2019-10-01 09:38:30 -07003353 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3354 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003355 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003356
3357 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003358 continue;
3359 }
3360 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3361 curDevices.find(device) == curDevices.end()) {
3362 continue;
3363 }
3364 bool applyVolume = false;
3365 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3366 curSrcDevices.insert(device);
3367 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003368 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3369 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003370 } else {
3371 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3372 }
3373 if (!applyVolume) {
3374 continue; // next output
3375 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003376 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3377 // If a higher priority strategy is active, and the output is routed to a device with a
3378 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003379 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003380 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003381 // If the volume source is active with higher priority source, ensure at least Sw Muted
3382 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003383 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3384 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3385 false /*preferredDevice*/);
3386 if (activeClients.empty()) {
3387 continue;
3388 }
3389 bool isPreempted = false;
3390 bool isHigherPriority = productStrategy < strategy;
3391 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003392 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003393 ALOGV("%s: Strategy=%d (\nrequester:\n"
3394 " group %d, volumeGroup=%d attributes=%s)\n"
3395 " higher priority source active:\n"
3396 " volumeGroup=%d attributes=%s) \n"
3397 " on output %zu, bailing out", __func__, productStrategy,
3398 group, group, toString(attributes).c_str(),
3399 client->volumeSource(), toString(client->attributes()).c_str(), i);
3400 applyVolume = false;
3401 isPreempted = true;
3402 break;
3403 }
3404 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003405 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003406 applyVolume = true;
3407 }
3408 }
3409 if (isPreempted || applyVolume) {
3410 break;
3411 }
3412 }
3413 if (!applyVolume) {
3414 continue; // next output
3415 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003416 }
François Gaffieed91f582020-01-31 10:35:37 +01003417 //FIXME: workaround for truncated touch sounds
3418 // delayed volume change for system stream to be removed when the problem is
3419 // handled by system UI
3420 status_t volStatus = checkAndSetVolume(
3421 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003422 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003423 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3424 if (volStatus != NO_ERROR) {
3425 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003426 }
3427 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003428
3429 // update voice volume if the an active call route exists
3430 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3431 && (curSrcDevices.find(
3432 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3433 != curSrcDevices.end())) {
3434 bool isVoiceVolSrc;
3435 bool isBtScoVolSrc;
3436 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3437 isVoiceVolSrc, isBtScoVolSrc, __func__)
3438 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003439 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3440 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3441 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003442 }
3443 }
3444
François Gaffiecfe17322018-11-07 13:41:29 +01003445 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3446 return status;
3447}
3448
François Gaffieaaac0fd2018-11-22 17:56:39 +01003449status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003450 audio_devices_t device,
3451 IVolumeCurves &volumeCurves)
3452{
3453 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3454 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003455 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3456 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003457 (index > volumeCurves.getVolumeIndexMax())) {
3458 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3459 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3460 return BAD_VALUE;
3461 }
3462 if (!audio_is_output_device(device)) {
3463 return BAD_VALUE;
3464 }
3465
3466 // Force max volume if stream cannot be muted
3467 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3468
François Gaffieaaac0fd2018-11-22 17:56:39 +01003469 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003470 volumeCurves.addCurrentVolumeIndex(device, index);
3471 return NO_ERROR;
3472}
3473
3474status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3475 int &index,
3476 audio_devices_t device)
3477{
3478 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3479 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003480 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003481 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003482 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003483 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003484 }
jiabin9a3361e2019-10-01 09:38:30 -07003485 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003486}
3487
3488status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3489 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003490 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003491{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003492 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003493 return BAD_VALUE;
3494 }
jiabin9a3361e2019-10-01 09:38:30 -07003495 index = curves.getVolumeIndex(deviceTypes);
3496 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003497 return NO_ERROR;
3498}
3499
3500status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3501 int &index)
3502{
3503 index = getVolumeCurves(attr).getVolumeIndexMin();
3504 return NO_ERROR;
3505}
3506
3507status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3508 int &index)
3509{
3510 index = getVolumeCurves(attr).getVolumeIndexMax();
3511 return NO_ERROR;
3512}
3513
Eric Laurent36829f92017-04-07 19:04:42 -07003514audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003515{
3516 // select one output among several suitable for global effects.
3517 // The priority is as follows:
3518 // 1: An offloaded output. If the effect ends up not being offloadable,
3519 // AudioFlinger will invalidate the track and the offloaded output
3520 // will be closed causing the effect to be moved to a PCM output.
3521 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003522 // 3: The primary output
3523 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003524
François Gaffiec005e562018-11-06 15:04:49 +01003525 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3526 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003527 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003528
Eric Laurent36829f92017-04-07 19:04:42 -07003529 if (outputs.size() == 0) {
3530 return AUDIO_IO_HANDLE_NONE;
3531 }
Eric Laurente552edb2014-03-10 17:42:56 -07003532
Eric Laurent36829f92017-04-07 19:04:42 -07003533 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3534 bool activeOnly = true;
3535
3536 while (output == AUDIO_IO_HANDLE_NONE) {
3537 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3538 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3539 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3540
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003541 for (audio_io_handle_t output : outputs) {
3542 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003543 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003544 continue;
3545 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003546 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3547 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003548 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003549 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003550 }
3551 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003552 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003553 }
3554 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003555 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003556 }
3557 }
3558 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3559 output = outputOffloaded;
3560 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3561 output = outputDeepBuffer;
3562 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3563 output = outputPrimary;
3564 } else {
3565 output = outputs[0];
3566 }
3567 activeOnly = false;
3568 }
3569
3570 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003571 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3572 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003573 mMusicEffectOutput = output;
3574 }
3575
3576 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003577 return output;
3578}
3579
Eric Laurent36829f92017-04-07 19:04:42 -07003580audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3581{
3582 return selectOutputForMusicEffects();
3583}
3584
Eric Laurente0720872014-03-11 09:30:41 -07003585status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003586 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003587 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003588 int session,
3589 int id)
3590{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003591 if (session != AUDIO_SESSION_DEVICE) {
3592 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003593 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003594 index = mInputs.indexOfKey(io);
3595 if (index < 0) {
3596 ALOGW("registerEffect() unknown io %d", io);
3597 return INVALID_OPERATION;
3598 }
Eric Laurente552edb2014-03-10 17:42:56 -07003599 }
3600 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003601 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3602 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3603 || strategy == PRODUCT_STRATEGY_NONE));
3604 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003605}
3606
Eric Laurentc241b0d2018-11-28 09:08:49 -08003607status_t AudioPolicyManager::unregisterEffect(int id)
3608{
3609 if (mEffects.getEffect(id) == nullptr) {
3610 return INVALID_OPERATION;
3611 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003612 if (mEffects.isEffectEnabled(id)) {
3613 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3614 setEffectEnabled(id, false);
3615 }
3616 return mEffects.unregisterEffect(id);
3617}
3618
3619status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3620{
3621 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3622 if (effect == nullptr) {
3623 return INVALID_OPERATION;
3624 }
3625
3626 status_t status = mEffects.setEffectEnabled(id, enabled);
3627 if (status == NO_ERROR) {
3628 mInputs.trackEffectEnabled(effect, enabled);
3629 }
3630 return status;
3631}
3632
Eric Laurent6c796322019-04-09 14:13:17 -07003633
3634status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3635{
3636 mEffects.moveEffects(ids, io);
3637 return NO_ERROR;
3638}
3639
Eric Laurentc75307b2015-03-17 15:29:32 -07003640bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3641{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003642 auto vs = toVolumeSource(stream, false);
3643 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003644}
3645
3646bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3647{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003648 auto vs = toVolumeSource(stream, false);
3649 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003650}
3651
Eric Laurente0720872014-03-11 09:30:41 -07003652bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003653{
3654 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003655 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003656 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003657 return true;
3658 }
3659 }
3660 return false;
3661}
3662
Eric Laurent275e8e92014-11-30 15:14:47 -08003663// Register a list of custom mixes with their attributes and format.
3664// When a mix is registered, corresponding input and output profiles are
3665// added to the remote submix hw module. The profile contains only the
3666// parameters (sampling rate, format...) specified by the mix.
3667// The corresponding input remote submix device is also connected.
3668//
3669// When a remote submix device is connected, the address is checked to select the
3670// appropriate profile and the corresponding input or output stream is opened.
3671//
3672// When capture starts, getInputForAttr() will:
3673// - 1 look for a mix matching the address passed in attribtutes tags if any
3674// - 2 if none found, getDeviceForInputSource() will:
3675// - 2.1 look for a mix matching the attributes source
3676// - 2.2 if none found, default to device selection by policy rules
3677// At this time, the corresponding output remote submix device is also connected
3678// and active playback use cases can be transferred to this mix if needed when reconnecting
3679// after AudioTracks are invalidated
3680//
3681// When playback starts, getOutputForAttr() will:
3682// - 1 look for a mix matching the address passed in attribtutes tags if any
3683// - 2 if none found, look for a mix matching the attributes usage
3684// - 3 if none found, default to device and output selection by policy rules.
3685
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003686status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003687{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3689 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003690 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003691 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003692 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003693 // examine each mix's route type
3694 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003695 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003696 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3697 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3698 ALOGE("Unsupported Policy Mix %zu of %zu: "
3699 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3700 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003702 break;
3703 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003704 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3705 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003706 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003707 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3708 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003709 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003710 rSubmixModule = mHwModules.getModuleFromName(
3711 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3712 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003713 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003714 i);
3715 res = INVALID_OPERATION;
3716 break;
3717 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003718 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003719
Eric Laurent97ac8712018-07-27 18:59:02 -07003720 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003721 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003722 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003723 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003724 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3725 } else {
3726 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3727 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003728 }
François Gaffie036e1e92015-03-19 10:16:24 +01003729
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003730 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003731 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732 res = INVALID_OPERATION;
3733 break;
3734 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003735 audio_config_t outputConfig = mix.mFormat;
3736 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003737 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3738 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3740 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003741 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003742 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3743 audio_is_linear_pcm(outputConfig.format)
3744 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003745 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003746 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3747 audio_is_linear_pcm(inputConfig.format)
3748 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003749
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003750 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003751 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003752 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003753 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003754 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003755 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003756 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003757 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3758 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003759 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003760 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003761 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003762
3763 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3764 mix.mDeviceType, mix.mDeviceAddress,
3765 String8(), AUDIO_FORMAT_DEFAULT);
3766 if (device == nullptr) {
3767 res = INVALID_OPERATION;
3768 break;
3769 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003770
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003771 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003772 // First try to find an already opened output supporting the device
3773 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003774 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003775
Eric Laurentc529cf62020-04-17 18:19:10 -07003776 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003777 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003778 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003779 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003780 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003781 } else {
3782 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003783 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003784 }
3785 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003786 // If no output found, try to find a direct output profile supporting the device
3787 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3788 sp<HwModule> module = mHwModules[i];
3789 for (size_t j = 0;
3790 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3791 j++) {
3792 sp<IOProfile> profile = module->getOutputProfiles()[j];
3793 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3794 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3795 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003796 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003797 res = INVALID_OPERATION;
3798 } else {
3799 foundOutput = true;
3800 }
3801 }
3802 }
3803 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003804 if (res != NO_ERROR) {
3805 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003806 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003807 res = INVALID_OPERATION;
3808 break;
3809 } else if (!foundOutput) {
3810 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003811 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003812 res = INVALID_OPERATION;
3813 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003814 } else {
3815 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003816 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003817 }
Eric Laurentc722f302014-12-10 11:21:49 -08003818 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003819 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003820 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003821 if (audio_flags::audio_mix_ownership()) {
3822 // Only unregister mixes that were actually registered to not accidentally unregister
3823 // mixes that already existed previously.
3824 unregisterPolicyMixes(registeredMixes);
3825 registeredMixes.clear();
3826 } else {
3827 unregisterPolicyMixes(mixes);
3828 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003829 } else if (checkOutputs) {
3830 checkForDeviceAndOutputChanges();
3831 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003832 }
3833 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003834}
3835
3836status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3837{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003838 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Marvin Raminabd9b892023-11-17 16:36:27 +01003839 status_t endResult = NO_ERROR;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003840 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003841 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003842 sp<HwModule> rSubmixModule;
3843 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003844 for (const auto& mix : mixes) {
3845 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003846
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003847 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003848 rSubmixModule = mHwModules.getModuleFromName(
3849 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3850 if (rSubmixModule == 0) {
3851 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003852 endResult = INVALID_OPERATION;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003853 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003854 }
3855 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003856
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003857 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003858
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003859 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003860 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003861 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 continue;
3863 }
3864
Kevin Rocard04ed0462019-05-02 17:53:24 -07003865 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003866 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003867 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3868 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003869 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003870 AUDIO_FORMAT_DEFAULT);
3871 if (res != OK) {
3872 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003873 "with type %d, address %s", device, address.c_str());
Marvin Raminabd9b892023-11-17 16:36:27 +01003874 endResult = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003875 }
3876 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 }
jiabin5740f082019-08-19 15:08:30 -07003878 rSubmixModule->removeOutputProfile(address.c_str());
3879 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003880
Kevin Rocard153f92d2018-12-18 18:33:28 -08003881 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003882 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003884 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003885 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003886 } else {
3887 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003888 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003889 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003890 }
Marvin Raminabd9b892023-11-17 16:36:27 +01003891 if (audio_flags::audio_mix_ownership()) {
3892 res = endResult;
3893 if (res == NO_ERROR && checkOutputs) {
3894 checkForDeviceAndOutputChanges();
3895 updateCallAndOutputRouting();
3896 }
3897 } else {
3898 if (res == NO_ERROR && checkOutputs) {
3899 checkForDeviceAndOutputChanges();
3900 updateCallAndOutputRouting();
3901 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003902 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003903 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003904}
3905
Marvin Raminbdefaf02023-11-01 09:10:32 +01003906status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3907 if (!audio_flags::audio_mix_test_api()) {
3908 return INVALID_OPERATION;
3909 }
3910
3911 _aidl_return.clear();
3912 _aidl_return.reserve(mPolicyMixes.size());
3913 for (const auto &policyMix: mPolicyMixes) {
3914 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3915 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3916 policyMix->mCbFlags);
3917 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003918 _aidl_return.back().mToken = policyMix->mToken;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003919 }
3920
3921 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3922 return OK;
3923}
3924
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003925status_t AudioPolicyManager::updatePolicyMix(
3926 const AudioMix& mix,
3927 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3928 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3929 if (res == NO_ERROR) {
3930 checkForDeviceAndOutputChanges();
3931 updateCallAndOutputRouting();
3932 }
3933 return res;
3934}
3935
Mikhail Naganov100f0122018-11-29 11:22:16 -08003936void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3937{
3938 size_t i = 0;
3939 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3940 for (const auto& fmt : mManualSurroundFormats) {
3941 if (i++ != 0) dst->append(", ");
3942 std::string sfmt;
3943 FormatConverter::toString(fmt, sfmt);
3944 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3945 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3946 }
3947}
3948
Eric Laurentc529cf62020-04-17 18:19:10 -07003949// Returns true if all devices types match the predicate and are supported by one HW module
3950bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003951 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003952 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003953 const char *context,
3954 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003955 for (size_t i = 0; i < devices.size(); i++) {
3956 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003957 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003958 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003959 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003960 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003961 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003962 return false;
3963 }
3964 }
3965 return true;
3966}
3967
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003968void AudioPolicyManager::changeOutputDevicesMuteState(
3969 const AudioDeviceTypeAddrVector& devices) {
3970 ALOGVV("%s() num devices %zu", __func__, devices.size());
3971
3972 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3973 getSoftwareOutputsForDevices(devices);
3974
3975 for (size_t i = 0; i < outputs.size(); i++) {
3976 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3977 DeviceVector prevDevices = outputDesc->devices();
3978 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3979 }
3980}
3981
3982std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3983 const AudioDeviceTypeAddrVector& devices) const
3984{
3985 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3986 DeviceVector deviceDescriptors;
3987 for (size_t j = 0; j < devices.size(); j++) {
3988 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3989 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3990 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3991 ALOGE("%s: device type %#x address %s not supported or not an output device",
3992 __func__, devices[j].mType, devices[j].getAddress());
3993 continue;
3994 }
3995 deviceDescriptors.add(desc);
3996 }
3997 for (size_t i = 0; i < mOutputs.size(); i++) {
3998 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3999 continue;
4000 }
4001 outputs.push_back(mOutputs.valueAt(i));
4002 }
4003 return outputs;
4004}
4005
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004006status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004007 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004008 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004009 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4010 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004011 }
4012 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004013 if (res != NO_ERROR) {
4014 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4015 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004016 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004017
4018 checkForDeviceAndOutputChanges();
4019 updateCallAndOutputRouting();
4020
4021 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004022}
4023
4024status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4025 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004026 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4027 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004028 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004029 __FUNCTION__, uid);
4030 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004031 }
4032
Eric Laurentc529cf62020-04-17 18:19:10 -07004033 checkForDeviceAndOutputChanges();
4034 updateCallAndOutputRouting();
4035
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004036 return res;
4037}
4038
Eric Laurent2517af32020-11-25 15:31:27 +01004039
jiabin0a488932020-08-07 17:32:40 -07004040status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4041 device_role_t role,
4042 const AudioDeviceTypeAddrVector &devices) {
4043 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4044 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004045
Eric Laurentc529cf62020-04-17 18:19:10 -07004046 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004047 return BAD_VALUE;
4048 }
jiabin0a488932020-08-07 17:32:40 -07004049 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004050 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004051 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4052 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004053 return status;
4054 }
4055
4056 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004057
4058 bool forceVolumeReeval = false;
4059 // FIXME: workaround for truncated touch sounds
4060 // to be removed when the problem is handled by system UI
4061 uint32_t delayMs = 0;
4062 if (strategy == mCommunnicationStrategy) {
4063 forceVolumeReeval = true;
4064 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4065 updateInputRouting();
4066 }
4067 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004068
4069 return NO_ERROR;
4070}
4071
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004072void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4073 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004074{
4075 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004076 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004077 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004078 // Only apply special touch sound delay once
4079 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004080 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004081 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004082 for (size_t i = 0; i < mOutputs.size(); i++) {
4083 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4084 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004085 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4086 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004087 // As done in setDeviceConnectionState, we could also fix default device issue by
4088 // preventing the force re-routing in case of default dev that distinguishes on address.
4089 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004090 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004091 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4092 // If the device is using preferred mixer attributes, the output need to reopen
4093 // with default configuration when the new selected devices are different from
4094 // current routing devices.
4095 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4096 continue;
4097 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304098
4099 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4100 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004101 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004102 // Only apply special touch sound delay once
4103 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004104 }
4105 if (forceVolumeReeval && !newDevices.isEmpty()) {
4106 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4107 }
4108 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004109 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004110 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004111}
4112
Eric Laurent2517af32020-11-25 15:31:27 +01004113void AudioPolicyManager::updateInputRouting() {
4114 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304115 // Skip for hotword recording as the input device switch
4116 // is handled within sound trigger HAL
4117 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4118 continue;
4119 }
Eric Laurent2517af32020-11-25 15:31:27 +01004120 auto newDevice = getNewInputDevice(activeDesc);
4121 // Force new input selection if the new device can not be reached via current input
4122 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4123 setInputDevice(activeDesc->mIoHandle, newDevice);
4124 } else {
4125 closeInput(activeDesc->mIoHandle);
4126 }
4127 }
4128}
4129
Paul Wang5d7cdb52022-11-22 09:45:06 +00004130status_t
4131AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4132 device_role_t role,
4133 const AudioDeviceTypeAddrVector &devices) {
4134 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4135 dumpAudioDeviceTypeAddrVector(devices).c_str());
4136
Eric Laurent78fedbf2023-03-09 14:40:44 +01004137 if (!areAllDevicesSupported(
4138 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004139 return BAD_VALUE;
4140 }
4141 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4142 if (status != NO_ERROR) {
4143 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4144 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4145 return status;
4146 }
4147
4148 checkForDeviceAndOutputChanges();
4149
4150 bool forceVolumeReeval = false;
4151 // TODO(b/263479999): workaround for truncated touch sounds
4152 // to be removed when the problem is handled by system UI
4153 uint32_t delayMs = 0;
4154 if (strategy == mCommunnicationStrategy) {
4155 forceVolumeReeval = true;
4156 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4157 updateInputRouting();
4158 }
4159 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4160
4161 return NO_ERROR;
4162}
4163
4164status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4165 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004166{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004167 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004168
Paul Wang5d7cdb52022-11-22 09:45:06 +00004169 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004170 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004171 ALOGW_IF(status != NAME_NOT_FOUND,
4172 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004173 strategy, status);
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
jiabin0a488932020-08-07 17:32:40 -07004193status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4194 device_role_t role,
4195 AudioDeviceTypeAddrVector &devices) {
4196 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004197}
4198
Jiabin Huang3b98d322020-09-03 17:54:16 +00004199status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4200 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4201 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4202 dumpAudioDeviceTypeAddrVector(devices).c_str());
4203
Mikhail Naganov55773032020-10-01 15:08:13 -07004204 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004205 return BAD_VALUE;
4206 }
4207 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4208 ALOGW_IF(status != NO_ERROR,
4209 "Engine could not set preferred devices %s for audio source %d role %d",
4210 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4211
4212 return status;
4213}
4214
4215status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4216 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4217 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4218 dumpAudioDeviceTypeAddrVector(devices).c_str());
4219
Mikhail Naganov55773032020-10-01 15:08:13 -07004220 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004221 return BAD_VALUE;
4222 }
4223 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4224 ALOGW_IF(status != NO_ERROR,
4225 "Engine could not add preferred devices %s for audio source %d role %d",
4226 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4227
Eric Laurent2517af32020-11-25 15:31:27 +01004228 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004229 return status;
4230}
4231
4232status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4233 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4234{
4235 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4236 dumpAudioDeviceTypeAddrVector(devices).c_str());
4237
Eric Laurent78fedbf2023-03-09 14:40:44 +01004238 if (!areAllDevicesSupported(
4239 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004240 return BAD_VALUE;
4241 }
4242
4243 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4244 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004245 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004246 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004247 if (status == NO_ERROR) {
4248 updateInputRouting();
4249 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004250 return status;
4251}
4252
4253status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4254 device_role_t role) {
4255 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4256
4257 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004258 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004259 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004260 if (status == NO_ERROR) {
4261 updateInputRouting();
4262 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004263 return status;
4264}
4265
4266status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4267 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4268 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4269}
4270
Oscar Azucena90e77632019-11-27 17:12:28 -08004271status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004272 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004273 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004274 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4275 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004276 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004277 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4278 if (status != NO_ERROR) {
4279 ALOGE("%s() could not set device affinity for userId %d",
4280 __FUNCTION__, userId);
4281 return status;
4282 }
4283
4284 // reevaluate outputs for all devices
4285 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004286 changeOutputDevicesMuteState(devices);
4287 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4288 true /* skipDelays */);
4289 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004290
4291 return NO_ERROR;
4292}
4293
4294status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004295 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004296 AudioDeviceTypeAddrVector devices;
4297 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004298 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4299 if (status != NO_ERROR) {
4300 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4301 __FUNCTION__, userId);
4302 return status;
4303 }
4304
4305 // reevaluate outputs for all devices
4306 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004307 changeOutputDevicesMuteState(devices);
4308 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4309 true /* skipDelays */);
4310 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004311
4312 return NO_ERROR;
4313}
4314
Andy Hungc29d82b2018-10-05 12:23:17 -07004315void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004316{
Andy Hungc29d82b2018-10-05 12:23:17 -07004317 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004318 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004319 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004320 std::string stateLiteral;
4321 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004322 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004323 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4324 "communications", "media", "record", "dock", "system",
4325 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4326 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4327 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004328 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4329 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4330 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4331 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4332 dst->append(" (MANUAL: ");
4333 dumpManualSurroundFormats(dst);
4334 dst->append(")");
4335 }
4336 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004337 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004338 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4339 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004340 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004341 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004342
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004343 dst->append("\n");
4344 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4345 dst->append("\n");
4346 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004347 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004348 mOutputs.dump(dst);
4349 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004350 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004351 mAudioPatches.dump(dst);
4352 mPolicyMixes.dump(dst);
4353 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004354
Kevin Rocardb99cc752019-03-21 20:52:24 -07004355 dst->appendFormat(" AllowedCapturePolicies:\n");
4356 for (auto& policy : mAllowedCapturePolicies) {
4357 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4358 }
4359
jiabina84c3d32022-12-02 18:59:55 +00004360 dst->appendFormat(" Preferred mixer audio configuration:\n");
4361 for (const auto it : mPreferredMixerAttrInfos) {
4362 dst->appendFormat(" - device port id: %d\n", it.first);
4363 for (const auto preferredMixerInfoIt : it.second) {
4364 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4365 preferredMixerInfoIt.second->dump(dst);
4366 }
4367 }
4368
François Gaffiec005e562018-11-06 15:04:49 +01004369 dst->appendFormat("\nPolicy Engine dump:\n");
4370 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004371}
4372
4373status_t AudioPolicyManager::dump(int fd)
4374{
4375 String8 result;
4376 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004377 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004378 return NO_ERROR;
4379}
4380
Kevin Rocardb99cc752019-03-21 20:52:24 -07004381status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4382{
4383 mAllowedCapturePolicies[uid] = capturePolicy;
4384 return NO_ERROR;
4385}
4386
Eric Laurente552edb2014-03-10 17:42:56 -07004387// This function checks for the parameters which can be offloaded.
4388// This can be enhanced depending on the capability of the DSP and policy
4389// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004390audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004391{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004392 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004393 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004394 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004395 offloadInfo.format,
4396 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4397 offloadInfo.has_video);
4398
jiabin2b9d5a12021-12-10 01:06:29 +00004399 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004400 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004401 }
4402
4403 // See if there is a profile to support this.
4404 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004405 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004406 offloadInfo.sample_rate,
4407 offloadInfo.format,
4408 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004409 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4410 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004411 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4412 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4413 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004414 if (profile == nullptr) {
4415 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4416 }
4417 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4418 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4419 }
4420 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004421}
4422
Michael Chana94fbb22018-04-24 14:31:19 +10004423bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4424 const audio_attributes_t& attributes) {
4425 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004426 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004427 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4428 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004429 config.sample_rate,
4430 config.format,
4431 config.channel_mask,
4432 output_flags,
4433 true /* directOnly */);
4434 ALOGV("%s() profile %sfound with name: %s, "
4435 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4436 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004437 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004438 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004439
4440 // also try the MSD module if compatible profile not found
4441 if (profile == nullptr) {
4442 profile = getMsdProfileForOutput(outputDevices,
4443 config.sample_rate,
4444 config.format,
4445 config.channel_mask,
4446 output_flags,
4447 true /* directOnly */);
4448 ALOGV("%s() MSD profile %sfound with name: %s, "
4449 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4450 __FUNCTION__, profile != 0 ? "" : "NOT ",
4451 (profile != 0 ? profile->getTagName().c_str() : "null"),
4452 config.sample_rate, config.format, config.channel_mask, output_flags);
4453 }
4454 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004455}
4456
jiabin2b9d5a12021-12-10 01:06:29 +00004457bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4458 bool durationIgnored) {
4459 if (mMasterMono) {
4460 return false; // no offloading if mono is set.
4461 }
4462
4463 // Check if offload has been disabled
4464 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4465 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4466 return false;
4467 }
4468
4469 // Check if stream type is music, then only allow offload as of now.
4470 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4471 {
4472 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4473 return false;
4474 }
4475
4476 //TODO: enable audio offloading with video when ready
4477 const bool allowOffloadWithVideo =
4478 property_get_bool("audio.offload.video", false /* default_value */);
4479 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4480 ALOGV("%s: has_video == true, returning false", __func__);
4481 return false;
4482 }
4483
4484 //If duration is less than minimum value defined in property, return false
4485 const int min_duration_secs = property_get_int32(
4486 "audio.offload.min.duration.secs", -1 /* default_value */);
4487 if (!durationIgnored) {
4488 if (min_duration_secs >= 0) {
4489 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4490 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4491 __func__, min_duration_secs);
4492 return false;
4493 }
4494 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4495 ALOGV("%s: Offload denied by duration < default min(=%u)",
4496 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4497 return false;
4498 }
4499 }
4500
4501 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4502 // creating an offloaded track and tearing it down immediately after start when audioflinger
4503 // detects there is an active non offloadable effect.
4504 // FIXME: We should check the audio session here but we do not have it in this context.
4505 // This may prevent offloading in rare situations where effects are left active by apps
4506 // in the background.
4507 if (mEffects.isNonOffloadableEffectEnabled()) {
4508 return false;
4509 }
4510
4511 return true;
4512}
4513
4514audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4515 const audio_config_t *config) {
4516 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4517 offloadInfo.format = config->format;
4518 offloadInfo.sample_rate = config->sample_rate;
4519 offloadInfo.channel_mask = config->channel_mask;
4520 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4521 offloadInfo.has_video = false;
4522 offloadInfo.is_streaming = false;
4523 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4524
4525 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4526 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4527 audio_flags_to_audio_output_flags(attr->flags, &flags);
4528 // only retain flags that will drive compressed offload or passthrough
4529 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4530 if (offloadPossible) {
4531 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4532 }
4533 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4534
Dorin Drimusfae3c642022-03-17 18:36:30 +01004535 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004536 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004537 DeviceVector outputDevices = engineOutputDevices;
4538 // the MSD module checks for different conditions and output devices
4539 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4540 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4541 continue;
4542 }
4543 outputDevices = getMsdAudioOutDevices();
4544 }
jiabin2b9d5a12021-12-10 01:06:29 +00004545 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004546 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004547 config->sample_rate, nullptr /*updatedSamplingRate*/,
4548 config->format, nullptr /*updatedFormat*/,
4549 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004550 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004551 continue;
4552 }
4553 // reject profiles not corresponding to a device currently available
4554 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4555 continue;
4556 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004557 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4558 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004559 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004560 != AUDIO_DIRECT_NOT_SUPPORTED) {
4561 // Already reports offload gapless supported. No need to report offload support.
4562 continue;
4563 }
4564 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4565 != AUDIO_OUTPUT_FLAG_NONE) {
4566 // If offload gapless is reported, no need to report offload support.
4567 directMode = (audio_direct_mode_t) ((directMode &
4568 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4569 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4570 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004571 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004572 }
4573 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004574 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004575 }
4576 }
4577 }
4578 return directMode;
4579}
4580
Dorin Drimusf2196d82022-01-03 12:11:18 +01004581status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4582 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004583 if (mEffects.isNonOffloadableEffectEnabled()) {
4584 return OK;
4585 }
jiabinf1c73972022-04-14 16:28:52 -07004586 DeviceVector devices;
4587 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004588 if (status != OK) {
4589 return status;
4590 }
4591 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4592 if (devices.empty()) {
4593 return OK; // no output devices for the attributes
4594 }
jiabinf1c73972022-04-14 16:28:52 -07004595 return getProfilesForDevices(devices, audioProfilesVector,
4596 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004597}
4598
jiabina84c3d32022-12-02 18:59:55 +00004599status_t AudioPolicyManager::getSupportedMixerAttributes(
4600 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4601 ALOGV("%s, portId=%d", __func__, portId);
4602 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4603 if (deviceDescriptor == nullptr) {
4604 ALOGE("%s the requested device is currently unavailable", __func__);
4605 return BAD_VALUE;
4606 }
jiabin96daffc2023-05-11 17:51:55 +00004607 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4608 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4609 deviceDescriptor->type());
4610 return BAD_VALUE;
4611 }
jiabina84c3d32022-12-02 18:59:55 +00004612 for (const auto& hwModule : mHwModules) {
4613 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4614 if (curProfile->supportsDevice(deviceDescriptor)) {
4615 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4616 }
4617 }
4618 }
4619 return NO_ERROR;
4620}
4621
4622status_t AudioPolicyManager::setPreferredMixerAttributes(
4623 const audio_attributes_t *attr,
4624 audio_port_handle_t portId,
4625 uid_t uid,
4626 const audio_mixer_attributes_t *mixerAttributes) {
4627 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4628 "mixerBehavior=%d}, uid=%d, portId=%u",
4629 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4630 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4631 mixerAttributes->mixer_behavior, uid, portId);
4632 if (attr->usage != AUDIO_USAGE_MEDIA) {
4633 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4634 return BAD_VALUE;
4635 }
4636 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4637 if (deviceDescriptor == nullptr) {
4638 ALOGE("%s the requested device is currently unavailable", __func__);
4639 return BAD_VALUE;
4640 }
4641 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4642 ALOGE("%s(%d), type=%d, is not a usb output device",
4643 __func__, portId, deviceDescriptor->type());
4644 return BAD_VALUE;
4645 }
4646
4647 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4648 audio_flags_to_audio_output_flags(attr->flags, &flags);
4649 flags = (audio_output_flags_t) (flags |
4650 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4651 sp<IOProfile> profile = nullptr;
4652 DeviceVector devices(deviceDescriptor);
4653 for (const auto& hwModule : mHwModules) {
4654 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4655 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004656 && curProfile->getCompatibilityScore(
4657 devices,
4658 mixerAttributes->config.sample_rate,
4659 nullptr /*updatedSamplingRate*/,
4660 mixerAttributes->config.format,
4661 nullptr /*updatedFormat*/,
4662 mixerAttributes->config.channel_mask,
4663 nullptr /*updatedChannelMask*/,
4664 flags,
4665 false /*exactMatchRequiredForInputFlags*/)
4666 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004667 profile = curProfile;
4668 break;
4669 }
4670 }
4671 }
4672 if (profile == nullptr) {
4673 ALOGE("%s, there is no compatible profile found", __func__);
4674 return BAD_VALUE;
4675 }
4676
4677 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4678 sp<PreferredMixerAttributesInfo>::make(
4679 uid, portId, profile, flags, *mixerAttributes);
4680 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4681 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4682
4683 // If 1) there is any client from the preferred mixer configuration owner that is currently
4684 // active and matches the strategy and 2) current output is on the preferred device and the
4685 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4686 // configuration.
4687 std::vector<audio_io_handle_t> outputsToReopen;
4688 for (size_t i = 0; i < mOutputs.size(); i++) {
4689 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004690 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4691 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4692 output->mUsePreferredMixerAttributes = true;
4693 } else {
4694 for (const auto &client: output->getActiveClients()) {
4695 if (client->uid() == uid && client->strategy() == strategy) {
4696 client->setIsInvalid();
4697 outputsToReopen.push_back(output->mIoHandle);
4698 }
jiabina84c3d32022-12-02 18:59:55 +00004699 }
4700 }
4701 }
4702 }
4703 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4704 config.sample_rate = mixerAttributes->config.sample_rate;
4705 config.channel_mask = mixerAttributes->config.channel_mask;
4706 config.format = mixerAttributes->config.format;
4707 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004708 sp<SwAudioOutputDescriptor> desc =
4709 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4710 if (desc == nullptr) {
4711 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4712 continue;
4713 }
4714 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004715 }
4716
4717 return NO_ERROR;
4718}
4719
4720sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004721 audio_port_handle_t devicePortId,
4722 product_strategy_t strategy,
4723 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004724 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4725 if (it == mPreferredMixerAttrInfos.end()) {
4726 return nullptr;
4727 }
jiabind9a58d32023-06-01 17:57:30 +00004728 if (activeBitPerfectPreferred) {
4729 for (auto [strategy, info] : it->second) {
4730 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4731 && info->getActiveClientCount() != 0) {
4732 return info;
4733 }
4734 }
jiabina84c3d32022-12-02 18:59:55 +00004735 }
jiabind9a58d32023-06-01 17:57:30 +00004736 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4737 return strategyMatchedMixerAttrInfoIt == it->second.end()
4738 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004739}
4740
4741status_t AudioPolicyManager::getPreferredMixerAttributes(
4742 const audio_attributes_t *attr,
4743 audio_port_handle_t portId,
4744 audio_mixer_attributes_t* mixerAttributes) {
4745 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4746 portId, mEngine->getProductStrategyForAttributes(*attr));
4747 if (info == nullptr) {
4748 return NAME_NOT_FOUND;
4749 }
4750 *mixerAttributes = info->getMixerAttributes();
4751 return NO_ERROR;
4752}
4753
4754status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4755 audio_port_handle_t portId,
4756 uid_t uid) {
4757 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4758 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4759 if (preferredMixerAttrInfo == nullptr) {
4760 return NAME_NOT_FOUND;
4761 }
4762 if (preferredMixerAttrInfo->getUid() != uid) {
4763 ALOGE("%s, requested uid=%d, owned uid=%d",
4764 __func__, uid, preferredMixerAttrInfo->getUid());
4765 return PERMISSION_DENIED;
4766 }
4767 mPreferredMixerAttrInfos[portId].erase(strategy);
4768 if (mPreferredMixerAttrInfos[portId].empty()) {
4769 mPreferredMixerAttrInfos.erase(portId);
4770 }
4771
4772 // Reconfig existing output
4773 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4774 for (size_t i = 0; i < mOutputs.size(); i++) {
4775 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4776 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4777 }
4778 }
4779 for (const auto output : potentialOutputsToReopen) {
4780 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4781 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4782 preferredMixerAttrInfo->getFlags())) {
4783 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4784 }
4785 }
4786 return NO_ERROR;
4787}
4788
Eric Laurent6a94d692014-05-20 11:18:06 -07004789status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4790 audio_port_type_t type,
4791 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004792 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 unsigned int *generation)
4794{
jiabin19cdba52020-11-24 11:28:58 -08004795 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4796 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 return BAD_VALUE;
4798 }
4799 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004800 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004801 *num_ports = 0;
4802 }
4803
4804 size_t portsWritten = 0;
4805 size_t portsMax = *num_ports;
4806 *num_ports = 0;
4807 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004808 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4809 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004810 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004811 for (const auto& dev : mAvailableOutputDevices) {
4812 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004813 continue;
4814 }
4815 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004816 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004817 }
4818 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 }
4821 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004822 for (const auto& dev : mAvailableInputDevices) {
4823 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004824 continue;
4825 }
4826 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004827 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004828 }
4829 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004830 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 }
4832 }
4833 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4834 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4835 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4836 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4837 }
4838 *num_ports += mInputs.size();
4839 }
4840 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004841 size_t numOutputs = 0;
4842 for (size_t i = 0; i < mOutputs.size(); i++) {
4843 if (!mOutputs[i]->isDuplicated()) {
4844 numOutputs++;
4845 if (portsWritten < portsMax) {
4846 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4847 }
4848 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004849 }
Eric Laurent84c70242014-06-23 08:46:27 -07004850 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 }
4852 }
jiabina84c3d32022-12-02 18:59:55 +00004853
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004855 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 return NO_ERROR;
4857}
4858
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004859status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4860 std::vector<media::AudioPortFw>* _aidl_return) {
4861 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4862 audio_port_v7 port;
4863 dev->toAudioPort(&port);
4864 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4865 _aidl_return->push_back(std::move(aidlPort));
4866 return OK;
4867 };
4868
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004869 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004870 for (const auto& dev : module->getDeclaredDevices()) {
4871 if (role == media::AudioPortRole::NONE ||
4872 ((role == media::AudioPortRole::SOURCE)
4873 == audio_is_input_device(dev->type()))) {
4874 RETURN_STATUS_IF_ERROR(pushPort(dev));
4875 }
4876 }
4877 }
4878 return OK;
4879}
4880
jiabin19cdba52020-11-24 11:28:58 -08004881status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004882{
Eric Laurent99fcae42018-05-17 16:59:18 -07004883 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4884 return BAD_VALUE;
4885 }
4886 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4887 if (dev != 0) {
4888 dev->toAudioPort(port);
4889 return NO_ERROR;
4890 }
4891 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4892 if (dev != 0) {
4893 dev->toAudioPort(port);
4894 return NO_ERROR;
4895 }
4896 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4897 if (out != 0) {
4898 out->toAudioPort(port);
4899 return NO_ERROR;
4900 }
4901 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4902 if (in != 0) {
4903 in->toAudioPort(port);
4904 return NO_ERROR;
4905 }
4906 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004907}
4908
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004909status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4910 audio_patch_handle_t *handle,
4911 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004912{
François Gaffieafd4cea2019-11-18 15:50:22 +01004913 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 if (handle == NULL || patch == NULL) {
4915 return BAD_VALUE;
4916 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004917 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004918 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004919 return BAD_VALUE;
4920 }
4921 // only one source per audio patch supported for now
4922 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 return INVALID_OPERATION;
4924 }
Eric Laurent874c42872014-08-08 15:13:39 -07004925 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 return INVALID_OPERATION;
4927 }
Eric Laurent874c42872014-08-08 15:13:39 -07004928 for (size_t i = 0; i < patch->num_sinks; i++) {
4929 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4930 return INVALID_OPERATION;
4931 }
4932 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004933
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004934 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4935 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4936 if (srcDevice == nullptr || sinkDevice == nullptr) {
4937 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4938 return BAD_VALUE;
4939 }
4940 ALOGV("%s between source %s and sink %s", __func__,
4941 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4942 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4943 // Default attributes, default volume priority, not to infer with non raw audio patches.
4944 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4945 const struct audio_port_config *source = &patch->sources[0];
4946 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004947 new SourceClientDescriptor(
4948 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4949 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4950 true);
4951 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004952
4953 status_t status =
4954 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4955
4956 if (status != NO_ERROR) {
4957 return INVALID_OPERATION;
4958 }
4959 mAudioSources.add(portId, sourceDesc);
4960 return NO_ERROR;
4961}
4962
4963status_t AudioPolicyManager::connectAudioSourceToSink(
4964 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4965 const struct audio_patch *patch,
4966 audio_patch_handle_t &handle,
4967 uid_t uid, uint32_t delayMs)
4968{
4969 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4970 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4971 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4972 return INVALID_OPERATION;
4973 }
4974 sourceDesc->connect(handle, sinkDevice);
4975 if (isMsdPatch(handle)) {
4976 return NO_ERROR;
4977 }
4978 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4979 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4980 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4981 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4982 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4983 goto FailurePatchAdded;
4984 }
4985 status = swOutput->start();
4986 if (status != NO_ERROR) {
4987 goto FailureSourceAdded;
4988 }
4989 swOutput->addClient(sourceDesc);
4990 status = startSource(swOutput, sourceDesc, &delayMs);
4991 if (status != NO_ERROR) {
4992 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4993 goto FailureSourceActive;
4994 }
4995 if (delayMs != 0) {
4996 usleep(delayMs * 1000);
4997 }
4998 return NO_ERROR;
4999
5000FailureSourceActive:
5001 swOutput->stop();
5002 releaseOutput(sourceDesc->portId());
5003FailureSourceAdded:
5004 sourceDesc->setSwOutput(nullptr);
5005FailurePatchAdded:
5006 releaseAudioPatchInternal(handle);
5007 return INVALID_OPERATION;
5008}
5009
5010status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5011 audio_patch_handle_t *handle,
5012 uid_t uid, uint32_t delayMs,
5013 const sp<SourceClientDescriptor>& sourceDesc)
5014{
5015 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 sp<AudioPatch> patchDesc;
5017 ssize_t index = mAudioPatches.indexOfKey(*handle);
5018
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5020 patch->sources[0].role,
5021 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005022#if LOG_NDEBUG == 0
5023 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005024 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5025 patch->sinks[i].role,
5026 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005027 }
5028#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005029
5030 if (index >= 0) {
5031 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005032 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5033 __func__, mUidCached, patchDesc->getUid(), uid);
5034 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 return INVALID_OPERATION;
5036 }
5037 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005038 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 }
5040
5041 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005044 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 return BAD_VALUE;
5046 }
Eric Laurent84c70242014-06-23 08:46:27 -07005047 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5048 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005049 if (patchDesc != 0) {
5050 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005051 ALOGV("%s source id differs for patch current id %d new id %d",
5052 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 return BAD_VALUE;
5054 }
5055 }
Eric Laurent874c42872014-08-08 15:13:39 -07005056 DeviceVector devices;
5057 for (size_t i = 0; i < patch->num_sinks; i++) {
5058 // Only support mix to devices connection
5059 // TODO add support for mix to mix connection
5060 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005061 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005062 return INVALID_OPERATION;
5063 }
5064 sp<DeviceDescriptor> devDesc =
5065 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5066 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005068 return BAD_VALUE;
5069 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005070
jiabin66acc432024-02-06 00:57:36 +00005071 if (outputDesc->mProfile->getCompatibilityScore(
5072 DeviceVector(devDesc),
5073 patch->sources[0].sample_rate,
5074 nullptr, // updatedSamplingRate
5075 patch->sources[0].format,
5076 nullptr, // updatedFormat
5077 patch->sources[0].channel_mask,
5078 nullptr, // updatedChannelMask
5079 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005080 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005081 return INVALID_OPERATION;
5082 }
5083 devices.add(devDesc);
5084 }
5085 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 return INVALID_OPERATION;
5087 }
Eric Laurent874c42872014-08-08 15:13:39 -07005088
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005090 ALOGV("%s setting device %s on output %d",
5091 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305092 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005093 index = mAudioPatches.indexOfKey(*handle);
5094 if (index >= 0) {
5095 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005096 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005097 }
5098 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005099 patchDesc->setUid(uid);
5100 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005101 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005102 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005103 return INVALID_OPERATION;
5104 }
5105 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5106 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5107 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005108 // only one sink supported when connecting an input device to a mix
5109 if (patch->num_sinks > 1) {
5110 return INVALID_OPERATION;
5111 }
François Gaffie53615e22015-03-19 09:24:12 +01005112 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005113 if (inputDesc == NULL) {
5114 return BAD_VALUE;
5115 }
5116 if (patchDesc != 0) {
5117 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5118 return BAD_VALUE;
5119 }
5120 }
François Gaffie11d30102018-11-02 16:09:09 +01005121 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005122 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005123 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 return BAD_VALUE;
5125 }
5126
jiabin66acc432024-02-06 00:57:36 +00005127 if (inputDesc->mProfile->getCompatibilityScore(
5128 DeviceVector(device),
5129 patch->sinks[0].sample_rate,
5130 nullptr, /*updatedSampleRate*/
5131 patch->sinks[0].format,
5132 nullptr, /*updatedFormat*/
5133 patch->sinks[0].channel_mask,
5134 nullptr, /*updatedChannelMask*/
5135 // FIXME for the parameter type,
5136 // and the NONE
5137 (audio_output_flags_t)
5138 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005139 return INVALID_OPERATION;
5140 }
5141 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005142 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005143 device->toString().c_str(), inputDesc->mIoHandle);
5144 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 index = mAudioPatches.indexOfKey(*handle);
5146 if (index >= 0) {
5147 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005148 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005149 }
5150 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005151 patchDesc->setUid(uid);
5152 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005153 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005154 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005155 return INVALID_OPERATION;
5156 }
5157 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5158 // device to device connection
5159 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005160 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005161 return BAD_VALUE;
5162 }
5163 }
François Gaffie11d30102018-11-02 16:09:09 +01005164 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005165 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005166 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005167 return BAD_VALUE;
5168 }
Eric Laurent874c42872014-08-08 15:13:39 -07005169
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 //update source and sink with our own data as the data passed in the patch may
5171 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005172 PatchBuilder patchBuilder;
5173 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005174
5175 // if first sink is to MSD, establish single MSD patch
5176 if (getMsdAudioOutDevices().contains(
5177 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5178 ALOGV("%s patching to MSD", __FUNCTION__);
5179 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5180 goto installPatch;
5181 }
5182
François Gaffieafd4cea2019-11-18 15:50:22 +01005183 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5184 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005185
Eric Laurent874c42872014-08-08 15:13:39 -07005186 for (size_t i = 0; i < patch->num_sinks; i++) {
5187 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005188 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005189 return INVALID_OPERATION;
5190 }
François Gaffie11d30102018-11-02 16:09:09 +01005191 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005192 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005193 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005194 return BAD_VALUE;
5195 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005196 audio_port_config sinkPortConfig = {};
5197 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5198 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005199
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005200 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5201 // volume management purpose (tracking activity)
5202 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5203 // in config XML to reach the sink so that is can be declared as available.
5204 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005205 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005206 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005207 // take care of dynamic routing for SwOutput selection,
5208 audio_attributes_t attributes = sourceDesc->attributes();
5209 audio_stream_type_t stream = sourceDesc->stream();
5210 audio_attributes_t resultAttr;
5211 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5212 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005213 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5214 config.channel_mask =
5215 (audio_channel_mask_get_representation(sourceMask)
5216 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5217 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005218 config.format = sourceDesc->config().format;
5219 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5220 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5221 bool isRequestedDeviceForExclusiveUse = false;
5222 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005223 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005224 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005225 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5226 &stream, sourceDesc->uid(), &config, &flags,
5227 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005228 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005229 if (output == AUDIO_IO_HANDLE_NONE) {
5230 ALOGV("%s no output for device %s",
5231 __FUNCTION__, sinkDevice->toString().c_str());
5232 return INVALID_OPERATION;
5233 }
5234 outputDesc = mOutputs.valueFor(output);
5235 if (outputDesc->isDuplicated()) {
5236 ALOGE("%s output is duplicated", __func__);
5237 return INVALID_OPERATION;
5238 }
François Gaffie7e39df22022-04-26 12:48:49 +02005239 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5240 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005241 } else {
5242 // Same for "raw patches" aka created from createAudioPatch API
5243 SortedVector<audio_io_handle_t> outputs =
5244 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5245 // if the sink device is reachable via an opened output stream, request to
5246 // go via this output stream by adding a second source to the patch
5247 // description
5248 output = selectOutput(outputs);
5249 if (output == AUDIO_IO_HANDLE_NONE) {
5250 ALOGE("%s no output available for internal patch sink", __func__);
5251 return INVALID_OPERATION;
5252 }
5253 outputDesc = mOutputs.valueFor(output);
5254 if (outputDesc->isDuplicated()) {
5255 ALOGV("%s output for device %s is duplicated",
5256 __func__, sinkDevice->toString().c_str());
5257 return INVALID_OPERATION;
5258 }
François Gaffie7e39df22022-04-26 12:48:49 +02005259 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005260 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005261 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005262 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005263 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005264 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005265 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5266 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005267 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5268 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005269 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005270 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005271 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005272 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005273 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005274 return INVALID_OPERATION;
5275 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005276 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005277 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005278 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005279 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005280 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005281 srcMixPortConfig.ext.mix.usecase.stream =
5282 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005283 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5284 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005285 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005286 }
Eric Laurent83b88082014-06-20 18:31:16 -07005287 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 }
5289 // TODO: check from routing capabilities in config file and other conflicting patches
5290
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005291installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 status_t status = installPatch(
5293 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005294 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 return INVALID_OPERATION;
5297 }
5298 } else {
5299 return BAD_VALUE;
5300 }
5301 } else {
5302 return BAD_VALUE;
5303 }
5304 return NO_ERROR;
5305}
5306
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005307status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005308{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005309 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 ssize_t index = mAudioPatches.indexOfKey(handle);
5311
5312 if (index < 0) {
5313 return BAD_VALUE;
5314 }
5315 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5317 __func__, mUidCached, patchDesc->getUid(), uid);
5318 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005319 return INVALID_OPERATION;
5320 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005321 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5322 for (size_t i = 0; i < mAudioSources.size(); i++) {
5323 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5324 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5325 portId = sourceDesc->portId();
5326 break;
5327 }
5328 }
5329 return portId != AUDIO_PORT_HANDLE_NONE ?
5330 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005331}
Eric Laurent6a94d692014-05-20 11:18:06 -07005332
François Gaffieafd4cea2019-11-18 15:50:22 +01005333status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005334 uint32_t delayMs,
5335 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005336{
5337 ALOGV("%s patch %d", __func__, handle);
5338 if (mAudioPatches.indexOfKey(handle) < 0) {
5339 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5340 return BAD_VALUE;
5341 }
5342 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005346 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005348 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005349 return BAD_VALUE;
5350 }
5351
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305352 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005353 getNewOutputDevices(outputDesc, true /*fromCache*/),
5354 true,
5355 0,
5356 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005357 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5358 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005359 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005360 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005361 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 return BAD_VALUE;
5363 }
5364 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005365 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 true,
5367 NULL);
5368 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005369 status_t status =
5370 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5371 ALOGV("%s patch panel returned %d patchHandle %d",
5372 __func__, status, patchDesc->getAfHandle());
5373 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005375 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005376 // SW or HW Bridge
5377 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5378 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005379 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005380 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5381 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5382 outputDesc = sourceDesc->swOutput().promote();
5383 }
5384 if (outputDesc == nullptr) {
5385 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5386 // releaseOutput has already called closeOutput in case of direct output
5387 return NO_ERROR;
5388 }
François Gaffie7e39df22022-04-26 12:48:49 +02005389 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005390 // While using a HwBridge, force reconsidering device only if not reusing an existing
5391 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005392 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005393 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5394 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5395 // Reconsider device only for cases:
5396 // 1 / Active Output
5397 // 2 / Inactive Output previously hosting HwBridge
5398 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5399 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5400 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305401 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005402 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5403 outputDesc->devices(),
5404 force,
5405 0,
5406 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005407 } else {
5408 return BAD_VALUE;
5409 }
5410 } else {
5411 return BAD_VALUE;
5412 }
5413 return NO_ERROR;
5414}
5415
5416status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5417 struct audio_patch *patches,
5418 unsigned int *generation)
5419{
François Gaffie53615e22015-03-19 09:24:12 +01005420 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 return BAD_VALUE;
5422 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005423 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005424 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005425}
5426
Eric Laurente1715a42014-05-20 11:30:42 -07005427status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005428{
Eric Laurente1715a42014-05-20 11:30:42 -07005429 ALOGV("setAudioPortConfig()");
5430
5431 if (config == NULL) {
5432 return BAD_VALUE;
5433 }
5434 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5435 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005436 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5437 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005438 }
5439
Eric Laurenta121f902014-06-03 13:32:54 -07005440 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005441 if (config->type == AUDIO_PORT_TYPE_MIX) {
5442 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005443 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005444 if (outputDesc == NULL) {
5445 return BAD_VALUE;
5446 }
Eric Laurent84c70242014-06-23 08:46:27 -07005447 ALOG_ASSERT(!outputDesc->isDuplicated(),
5448 "setAudioPortConfig() called on duplicated output %d",
5449 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005450 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005451 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005452 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005453 if (inputDesc == NULL) {
5454 return BAD_VALUE;
5455 }
Eric Laurenta121f902014-06-03 13:32:54 -07005456 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005457 } else {
5458 return BAD_VALUE;
5459 }
5460 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5461 sp<DeviceDescriptor> deviceDesc;
5462 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5463 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5464 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5465 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5466 } else {
5467 return BAD_VALUE;
5468 }
5469 if (deviceDesc == NULL) {
5470 return BAD_VALUE;
5471 }
Eric Laurenta121f902014-06-03 13:32:54 -07005472 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005473 } else {
5474 return BAD_VALUE;
5475 }
5476
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005477 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005478 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5479 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005480 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005481 audioPortConfig->toAudioPortConfig(&newConfig, config);
5482 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005483 }
Eric Laurenta121f902014-06-03 13:32:54 -07005484 if (status != NO_ERROR) {
5485 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005486 }
Eric Laurente1715a42014-05-20 11:30:42 -07005487
5488 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005489}
5490
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005491void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5492{
Eric Laurentd60560a2015-04-10 11:31:20 -07005493 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005494 clearAudioPatches(uid);
5495 clearSessionRoutes(uid);
5496}
5497
Eric Laurent6a94d692014-05-20 11:18:06 -07005498void AudioPolicyManager::clearAudioPatches(uid_t uid)
5499{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005500 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005502 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005503 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005504 }
5505 }
5506}
5507
François Gaffiec005e562018-11-06 15:04:49 +01005508void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005509{
François Gaffiec005e562018-11-06 15:04:49 +01005510 // Take the first attributes following the product strategy as it is used to retrieve the routed
5511 // device. All attributes wihin a strategy follows the same "routing strategy"
5512 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5513 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005514 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005515 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005516 for (size_t j = 0; j < mOutputs.size(); j++) {
5517 if (mOutputs.keyAt(j) == ouptutToSkip) {
5518 continue;
5519 }
5520 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005521 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005522 continue;
5523 }
5524 // If the default device for this strategy is on another output mix,
5525 // invalidate all tracks in this strategy to force re connection.
5526 // Otherwise select new device on the output mix.
5527 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005528 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005529 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005530 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5531 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5532 // If the device is using preferred mixer attributes, the output need to reopen
5533 // with default configuration when the new selected devices are different from
5534 // current routing devices.
5535 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5536 continue;
5537 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305538 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005539 }
5540 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005541 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005542}
5543
5544void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5545{
5546 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005547 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005548 for (size_t i = 0; i < mOutputs.size(); i++) {
5549 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005550 for (const auto& client : outputDesc->getClientIterable()) {
5551 if (client->hasPreferredDevice() && client->uid() == uid) {
5552 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005553 auto clientStrategy = client->strategy();
5554 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5555 end(affectedStrategies)) {
5556 continue;
5557 }
5558 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005559 }
5560 }
5561 }
5562 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005563 for (const auto& strategy : affectedStrategies) {
5564 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005565 }
5566
5567 // remove input routes associated with this uid
5568 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005569 for (size_t i = 0; i < mInputs.size(); i++) {
5570 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005571 for (const auto& client : inputDesc->getClientIterable()) {
5572 if (client->hasPreferredDevice() && client->uid() == uid) {
5573 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5574 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005575 }
5576 }
5577 }
5578 // reroute inputs if necessary
5579 SortedVector<audio_io_handle_t> inputsToClose;
5580 for (size_t i = 0; i < mInputs.size(); i++) {
5581 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005582 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005583 inputsToClose.add(inputDesc->mIoHandle);
5584 }
5585 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005586 for (const auto& input : inputsToClose) {
5587 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005588 }
5589}
5590
Eric Laurentd60560a2015-04-10 11:31:20 -07005591void AudioPolicyManager::clearAudioSources(uid_t uid)
5592{
5593 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005594 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5595 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005596 stopAudioSource(mAudioSources.keyAt(i));
5597 }
5598 }
5599}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005600
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005601status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5602 audio_io_handle_t *ioHandle,
5603 audio_devices_t *device)
5604{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005605 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5606 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005607 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005608 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5609 if (deviceDesc == nullptr) {
5610 return INVALID_OPERATION;
5611 }
5612 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005613
François Gaffiedf372692015-03-19 10:43:27 +01005614 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005615}
5616
Eric Laurentd60560a2015-04-10 11:31:20 -07005617status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005618 const audio_attributes_t *attributes,
5619 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005620 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005621{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005622 ALOGV("%s", __FUNCTION__);
5623 *portId = AUDIO_PORT_HANDLE_NONE;
5624
5625 if (source == NULL || attributes == NULL || portId == NULL) {
5626 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5627 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005628 return BAD_VALUE;
5629 }
5630
Eric Laurentd60560a2015-04-10 11:31:20 -07005631 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5632 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005633 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5634 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005635 return INVALID_OPERATION;
5636 }
5637
François Gaffie11d30102018-11-02 16:09:09 +01005638 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005639 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005640 String8(source->ext.device.address),
5641 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005642 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005643 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005644 return BAD_VALUE;
5645 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005646
jiabin4ef93452019-09-10 14:29:54 -07005647 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005648
François Gaffieaaac0fd2018-11-22 17:56:39 +01005649 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005650 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005651 mEngine->getStreamTypeForAttributes(*attributes),
5652 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005653 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005654
5655 status_t status = connectAudioSource(sourceDesc);
5656 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005657 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005658 }
5659 return status;
5660}
5661
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005662status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005663{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005664 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005665
5666 // make sure we only have one patch per source.
5667 disconnectAudioSource(sourceDesc);
5668
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005669 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005670 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5671 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5672 sourceDesc->srcDevice()->type(),
5673 String8(sourceDesc->srcDevice()->address().c_str()),
5674 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005675 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005676 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005677 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005678 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005679 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5680 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5681 return INVALID_OPERATION;
5682 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005683 PatchBuilder patchBuilder;
5684 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5685 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005686
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005687 return connectAudioSourceToSink(
5688 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005689}
5690
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005691status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005692{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005693 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5694 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005695 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005696 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005697 return BAD_VALUE;
5698 }
5699 status_t status = disconnectAudioSource(sourceDesc);
5700
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005701 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005702 return status;
5703}
5704
Andy Hung2ddee192015-12-18 17:34:44 -08005705status_t AudioPolicyManager::setMasterMono(bool mono)
5706{
5707 if (mMasterMono == mono) {
5708 return NO_ERROR;
5709 }
5710 mMasterMono = mono;
5711 // if enabling mono we close all offloaded devices, which will invalidate the
5712 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5713 // for recreating the new AudioTrack as non-offloaded PCM.
5714 //
5715 // If disabling mono, we leave all tracks as is: we don't know which clients
5716 // and tracks are able to be recreated as offloaded. The next "song" should
5717 // play back offloaded.
5718 if (mMasterMono) {
5719 Vector<audio_io_handle_t> offloaded;
5720 for (size_t i = 0; i < mOutputs.size(); ++i) {
5721 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5722 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5723 offloaded.push(desc->mIoHandle);
5724 }
5725 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005726 for (const auto& handle : offloaded) {
5727 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005728 }
5729 }
5730 // update master mono for all remaining outputs
5731 for (size_t i = 0; i < mOutputs.size(); ++i) {
5732 updateMono(mOutputs.keyAt(i));
5733 }
5734 return NO_ERROR;
5735}
5736
5737status_t AudioPolicyManager::getMasterMono(bool *mono)
5738{
5739 *mono = mMasterMono;
5740 return NO_ERROR;
5741}
5742
Eric Laurentac9cef52017-06-09 15:46:26 -07005743float AudioPolicyManager::getStreamVolumeDB(
5744 audio_stream_type_t stream, int index, audio_devices_t device)
5745{
jiabin9a3361e2019-10-01 09:38:30 -07005746 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005747}
5748
jiabin81772902018-04-02 17:52:27 -07005749status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5750 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005751 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005752{
Kriti Dang6537def2021-03-02 13:46:59 +01005753 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5754 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005755 return BAD_VALUE;
5756 }
Kriti Dang6537def2021-03-02 13:46:59 +01005757 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5758 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005759
5760 size_t formatsWritten = 0;
5761 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005762
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005763 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005764 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5765 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005766 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005767 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005768 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005769 bool formatEnabled = true;
5770 switch (forceUse) {
5771 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005772 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005773 break;
5774 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5775 formatEnabled = false;
5776 break;
5777 default: // AUTO or ALWAYS => true
5778 break;
jiabin81772902018-04-02 17:52:27 -07005779 }
5780 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5781 }
jiabin81772902018-04-02 17:52:27 -07005782 }
5783 return NO_ERROR;
5784}
5785
Kriti Dang6537def2021-03-02 13:46:59 +01005786status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5787 audio_format_t *surroundFormats) {
5788 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5789 return BAD_VALUE;
5790 }
5791 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5792 __func__, *numSurroundFormats, surroundFormats);
5793
5794 size_t formatsWritten = 0;
5795 size_t formatsMax = *numSurroundFormats;
5796 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5797
5798 // Return formats from all device profiles that have already been resolved by
5799 // checkOutputsForDevice().
5800 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5801 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5802 audio_devices_t deviceType = device->type();
5803 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5804 // returns formats reported by HDMI devices.
5805 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5806 continue;
5807 }
5808 // Formats reported by sink devices
5809 std::unordered_set<audio_format_t> formatset;
5810 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5811 formatset.insert(it->second.begin(), it->second.end());
5812 }
5813
5814 // Formats hard-coded in the in policy configuration file (if any).
5815 FormatVector encodedFormats = device->encodedFormats();
5816 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5817 // Filter the formats which are supported by the vendor hardware.
5818 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005819 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005820 formats.insert(*it);
5821 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005822 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005823 if (pair.second.count(*it) != 0) {
5824 formats.insert(pair.first);
5825 break;
5826 }
5827 }
5828 }
5829 }
5830 }
5831 *numSurroundFormats = formats.size();
5832 for (const auto& format: formats) {
5833 if (formatsWritten < formatsMax) {
5834 surroundFormats[formatsWritten++] = format;
5835 }
5836 }
5837 return NO_ERROR;
5838}
5839
jiabin81772902018-04-02 17:52:27 -07005840status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5841{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005842 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005843 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5844 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005845 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005846 return BAD_VALUE;
5847 }
5848
Mikhail Naganov100f0122018-11-29 11:22:16 -08005849 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5850 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005851 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005852 return INVALID_OPERATION;
5853 }
5854
Mikhail Naganov100f0122018-11-29 11:22:16 -08005855 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005856 return NO_ERROR;
5857 }
5858
Mikhail Naganov100f0122018-11-29 11:22:16 -08005859 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005860 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005861 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005862 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005863 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005864 }
5865 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005866 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005867 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005868 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005869 }
5870 }
5871
5872 sp<SwAudioOutputDescriptor> outputDesc;
5873 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005874 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5875 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005876 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5877 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005878 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005879 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005880 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5881 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5882 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005883 name.c_str(),
5884 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005885 if (status != NO_ERROR) {
5886 continue;
5887 }
5888 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5889 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5890 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005891 name.c_str(),
5892 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005893 profileUpdated |= (status == NO_ERROR);
5894 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005895 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005896 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005897 AUDIO_DEVICE_IN_HDMI);
5898 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5899 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005900 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005901 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005902 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5903 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5904 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005905 name.c_str(),
5906 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005907 if (status != NO_ERROR) {
5908 continue;
5909 }
5910 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5911 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5912 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005913 name.c_str(),
5914 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005915 profileUpdated |= (status == NO_ERROR);
5916 }
5917
jiabin81772902018-04-02 17:52:27 -07005918 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005919 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005920 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005921 }
5922
5923 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5924}
5925
Eric Laurent5ada82e2019-08-29 17:53:54 -07005926void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005927{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005928 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005929 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005930 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005931 }
5932}
5933
jiabin6012f912018-11-02 17:06:30 -07005934bool AudioPolicyManager::isHapticPlaybackSupported()
5935{
5936 for (const auto& hwModule : mHwModules) {
5937 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5938 for (const auto &outProfile : outputProfiles) {
5939 struct audio_port audioPort;
5940 outProfile->toAudioPort(&audioPort);
5941 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5942 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5943 return true;
5944 }
5945 }
5946 }
5947 }
5948 return false;
5949}
5950
Carter Hsu325a8eb2022-01-19 19:56:51 +08005951bool AudioPolicyManager::isUltrasoundSupported()
5952{
5953 bool hasUltrasoundOutput = false;
5954 bool hasUltrasoundInput = false;
5955 for (const auto& hwModule : mHwModules) {
5956 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5957 if (!hasUltrasoundOutput) {
5958 for (const auto &outProfile : outputProfiles) {
5959 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5960 hasUltrasoundOutput = true;
5961 break;
5962 }
5963 }
5964 }
5965
5966 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5967 if (!hasUltrasoundInput) {
5968 for (const auto &inputProfile : inputProfiles) {
5969 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5970 hasUltrasoundInput = true;
5971 break;
5972 }
5973 }
5974 }
5975
5976 if (hasUltrasoundOutput && hasUltrasoundInput)
5977 return true;
5978 }
5979 return false;
5980}
5981
Atneya Nair698f5ef2022-12-15 16:15:09 -08005982bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5983{
5984 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5985 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5986 for (const auto& hwModule : mHwModules) {
5987 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5988 for (const auto &inputProfile : inputProfiles) {
5989 if ((inputProfile->getFlags() & mask) == mask) {
5990 return true;
5991 }
5992 }
5993 }
5994 return false;
5995}
5996
Eric Laurent8340e672019-11-06 11:01:08 -08005997bool AudioPolicyManager::isCallScreenModeSupported()
5998{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005999 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006000}
6001
6002
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006003status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006004{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006005 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006006 if (!sourceDesc->isConnected()) {
6007 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6008 return NO_ERROR;
6009 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006010 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6011 if (swOutput != 0) {
6012 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006013 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006014 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006015 }
jiabinbce0c1d2020-10-05 11:20:18 -07006016 if (releaseOutput(sourceDesc->portId())) {
6017 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6018 // no need to release audio patch here but just return NO_ERROR.
6019 return NO_ERROR;
6020 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006021 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006022 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006023 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006024 // close Hwoutput and remove from mHwOutputs
6025 } else {
6026 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6027 }
6028 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006029 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006030 sourceDesc->disconnect();
6031 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006032}
6033
François Gaffiec005e562018-11-06 15:04:49 +01006034sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6035 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006036{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006037 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006038 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006039 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006040 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006041 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6042 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006043 source = sourceDesc;
6044 break;
6045 }
6046 }
6047 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006048}
6049
Eric Laurentb4f42a92022-01-17 17:37:31 +01006050bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006051 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006052 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006053{
6054 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6055 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006056 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006057 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006058 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6059 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6060 return false;
6061 }
6062 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6063 return false;
6064 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006065 }
6066
Eric Laurentd332bc82023-08-04 11:45:23 +02006067 // The caller can have the audio config criteria ignored by either passing a null ptr or
6068 // the AUDIO_CONFIG_INITIALIZER value.
6069 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006070 // some positional channel masks and PCM format and for stereo if low latency performance
6071 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006072
6073 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006074 static const bool stereo_spatialization_enabled =
6075 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006076 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006077 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006078 ? audio_channel_mask_contains_stereo(config->channel_mask)
6079 : audio_is_channel_mask_spatialized(config->channel_mask);
6080 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006081 return false;
6082 }
6083 if (!audio_is_linear_pcm(config->format)) {
6084 return false;
6085 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006086 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6087 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6088 return false;
6089 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006090 }
6091
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006092 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006093 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006094 if (profile == nullptr) {
6095 return false;
6096 }
6097
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006098 return true;
6099}
6100
6101void AudioPolicyManager::checkVirtualizerClientRoutes() {
6102 std::set<audio_stream_type_t> streamsToInvalidate;
6103 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006104 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6105 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006106 audio_attributes_t attr = client->attributes();
6107 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6108 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6109 audio_config_base_t clientConfig = client->config();
6110 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006111 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006112 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006113 streamsToInvalidate.insert(client->stream());
6114 }
6115 }
6116 }
6117
jiabinc44b3462022-12-08 12:52:31 -08006118 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006119}
6120
Eric Laurente191d1b2022-04-15 11:59:25 +02006121
6122bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6123 const sp<SwAudioOutputDescriptor>& outputDesc) {
6124 if (outputDesc->isDuplicated()) {
6125 return false;
6126 }
6127 DeviceVector devices = outputDesc->supportedDevices();
6128 for (size_t i = 0; i < mOutputs.size(); i++) {
6129 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6130 if (desc == outputDesc || desc->isDuplicated()) {
6131 continue;
6132 }
6133 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6134 if (!sharedDevices.isEmpty()
6135 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6136 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6137 return false;
6138 }
6139 }
6140 return true;
6141}
6142
6143
Eric Laurentfa0f6742021-08-17 18:39:44 +02006144status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006145 const audio_attributes_t *attr,
6146 audio_io_handle_t *output) {
6147 *output = AUDIO_IO_HANDLE_NONE;
6148
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006149 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6150 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6151 audio_config_t *configPtr = nullptr;
6152 audio_config_t config;
6153 if (mixerConfig != nullptr) {
6154 config = audio_config_initializer(mixerConfig);
6155 configPtr = &config;
6156 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006157 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006158 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006159 return BAD_VALUE;
6160 }
6161
6162 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006163 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006164 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006165 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006166 return BAD_VALUE;
6167 }
6168
Eric Laurente191d1b2022-04-15 11:59:25 +02006169 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006170 for (size_t i = 0; i < mOutputs.size(); i++) {
6171 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006172 if (!desc->isDuplicated()
6173 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6174 spatializerOutputs.push_back(desc);
6175 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006176 }
6177 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006178 mSpatializerOutput.clear();
6179 bool outputsChanged = false;
6180 for (const auto& desc : spatializerOutputs) {
6181 if (desc->mProfile == profile
6182 && (configPtr == nullptr
6183 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6184 mSpatializerOutput = desc;
6185 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6186 } else {
6187 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6188 " and devices %s", __func__, desc->mIoHandle,
6189 configPtr != nullptr ? configPtr->channel_mask : 0,
6190 devices.toString().c_str());
6191 closeOutput(desc->mIoHandle);
6192 outputsChanged = true;
6193 }
Eric Laurent39095982021-08-24 18:29:27 +02006194 }
6195
Eric Laurente191d1b2022-04-15 11:59:25 +02006196 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006197 sp<SwAudioOutputDescriptor> desc =
6198 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006199 if (desc != nullptr) {
6200 mSpatializerOutput = desc;
6201 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006202 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006203 }
6204
6205 checkVirtualizerClientRoutes();
6206
Eric Laurente191d1b2022-04-15 11:59:25 +02006207 if (outputsChanged) {
6208 mPreviousOutputs = mOutputs;
6209 mpClientInterface->onAudioPortListUpdate();
6210 }
6211
6212 if (mSpatializerOutput == nullptr) {
6213 ALOGV("%s could not open spatializer output with requested config", __func__);
6214 return BAD_VALUE;
6215 }
Eric Laurent39095982021-08-24 18:29:27 +02006216 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006217 ALOGV("%s returning new spatializer output %d", __func__, *output);
6218 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006219}
6220
Eric Laurentfa0f6742021-08-17 18:39:44 +02006221status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6222 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006223 return INVALID_OPERATION;
6224 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006225 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006226 return BAD_VALUE;
6227 }
Eric Laurent39095982021-08-24 18:29:27 +02006228
Eric Laurente191d1b2022-04-15 11:59:25 +02006229 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6230 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6231 closeOutput(mSpatializerOutput->mIoHandle);
6232 //from now on mSpatializerOutput is null
6233 checkVirtualizerClientRoutes();
6234 }
Eric Laurent39095982021-08-24 18:29:27 +02006235
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006236 return NO_ERROR;
6237}
6238
Eric Laurente552edb2014-03-10 17:42:56 -07006239// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006240// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006241// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006242uint32_t AudioPolicyManager::nextAudioPortGeneration()
6243{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006244 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006245}
6246
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006247AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006248 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006249 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006250 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006251 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006252 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006253 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006254 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006255 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006256 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006257 mAudioPortGeneration(1),
6258 mBeaconMuteRefCount(0),
6259 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006260 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006261 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006262 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006263 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006264{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006265}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006266
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006267status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006268 if (mEngine == nullptr) {
6269 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006270 }
6271 mEngine->setObserver(this);
6272 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006273 if (status != NO_ERROR) {
6274 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6275 return status;
6276 }
François Gaffie2110e042015-03-24 08:41:51 +01006277
jiabin29230182023-04-04 21:02:36 +00006278 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6279 // at the end of this function.
6280 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006281 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6282 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6283
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006284 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006285 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006286 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006287
Eric Laurent3a4311c2014-03-17 12:00:47 -07006288 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006289 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6290 defaultOutputDevice == nullptr ||
6291 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6292 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6293 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006294 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006295 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006296 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006297
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006298 // Silence ALOGV statements
6299 property_set("log.tag." LOG_TAG, "D");
6300
Eric Laurente552edb2014-03-10 17:42:56 -07006301 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006302 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006303}
6304
Eric Laurente0720872014-03-11 09:30:41 -07006305AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006306{
Eric Laurente552edb2014-03-10 17:42:56 -07006307 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006308 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006309 }
6310 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006311 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006312 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006313 mAvailableOutputDevices.clear();
6314 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006315 mOutputs.clear();
6316 mInputs.clear();
6317 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006318 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006319 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006320}
6321
Eric Laurente0720872014-03-11 09:30:41 -07006322status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006323{
Eric Laurent87ffa392015-05-22 10:32:38 -07006324 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006325}
6326
Eric Laurente552edb2014-03-10 17:42:56 -07006327// ---
6328
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006329void AudioPolicyManager::onNewAudioModulesAvailable()
6330{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006331 DeviceVector newDevices;
6332 onNewAudioModulesAvailableInt(&newDevices);
6333 if (!newDevices.empty()) {
6334 nextAudioPortGeneration();
6335 mpClientInterface->onAudioPortListUpdate();
6336 }
6337}
6338
6339void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6340{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006341 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006342 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6343 continue;
6344 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006345 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006346 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6347 handle != AUDIO_MODULE_HANDLE_NONE) {
6348 hwModule->setHandle(handle);
6349 } else {
6350 ALOGW("could not load HW module %s", hwModule->getName());
6351 continue;
6352 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006353 }
6354 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006355 // open all output streams needed to access attached devices.
6356 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006357 // This also validates mAvailableOutputDevices list
6358 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6359 if (!outProfile->canOpenNewIo()) {
6360 ALOGE("Invalid Output profile max open count %u for profile %s",
6361 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6362 continue;
6363 }
6364 if (!outProfile->hasSupportedDevices()) {
6365 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6366 continue;
6367 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006368 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6369 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006370 mTtsOutputAvailable = true;
6371 }
6372
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006373 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006374 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006375 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006376 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6377 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006378 } else {
6379 // choose first device present in profile's SupportedDevices also part of
6380 // mAvailableOutputDevices.
6381 if (availProfileDevices.isEmpty()) {
6382 continue;
6383 }
6384 supportedDevice = availProfileDevices.itemAt(0);
6385 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006386 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006387 continue;
6388 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306389
6390 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6391 && availProfileDevices.areAllDevicesAttached()) {
6392 ALOGV("%s skip opening output for mmap profile %s", __func__,
6393 outProfile->getTagName().c_str());
6394 continue;
6395 }
6396
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006397 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6398 mpClientInterface);
6399 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006400 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6401 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006402 AUDIO_STREAM_DEFAULT,
6403 AUDIO_OUTPUT_FLAG_NONE, &output);
6404 if (status != NO_ERROR) {
6405 ALOGW("Cannot open output stream for devices %s on hw module %s",
6406 supportedDevice->toString().c_str(), hwModule->getName());
6407 continue;
6408 }
6409 for (const auto &device : availProfileDevices) {
6410 // give a valid ID to an attached device once confirmed it is reachable
6411 if (!device->isAttached()) {
6412 device->attach(hwModule);
6413 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006414 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006415 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006416 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6417 }
6418 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006419 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006420 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6421 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006422 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006423 }
Eric Laurent39095982021-08-24 18:29:27 +02006424 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006425 outputDesc->close();
6426 } else {
6427 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306428 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006429 DeviceVector(supportedDevice),
6430 true,
6431 0,
6432 NULL);
6433 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006434 }
6435 // open input streams needed to access attached devices to validate
6436 // mAvailableInputDevices list
6437 for (const auto& inProfile : hwModule->getInputProfiles()) {
6438 if (!inProfile->canOpenNewIo()) {
6439 ALOGE("Invalid Input profile max open count %u for profile %s",
6440 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6441 continue;
6442 }
6443 if (!inProfile->hasSupportedDevices()) {
6444 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6445 continue;
6446 }
6447 // chose first device present in profile's SupportedDevices also part of
6448 // available input devices
6449 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006450 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006451 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006452 ALOGV("%s: Input device list is empty! for profile %s",
6453 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006454 continue;
6455 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306456
6457 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6458 && availProfileDevices.areAllDevicesAttached()) {
6459 ALOGV("%s skip opening input for mmap profile %s", __func__,
6460 inProfile->getTagName().c_str());
6461 continue;
6462 }
6463
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006464 sp<AudioInputDescriptor> inputDesc =
6465 new AudioInputDescriptor(inProfile, mpClientInterface);
6466
6467 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6468 status_t status = inputDesc->open(nullptr,
6469 availProfileDevices.itemAt(0),
6470 AUDIO_SOURCE_MIC,
Jaideep Sharma69e093e2024-06-18 14:12:50 +05306471 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006472 &input);
6473 if (status != NO_ERROR) {
6474 ALOGW("Cannot open input stream for device %s on hw module %s",
6475 availProfileDevices.toString().c_str(),
6476 hwModule->getName());
6477 continue;
6478 }
6479 for (const auto &device : availProfileDevices) {
6480 // give a valid ID to an attached device once confirmed it is reachable
6481 if (!device->isAttached()) {
6482 device->attach(hwModule);
6483 device->importAudioPortAndPickAudioProfile(inProfile, true);
6484 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006485 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006486 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6487 }
6488 }
6489 inputDesc->close();
6490 }
6491 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006492
6493 // Check if spatializer outputs can be closed until used.
6494 // mOutputs vector never contains duplicated outputs at this point.
6495 std::vector<audio_io_handle_t> outputsClosed;
6496 for (size_t i = 0; i < mOutputs.size(); i++) {
6497 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6498 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6499 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6500 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006501 nextAudioPortGeneration();
6502 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6503 if (index >= 0) {
6504 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6505 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6506 patchDesc->getAfHandle(), 0);
6507 mAudioPatches.removeItemsAt(index);
6508 mpClientInterface->onAudioPatchListUpdate();
6509 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006510 desc->close();
6511 }
6512 }
6513 for (auto output : outputsClosed) {
6514 removeOutput(output);
6515 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006516}
6517
Eric Laurent98e38192018-02-15 18:31:53 -08006518void AudioPolicyManager::addOutput(audio_io_handle_t output,
6519 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006520{
Eric Laurent1c333e22014-05-20 10:48:17 -07006521 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006522 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006523 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006524 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006525 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006526}
6527
François Gaffie53615e22015-03-19 09:24:12 +01006528void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6529{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006530 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6531 ALOGV("%s: removing primary output", __func__);
6532 mPrimaryOutput = nullptr;
6533 }
François Gaffie53615e22015-03-19 09:24:12 +01006534 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006535 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006536}
6537
Eric Laurent98e38192018-02-15 18:31:53 -08006538void AudioPolicyManager::addInput(audio_io_handle_t input,
6539 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006540{
Eric Laurent1c333e22014-05-20 10:48:17 -07006541 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006542 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006543}
Eric Laurente552edb2014-03-10 17:42:56 -07006544
François Gaffie11d30102018-11-02 16:09:09 +01006545status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006546 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006547 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006548{
François Gaffie11d30102018-11-02 16:09:09 +01006549 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006550 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006551 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006552
François Gaffie11d30102018-11-02 16:09:09 +01006553 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006554 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006555 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006556 }
Eric Laurente552edb2014-03-10 17:42:56 -07006557
Eric Laurent3b73df72014-03-11 09:06:29 -07006558 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006559 // first call getAudioPort to get the supported attributes from the HAL
6560 struct audio_port_v7 port = {};
6561 device->toAudioPort(&port);
6562 status_t status = mpClientInterface->getAudioPort(&port);
6563 if (status == NO_ERROR) {
6564 device->importAudioPort(port);
6565 }
6566
6567 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006568 for (size_t i = 0; i < mOutputs.size(); i++) {
6569 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006570 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006571 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006572 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6573 mOutputs.keyAt(i), device->toString().c_str());
6574 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006575 }
6576 }
6577 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006578 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006579 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006580 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6581 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006582 if (profile->supportsDevice(device)) {
6583 profiles.add(profile);
6584 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6585 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006586 }
6587 }
6588 }
6589
Eric Laurent7b279bb2015-12-14 10:18:23 -08006590 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006591
Eric Laurente552edb2014-03-10 17:42:56 -07006592 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006593 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006594 return BAD_VALUE;
6595 }
6596
6597 // open outputs for matching profiles if needed. Direct outputs are also opened to
6598 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6599 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006600 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006601
6602 // nothing to do if one output is already opened for this profile
6603 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006604 for (j = 0; j < outputs.size(); j++) {
6605 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006606 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006607 // matching profile: save the sample rates, format and channel masks supported
6608 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006609 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006610 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006611 }
Eric Laurente552edb2014-03-10 17:42:56 -07006612 break;
6613 }
6614 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006615 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006616 continue;
6617 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306618 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6619 ALOGV("%s skip opening output for mmap profile %s",
6620 __func__, profile->getTagName().c_str());
6621 continue;
6622 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006623 if (!profile->canOpenNewIo()) {
6624 ALOGW("Max Output number %u already opened for this profile %s",
6625 profile->maxOpenCount, profile->getTagName().c_str());
6626 continue;
6627 }
6628
Eric Laurent83efe1c2017-07-09 16:51:08 -07006629 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006630 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006631 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6632 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006633 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006634 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006635 profiles.removeAt(profile_index);
6636 profile_index--;
6637 } else {
6638 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006639 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006640 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006641 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6642 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006643 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006644 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006645
François Gaffie11d30102018-11-02 16:09:09 +01006646 if (device_distinguishes_on_address(deviceType)) {
6647 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6648 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306649 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6650 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006651 }
Eric Laurente552edb2014-03-10 17:42:56 -07006652 ALOGV("checkOutputsForDevice(): adding output %d", output);
6653 }
6654 }
6655
6656 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006657 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006658 return BAD_VALUE;
6659 }
Eric Laurentd4692962014-05-05 18:13:44 -07006660 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006661 // check if one opened output is not needed any more after disconnecting one device
6662 for (size_t i = 0; i < mOutputs.size(); i++) {
6663 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006664 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006665 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006666 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006667 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006668 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006669 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006670 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6671 mOutputs.keyAt(i));
6672 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006673 }
Eric Laurente552edb2014-03-10 17:42:56 -07006674 }
6675 }
Eric Laurentd4692962014-05-05 18:13:44 -07006676 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006677 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006678 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6679 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006680 if (!profile->supportsDevice(device)) {
6681 continue;
6682 }
6683 ALOGV("checkOutputsForDevice(): "
6684 "clearing direct output profile %zu on module %s",
6685 j, hwModule->getName());
6686 profile->clearAudioProfiles();
6687 if (!profile->hasDynamicAudioProfile()) {
6688 continue;
6689 }
6690 // When a device is disconnected, if there is an IOProfile that contains dynamic
6691 // profiles and supports the disconnected device, call getAudioPort to repopulate
6692 // the capabilities of the devices that is supported by the IOProfile.
6693 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6694 if (supportedDevice == device ||
6695 !mAvailableOutputDevices.contains(supportedDevice)) {
6696 continue;
6697 }
6698 struct audio_port_v7 port;
6699 supportedDevice->toAudioPort(&port);
6700 status_t status = mpClientInterface->getAudioPort(&port);
6701 if (status == NO_ERROR) {
6702 supportedDevice->importAudioPort(port);
6703 }
Eric Laurente552edb2014-03-10 17:42:56 -07006704 }
6705 }
6706 }
6707 }
6708 return NO_ERROR;
6709}
6710
François Gaffie11d30102018-11-02 16:09:09 +01006711status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006712 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006713{
François Gaffie11d30102018-11-02 16:09:09 +01006714 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006715 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006716 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006717 }
6718
Eric Laurentd4692962014-05-05 18:13:44 -07006719 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006720 sp<AudioInputDescriptor> desc;
6721
jiabinbf5f4262023-04-12 21:48:34 +00006722 // first call getAudioPort to get the supported attributes from the HAL
6723 struct audio_port_v7 port = {};
6724 device->toAudioPort(&port);
6725 status_t status = mpClientInterface->getAudioPort(&port);
6726 if (status == NO_ERROR) {
6727 device->importAudioPort(port);
6728 }
6729
Eric Laurent0dd51852019-04-19 18:18:58 -07006730 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006731 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006732 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006733 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006734 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006735 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006736 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006737
François Gaffie11d30102018-11-02 16:09:09 +01006738 if (profile->supportsDevice(device)) {
6739 profiles.add(profile);
6740 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6741 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006742 }
6743 }
6744 }
6745
Eric Laurent0dd51852019-04-19 18:18:58 -07006746 if (profiles.isEmpty()) {
6747 ALOGW("%s: No input profile available for device %s",
6748 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006749 return BAD_VALUE;
6750 }
6751
6752 // open inputs for matching profiles if needed. Direct inputs are also opened to
6753 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6754 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6755
Eric Laurent1c333e22014-05-20 10:48:17 -07006756 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006757
Eric Laurentd4692962014-05-05 18:13:44 -07006758 // nothing to do if one input is already opened for this profile
6759 size_t input_index;
6760 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6761 desc = mInputs.valueAt(input_index);
6762 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006763 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006764 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006765 }
Eric Laurentd4692962014-05-05 18:13:44 -07006766 break;
6767 }
6768 }
6769 if (input_index != mInputs.size()) {
6770 continue;
6771 }
6772
Jaideep Sharma44824a22024-06-18 16:32:34 +05306773 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6774 ALOGV("%s skip opening input for mmap profile %s",
6775 __func__, profile->getTagName().c_str());
6776 continue;
6777 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006778 if (!profile->canOpenNewIo()) {
6779 ALOGW("Max Input number %u already opened for this profile %s",
6780 profile->maxOpenCount, profile->getTagName().c_str());
6781 continue;
6782 }
6783
Eric Laurentfe231122017-11-17 17:48:06 -08006784 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006785 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma69e093e2024-06-18 14:12:50 +05306786 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
6787 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006788
Eric Laurentcf2c0212014-07-25 16:20:43 -07006789 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006790 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006791 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006792 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006793 mpClientInterface->setParameters(input, String8(param));
6794 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006795 }
jiabin12537fc2023-10-12 17:56:08 +00006796 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006797 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006798 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006799 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006800 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006801 }
6802
Eric Laurent0dd51852019-04-19 18:18:58 -07006803 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006804 addInput(input, desc);
6805 }
6806 } // endif input != 0
6807
Eric Laurentcf2c0212014-07-25 16:20:43 -07006808 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006809 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006810 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006811 profiles.removeAt(profile_index);
6812 profile_index--;
6813 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006814 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006815 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006816 }
Eric Laurentd4692962014-05-05 18:13:44 -07006817 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006818
6819 if (checkCloseInput(desc)) {
6820 ALOGV("%s closing input %d", __func__, input);
6821 closeInput(input);
6822 }
Eric Laurentd4692962014-05-05 18:13:44 -07006823 }
6824 } // end scan profiles
6825
6826 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006827 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006828 return BAD_VALUE;
6829 }
6830 } else {
6831 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006832 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006833 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006834 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006835 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006836 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006837 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006838 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006839 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6840 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006841 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006842 }
6843 }
6844 }
6845 } // end disconnect
6846
6847 return NO_ERROR;
6848}
6849
6850
Eric Laurente0720872014-03-11 09:30:41 -07006851void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006852{
6853 ALOGV("closeOutput(%d)", output);
6854
François Gaffie1c878552018-11-22 16:53:21 +01006855 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6856 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006857 ALOGW("closeOutput() unknown output %d", output);
6858 return;
6859 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006860 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006861 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006862
Eric Laurente552edb2014-03-10 17:42:56 -07006863 // look for duplicated outputs connected to the output being removed.
6864 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006865 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6866 if (dupOutput->isDuplicated() &&
6867 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6868 sp<SwAudioOutputDescriptor> remainingOutput =
6869 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006870 // As all active tracks on duplicated output will be deleted,
6871 // and as they were also referenced on the other output, the reference
6872 // count for their stream type must be adjusted accordingly on
6873 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006874 const bool wasActive = remainingOutput->isActive();
6875 // Note: no-op on the closing output where all clients has already been set inactive
6876 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006877 // stop() will be a no op if the output is still active but is needed in case all
6878 // active streams refcounts where cleared above
6879 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006880 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006881 }
Eric Laurente552edb2014-03-10 17:42:56 -07006882 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6883 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6884
6885 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006886 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006887 }
6888 }
6889
Eric Laurent05b90f82014-08-27 15:32:29 -07006890 nextAudioPortGeneration();
6891
François Gaffie1c878552018-11-22 16:53:21 +01006892 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006893 if (index >= 0) {
6894 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006895 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6896 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006897 mAudioPatches.removeItemsAt(index);
6898 mpClientInterface->onAudioPatchListUpdate();
6899 }
6900
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006901 if (closingOutputWasActive) {
6902 closingOutput->stop();
6903 }
François Gaffie1c878552018-11-22 16:53:21 +01006904 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006905 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6906 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6907 for (const auto device : closingOutput->devices()) {
6908 device->setPreferredConfig(nullptr);
6909 }
6910 }
Eric Laurente552edb2014-03-10 17:42:56 -07006911
François Gaffie53615e22015-03-19 09:24:12 +01006912 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006913 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006914 if (closingOutput == mSpatializerOutput) {
6915 mSpatializerOutput.clear();
6916 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006917
6918 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6919 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006920 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006921 bool directOutputOpen = false;
6922 for (size_t i = 0; i < mOutputs.size(); i++) {
6923 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6924 directOutputOpen = true;
6925 break;
6926 }
6927 }
6928 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006929 ALOGV("no direct outputs open, reset MSD patches");
6930 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6931 // how output devices for patching are resolved. Avoid by caching and reusing the
6932 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6933 // devices to patch to. This may be complicated by the fact that devices may become
6934 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006935 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006936 }
6937 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006938}
6939
6940void AudioPolicyManager::closeInput(audio_io_handle_t input)
6941{
6942 ALOGV("closeInput(%d)", input);
6943
6944 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6945 if (inputDesc == NULL) {
6946 ALOGW("closeInput() unknown input %d", input);
6947 return;
6948 }
6949
Eric Laurent6a94d692014-05-20 11:18:06 -07006950 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006951
François Gaffie11d30102018-11-02 16:09:09 +01006952 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006953 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006954 if (index >= 0) {
6955 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006956 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6957 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006958 mAudioPatches.removeItemsAt(index);
6959 mpClientInterface->onAudioPatchListUpdate();
6960 }
6961
François Gaffie6ebbce02023-07-19 13:27:53 +02006962 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006963 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006964 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006965
François Gaffie11d30102018-11-02 16:09:09 +01006966 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6967 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006968 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006969 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006970 }
Eric Laurente552edb2014-03-10 17:42:56 -07006971}
6972
François Gaffie11d30102018-11-02 16:09:09 +01006973SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6974 const DeviceVector &devices,
6975 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006976{
6977 SortedVector<audio_io_handle_t> outputs;
6978
François Gaffie11d30102018-11-02 16:09:09 +01006979 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006980 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006981 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006982 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006983 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006984 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006985 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006986 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006987 outputs.add(openOutputs.keyAt(i));
6988 }
6989 }
6990 return outputs;
6991}
6992
Mikhail Naganov37977152018-07-11 15:54:44 -07006993void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6994{
6995 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6996 // output is suspended before any tracks are moved to it
6997 checkA2dpSuspend();
6998 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006999 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007000 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007001 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007002 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007003 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7004 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7005 // configuration changes will ultimately be rerouted correctly. We can still avoid
7006 // unnecessary rerouting by caching and reusing the arguments to
7007 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7008 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007009 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007010 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007011 // an event that changed routing likely occurred, inform upper layers
7012 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007013}
7014
François Gaffiec005e562018-11-06 15:04:49 +01007015bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7016 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007017{
François Gaffiec005e562018-11-06 15:04:49 +01007018 return mEngine->getProductStrategyForAttributes(lAttr) ==
7019 mEngine->getProductStrategyForAttributes(rAttr);
7020}
7021
Francois Gaffieff1eb522020-05-06 18:37:04 +02007022void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7023{
7024 for (size_t i = 0; i < mAudioSources.size(); i++) {
7025 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7026 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007027 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007028 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007029 connectAudioSource(sourceDesc);
7030 }
7031 }
7032}
7033
7034void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7035{
7036 for (size_t i = 0; i < mAudioSources.size(); i++) {
7037 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7038 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7039 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7040 disconnectAudioSource(sourceDesc);
7041 }
7042 }
7043}
7044
François Gaffiec005e562018-11-06 15:04:49 +01007045void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7046{
7047 auto psId = mEngine->getProductStrategyForAttributes(attr);
7048
7049 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7050 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007051
François Gaffie11d30102018-11-02 16:09:09 +01007052 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7053 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007054
Eric Laurentc209fe42020-06-05 18:11:23 -07007055 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007056 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007057 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007058 // take into account dynamic audio policies related changes: if a client is now associated
7059 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007060 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007061 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7062 if (desc->isDuplicated()) {
7063 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007064 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007065 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7066 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7067 continue;
7068 }
7069 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007070 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007071 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7072 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7073 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007074 if (status != OK) {
7075 continue;
7076 }
yucliuf4de36d2020-09-14 14:57:56 -07007077 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007078 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007079 maxLatency = desc->latency();
7080 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007081 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007082 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007083 }
7084 }
7085
Eric Laurent56ed8842022-11-15 16:04:41 +01007086 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007087 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7088 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007089 for (audio_io_handle_t srcOut : srcOutputs) {
7090 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007091 if (desc == nullptr) continue;
7092
7093 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007094 maxLatency = desc->latency();
7095 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007096
Eric Laurent56ed8842022-11-15 16:04:41 +01007097 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007098 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007099 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007100 // a client on a non direct outputs has necessarily a linear PCM format
7101 // so we can call selectOutput() safely
7102 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7103 client->flags(),
7104 client->config().format,
7105 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007106 client->config().sample_rate,
7107 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007108 if (newOutput != srcOut) {
7109 invalidate = true;
7110 break;
7111 }
7112 } else {
7113 sp<IOProfile> profile = getProfileForOutput(newDevices,
7114 client->config().sample_rate,
7115 client->config().format,
7116 client->config().channel_mask,
7117 client->flags(),
7118 true /* directOnly */);
7119 if (profile != desc->mProfile) {
7120 invalidate = true;
7121 break;
7122 }
7123 }
7124 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007125 // mute strategy while moving tracks from one output to another
7126 if (invalidate) {
7127 invalidatedOutputs.push_back(desc);
7128 if (desc->isStrategyActive(psId)) {
7129 setStrategyMute(psId, true, desc);
7130 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7131 newDevices.types());
7132 }
Eric Laurente552edb2014-03-10 17:42:56 -07007133 }
François Gaffiec005e562018-11-06 15:04:49 +01007134 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007135 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007136 connectAudioSource(source);
7137 }
Eric Laurente552edb2014-03-10 17:42:56 -07007138 }
7139
Eric Laurent56ed8842022-11-15 16:04:41 +01007140 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7141 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7142 std::to_string(srcOutputs[0]).c_str(),
7143 std::to_string(dstOutputs[0]).c_str());
7144
François Gaffiec005e562018-11-06 15:04:49 +01007145 // Move effects associated to this stream from previous output to new output
7146 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007147 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007148 }
François Gaffiec005e562018-11-06 15:04:49 +01007149 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007150 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007151 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007152 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007153 desc->setTracksInvalidatedStatusByStrategy(psId);
7154 }
Eric Laurente552edb2014-03-10 17:42:56 -07007155 }
7156 }
7157}
7158
Eric Laurente0720872014-03-11 09:30:41 -07007159void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007160{
François Gaffiec005e562018-11-06 15:04:49 +01007161 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7162 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7163 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007164 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007165 }
Eric Laurente552edb2014-03-10 17:42:56 -07007166}
7167
Kevin Rocard153f92d2018-12-18 18:33:28 -08007168void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007169 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007170 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007171 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007172 for (size_t i = 0; i < mOutputs.size(); i++) {
7173 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7174 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007175 sp<AudioPolicyMix> primaryMix;
7176 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007177 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007178 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7179 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7180 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007181 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7182 for (auto &secondaryMix : secondaryMixes) {
7183 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7184 if (outputDesc != nullptr &&
7185 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7186 secondaryDescs.push_back(outputDesc);
7187 }
7188 }
7189
jiabinc44b3462022-12-08 12:52:31 -08007190 if (status != OK &&
7191 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7192 // When it failed to query secondary output, only invalidate the client that is not
7193 // MMAP. The reason is that MMAP stream will not support secondary output.
7194 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007195 } else if (!std::equal(
7196 client->getSecondaryOutputs().begin(),
7197 client->getSecondaryOutputs().end(),
7198 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007199 if (!audio_is_linear_pcm(client->config().format)) {
7200 // If the format is not PCM, the tracks should be invalidated to get correct
7201 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007202 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007203 } else {
7204 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7205 std::vector<audio_io_handle_t> secondaryOutputIds;
7206 for (const auto &secondaryDesc: secondaryDescs) {
7207 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7208 weakSecondaryDescs.push_back(secondaryDesc);
7209 }
7210 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7211 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007212 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007213 }
7214 }
7215 }
jiabin10a03f12021-05-07 23:46:28 +00007216 if (!trackSecondaryOutputs.empty()) {
7217 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7218 }
jiabinc44b3462022-12-08 12:52:31 -08007219 if (!clientsToInvalidate.empty()) {
7220 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7221 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007222 }
7223}
7224
Eric Laurent2517af32020-11-25 15:31:27 +01007225bool AudioPolicyManager::isScoRequestedForComm() const {
7226 AudioDeviceTypeAddrVector devices;
7227 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7228 for (const auto &device : devices) {
7229 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7230 return true;
7231 }
7232 }
7233 return false;
7234}
7235
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007236bool AudioPolicyManager::isHearingAidUsedForComm() const {
7237 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7238 true /*fromCache*/);
7239 for (const auto &device : devices) {
7240 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7241 return true;
7242 }
7243 }
7244 return false;
7245}
7246
7247
Eric Laurente0720872014-03-11 09:30:41 -07007248void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007249{
François Gaffie53615e22015-03-19 09:24:12 +01007250 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007251 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007252 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007253 return;
7254 }
7255
Eric Laurent3a4311c2014-03-17 12:00:47 -07007256 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007257 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7258 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007259 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007260
7261 // if suspended, restore A2DP output if:
7262 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007263 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007264 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007265 //
Eric Laurentf732e072016-08-03 19:30:28 -07007266 // if not suspended, suspend A2DP output if:
7267 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007268 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007269 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007270 //
7271 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007272 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007273 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007274 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007275 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007276
7277 mpClientInterface->restoreOutput(a2dpOutput);
7278 mA2dpSuspended = false;
7279 }
7280 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007281 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007282 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007283 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007284 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007285
7286 mpClientInterface->suspendOutput(a2dpOutput);
7287 mA2dpSuspended = true;
7288 }
7289 }
7290}
7291
François Gaffie11d30102018-11-02 16:09:09 +01007292DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7293 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007294{
François Gaffiedb1755b2023-09-01 11:50:35 +02007295 if (outputDesc == nullptr) {
7296 return DeviceVector{};
7297 }
François Gaffie11d30102018-11-02 16:09:09 +01007298
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007299 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007300 if (index >= 0) {
7301 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007302 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007303 ALOGV("%s device %s forced by patch %d", __func__,
7304 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7305 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007306 }
7307 }
7308
Dean Wheatley514b4312020-06-17 21:45:00 +10007309 // Do not retrieve engine device for outputs through MSD
7310 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7311 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7312 return outputDesc->devices();
7313 }
7314
Eric Laurent97ac8712018-07-27 18:59:02 -07007315 // Honor explicit routing requests only if no client using default routing is active on this
7316 // input: a specific app can not force routing for other apps by setting a preferred device.
7317 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007318 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007319 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007320 if (device != nullptr) {
7321 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007322 }
7323
François Gaffiea807ef92018-11-05 10:44:33 +01007324 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7325 // of setForceUse / Default Bus device here
7326 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7327 if (device != nullptr) {
7328 return DeviceVector(device);
7329 }
7330
François Gaffiedb1755b2023-09-01 11:50:35 +02007331 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007332 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7333 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307334 auto hasStreamActive = [&](auto stream) {
7335 return hasStream(streams, stream) && isStreamActive(stream, 0);
7336 };
Eric Laurent484e9272018-06-07 17:29:23 -07007337
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307338 auto doGetOutputDevicesForVoice = [&]() {
7339 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007340 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307341 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007342 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7343 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307344 };
7345
7346 // With low-latency playing on speaker, music on WFD, when the first low-latency
7347 // output is stopped, getNewOutputDevices checks for a product strategy
7348 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007349 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307350 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7351 // stream is associated to the output descriptor.
7352 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7353 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7354 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7355 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007356 // Retrieval of devices for voice DL is done on primary output profile, cannot
7357 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007358 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007359 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7360 break;
7361 }
Eric Laurente552edb2014-03-10 17:42:56 -07007362 }
François Gaffiec005e562018-11-06 15:04:49 +01007363 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007364 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007365}
7366
François Gaffie11d30102018-11-02 16:09:09 +01007367sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7368 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007369{
François Gaffie11d30102018-11-02 16:09:09 +01007370 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007371
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007372 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007373 if (index >= 0) {
7374 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007375 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007376 ALOGV("getNewInputDevice() device %s forced by patch %d",
7377 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7378 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007379 }
7380 }
7381
Eric Laurent97ac8712018-07-27 18:59:02 -07007382 // Honor explicit routing requests only if no client using default routing is active on this
7383 // input: a specific app can not force routing for other apps by setting a preferred device.
7384 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007385 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7386 if (device != nullptr) {
7387 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007388 }
7389
Eric Laurentdc95a252018-04-12 12:46:56 -07007390 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007391 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007392 audio_attributes_t attributes;
7393 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007394 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007395 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7396 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007397 attributes = topClient->attributes();
7398 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007399 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007400 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007401 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7402 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007403 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007404 }
7405
Francois Gaffie716e1432019-01-14 16:58:59 +01007406 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7407 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007408 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007409 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007410 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007411 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007412
Eric Laurente552edb2014-03-10 17:42:56 -07007413 return device;
7414}
7415
Eric Laurent794fde22016-03-11 09:50:45 -08007416bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7417 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007418 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007419}
7420
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007421status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007422 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007423 if (devices == nullptr) {
7424 return BAD_VALUE;
7425 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007426
Andy Hung6d23c0f2022-02-16 09:37:15 -08007427 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007428 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7429 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007430 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007431 for (const auto& device : curDevices) {
7432 devices->push_back(device->getDeviceTypeAddr());
7433 }
7434 return NO_ERROR;
7435}
7436
Eric Laurente0720872014-03-11 09:30:41 -07007437void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007438 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007439 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007440 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007441 updateDevicesAndOutputs();
7442 break;
7443 default:
7444 break;
7445 }
7446}
7447
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007448uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007449
7450 // skip beacon mute management if a dedicated TTS output is available
7451 if (mTtsOutputAvailable) {
7452 return 0;
7453 }
7454
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007455 switch(event) {
7456 case STARTING_OUTPUT:
7457 mBeaconMuteRefCount++;
7458 break;
7459 case STOPPING_OUTPUT:
7460 if (mBeaconMuteRefCount > 0) {
7461 mBeaconMuteRefCount--;
7462 }
7463 break;
7464 case STARTING_BEACON:
7465 mBeaconPlayingRefCount++;
7466 break;
7467 case STOPPING_BEACON:
7468 if (mBeaconPlayingRefCount > 0) {
7469 mBeaconPlayingRefCount--;
7470 }
7471 break;
7472 }
7473
7474 if (mBeaconMuteRefCount > 0) {
7475 // any playback causes beacon to be muted
7476 return setBeaconMute(true);
7477 } else {
7478 // no other playback: unmute when beacon starts playing, mute when it stops
7479 return setBeaconMute(mBeaconPlayingRefCount == 0);
7480 }
7481}
7482
7483uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7484 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7485 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7486 // keep track of muted state to avoid repeating mute/unmute operations
7487 if (mBeaconMuted != mute) {
7488 // mute/unmute AUDIO_STREAM_TTS on all outputs
7489 ALOGV("\t muting %d", mute);
7490 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007491 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7492 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7493 ALOGV("\t no tts volume source available");
7494 return 0;
7495 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007496 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007497 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007498 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007499 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007500 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007501 maxLatency = latency;
7502 }
7503 }
7504 mBeaconMuted = mute;
7505 return maxLatency;
7506 }
7507 return 0;
7508}
7509
Eric Laurente0720872014-03-11 09:30:41 -07007510void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007511{
François Gaffiec005e562018-11-06 15:04:49 +01007512 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007513 mPreviousOutputs = mOutputs;
7514}
7515
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007516uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007517 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007518 uint32_t delayMs)
7519{
7520 // mute/unmute strategies using an incompatible device combination
7521 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7522 // if unmuting, unmute only after the specified delay
7523 if (outputDesc->isDuplicated()) {
7524 return 0;
7525 }
7526
7527 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007528 DeviceVector devices = outputDesc->devices();
7529 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007530
François Gaffiec005e562018-11-06 15:04:49 +01007531 auto productStrategies = mEngine->getOrderedProductStrategies();
7532 for (const auto &productStrategy : productStrategies) {
7533 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7534 DeviceVector curDevices =
7535 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7536 curDevices = curDevices.filter(outputDesc->supportedDevices());
7537 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007538 bool doMute = false;
7539
François Gaffiec005e562018-11-06 15:04:49 +01007540 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007541 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007542 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7543 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007544 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007545 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007546 }
Eric Laurent99401132014-05-07 19:48:15 -07007547 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007548 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007549 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007550 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007551 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007552 continue;
7553 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307554 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007555 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7556 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7557 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007558 if (mute) {
7559 // FIXME: should not need to double latency if volume could be applied
7560 // immediately by the audioflinger mixer. We must account for the delay
7561 // between now and the next time the audioflinger thread for this output
7562 // will process a buffer (which corresponds to one buffer size,
7563 // usually 1/2 or 1/4 of the latency).
7564 if (muteWaitMs < desc->latency() * 2) {
7565 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007566 }
7567 }
7568 }
7569 }
7570 }
7571 }
7572
Eric Laurent99401132014-05-07 19:48:15 -07007573 // temporary mute output if device selection changes to avoid volume bursts due to
7574 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007575 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007576 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007577
Eric Laurentdc462862016-07-19 12:29:53 -07007578 if (muteWaitMs < tempMuteWaitMs) {
7579 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007580 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007581
7582 // If recommended duration is defined, replace temporary mute duration to avoid
7583 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7584 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7585 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7586 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7587 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7588
François Gaffieaaac0fd2018-11-22 17:56:39 +01007589 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7590 // make sure that we do not start the temporary mute period too early in case of
7591 // delayed device change
7592 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7593 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007594 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007595 }
7596 }
7597
Eric Laurente552edb2014-03-10 17:42:56 -07007598 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7599 if (muteWaitMs > delayMs) {
7600 muteWaitMs -= delayMs;
7601 usleep(muteWaitMs * 1000);
7602 return muteWaitMs;
7603 }
7604 return 0;
7605}
7606
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307607uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7608 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007609 const DeviceVector &devices,
7610 bool force,
7611 int delayMs,
7612 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007613 bool requiresMuteCheck, bool requiresVolumeCheck,
7614 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007615{
jiabin3ff8d7d2022-12-13 06:27:44 +00007616 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307617 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7618 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7619 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007620 uint32_t muteWaitMs;
7621
7622 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307623 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007624 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307625 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007626 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007627 return muteWaitMs;
7628 }
Eric Laurente552edb2014-03-10 17:42:56 -07007629
7630 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007631 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007632 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007633 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007634
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307635 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7636 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007637
7638 if (!filteredDevices.isEmpty()) {
7639 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007640 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007641
7642 // if the outputs are not materially active, there is no need to mute.
7643 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007644 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007645 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307646 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7647 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007648 muteWaitMs = 0;
7649 }
Eric Laurente552edb2014-03-10 17:42:56 -07007650
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007651 bool outputRouted = outputDesc->isRouted();
7652
Eric Laurent79ea9582020-06-11 18:49:24 -07007653 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7654 // output profile or if new device is not supported AND previous device(s) is(are) still
7655 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007656 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307657 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7658 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007659 // restore previous device after evaluating strategy mute state
7660 outputDesc->setDevices(prevDevices);
7661 return muteWaitMs;
7662 }
7663
Eric Laurente552edb2014-03-10 17:42:56 -07007664 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007665 // the requested device is AUDIO_DEVICE_NONE
7666 // OR the requested device is the same as current device
7667 // AND force is not specified
7668 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007669 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007670 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307671 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7672 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7673 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007674 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307675 ALOGV("%s %s setting same device on routed output, force apply volumes",
7676 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007677 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7678 }
Eric Laurente552edb2014-03-10 17:42:56 -07007679 return muteWaitMs;
7680 }
7681
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307682 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7683 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007684
Eric Laurente552edb2014-03-10 17:42:56 -07007685 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007686 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007687 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007688 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007689 PatchBuilder patchBuilder;
7690 patchBuilder.addSource(outputDesc);
7691 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7692 for (const auto &filteredDevice : filteredDevices) {
7693 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007694 }
7695
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007696 // Add half reported latency to delayMs when muteWaitMs is null in order
7697 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007698 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7699 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7700 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007701 }
Eric Laurente552edb2014-03-10 17:42:56 -07007702
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007703 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7704 if (!skipMuteDelay) {
7705 // update stream volumes according to new device
7706 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7707 }
Eric Laurente552edb2014-03-10 17:42:56 -07007708
7709 return muteWaitMs;
7710}
7711
Eric Laurentc75307b2015-03-17 15:29:32 -07007712status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007713 int delayMs,
7714 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007715{
Eric Laurent6a94d692014-05-20 11:18:06 -07007716 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007717 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7718 return INVALID_OPERATION;
7719 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007720 if (patchHandle) {
7721 index = mAudioPatches.indexOfKey(*patchHandle);
7722 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007723 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007724 }
7725 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007726 return INVALID_OPERATION;
7727 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007728 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007729 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007730 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007731 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007732 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007733 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007734 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007735 return status;
7736}
7737
7738status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007739 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007740 bool force,
7741 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007742{
7743 status_t status = NO_ERROR;
7744
Eric Laurent1f2f2232014-06-02 12:01:23 -07007745 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007746 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7747 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007748
François Gaffie11d30102018-11-02 16:09:09 +01007749 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007750 PatchBuilder patchBuilder;
7751 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007752 // AUDIO_SOURCE_HOTWORD is for internal use only:
7753 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007754 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7755 auto result = usecase;
7756 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7757 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7758 }
7759 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007760 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007761 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007762 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007763 }
7764 }
7765 return status;
7766}
7767
Eric Laurent6a94d692014-05-20 11:18:06 -07007768status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7769 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007770{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007771 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007772 ssize_t index;
7773 if (patchHandle) {
7774 index = mAudioPatches.indexOfKey(*patchHandle);
7775 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007776 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007777 }
7778 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007779 return INVALID_OPERATION;
7780 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007781 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007782 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007783 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007784 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007785 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007786 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007787 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007788 return status;
7789}
7790
François Gaffie11d30102018-11-02 16:09:09 +01007791sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007792 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007793 audio_format_t& format,
7794 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007795 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007796{
7797 // Choose an input profile based on the requested capture parameters: select the first available
7798 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007799 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007800
Atneya Nair0f0a8032022-12-12 16:20:12 -08007801 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7802 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7803 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7804
7805 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007806
jiabin2fd710d2022-05-02 23:20:22 +00007807 for (;;) {
7808 sp<IOProfile> firstInexact = nullptr;
7809 uint32_t updatedSamplingRate = 0;
7810 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7811 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7812 for (const auto& hwModule : mHwModules) {
7813 for (const auto& profile : hwModule->getInputProfiles()) {
7814 // profile->log();
7815 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007816 if (profile->getCompatibilityScore(
7817 DeviceVector(device),
7818 samplingRate,
7819 &updatedSamplingRate,
7820 format,
7821 &updatedFormat,
7822 channelMask,
7823 &updatedChannelMask,
7824 // FIXME ugly cast
7825 (audio_output_flags_t) flags,
7826 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7827 samplingRate = updatedSamplingRate;
7828 format = updatedFormat;
7829 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007830 return profile;
7831 }
jiabin66acc432024-02-06 00:57:36 +00007832 if (firstInexact == nullptr
7833 && profile->getCompatibilityScore(
7834 DeviceVector(device),
7835 samplingRate,
7836 &updatedSamplingRate,
7837 format,
7838 &updatedFormat,
7839 channelMask,
7840 &updatedChannelMask,
7841 // FIXME ugly cast
7842 (audio_output_flags_t) flags,
7843 false /*exactMatchRequiredForInputFlags*/)
7844 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007845 firstInexact = profile;
7846 }
7847 }
7848 }
7849
7850 if (firstInexact != nullptr) {
7851 samplingRate = updatedSamplingRate;
7852 format = updatedFormat;
7853 channelMask = updatedChannelMask;
7854 return firstInexact;
7855 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7856 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7857 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7858 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7859 flags = AUDIO_INPUT_FLAG_NONE;
7860 } else { // fail
7861 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7862 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7863 samplingRate, format, channelMask, oriFlags);
7864 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007865 }
7866 }
jiabin2fd710d2022-05-02 23:20:22 +00007867
7868 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007869}
7870
François Gaffieaaac0fd2018-11-22 17:56:39 +01007871float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7872 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007873 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007874 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007875{
jiabin9a3361e2019-10-01 09:38:30 -07007876 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007877
7878 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7879 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7880 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7881 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007882 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7883 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7884 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7885 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7886 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007887 // Verify that the current volume source is not the ringer volume to prevent recursively
7888 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7889 // to the same volume group.
7890 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007891 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7892 mOutputs.isActive(ringVolumeSrc, 0)) {
7893 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007894 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007895 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007896 }
7897
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007898 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007899 if ((volumeSource != callVolumeSrc && (isInCall() ||
7900 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007901 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007902 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7903 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007904 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7905 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7906 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007907 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007908 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007909 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007910 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007911 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007912 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007913 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7914 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7915 // programmatically muted.
7916 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7917 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7918 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007919 bool exemptFromCapping =
7920 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7921 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007922 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7923 volumeSource, volumeDb);
7924 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007925 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7926 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7927 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007928 }
7929 }
Eric Laurente552edb2014-03-10 17:42:56 -07007930 // if a headset is connected, apply the following rules to ring tones and notifications
7931 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007932 // - always attenuate notifications volume by 6dB
7933 // - attenuate ring tones volume by 6dB unless music is not playing and
7934 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007935 // - if music is playing, always limit the volume to current music volume,
7936 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007937 if (!Intersection(deviceTypes,
7938 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7939 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007940 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7941 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007942 ((volumeSource == alarmVolumeSrc ||
7943 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007944 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7945 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7946 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007947 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7948 curves.canBeMuted()) {
7949
Eric Laurente552edb2014-03-10 17:42:56 -07007950 // when the phone is ringing we must consider that music could have been paused just before
7951 // by the music application and behave as if music was active if the last music track was
7952 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07007953 // Verify that the current volume source is not the music volume to prevent recursively
7954 // calling to compute volume. This could happen in cases where music and
7955 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7956 if (volumeSource != musicVolumeSrc &&
7957 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7958 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007959 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007960 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007961 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7962 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007963 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007964 float musicVolDb = computeVolume(musicCurves,
7965 musicVolumeSrc,
7966 musicCurves.getVolumeIndex(musicDevice),
7967 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007968 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7969 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7970 if (volumeDb > minVolDb) {
7971 volumeDb = minVolDb;
7972 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007973 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007974 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7975 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08007976 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7977 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
7978 // on A2DP/BLE, also ensure notification volume is not too low compared to media
7979 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01007980 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007981 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007982 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7983 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007984 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7985 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007986 }
7987 }
jiabin9a3361e2019-10-01 09:38:30 -07007988 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007989 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007990 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007991 }
7992 }
7993
François Gaffie43c73442018-11-08 08:21:55 +01007994 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007995}
7996
Eric Laurent3839bc02018-07-10 18:33:34 -07007997int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007998 VolumeSource fromVolumeSource,
7999 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008000{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008001 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008002 return srcIndex;
8003 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008004 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8005 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008006 float minSrc = (float)srcCurves.getVolumeIndexMin();
8007 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8008 float minDst = (float)dstCurves.getVolumeIndexMin();
8009 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008010
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008011 // preserve mute request or correct range
8012 if (srcIndex < minSrc) {
8013 if (srcIndex == 0) {
8014 return 0;
8015 }
8016 srcIndex = minSrc;
8017 } else if (srcIndex > maxSrc) {
8018 srcIndex = maxSrc;
8019 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008020 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8021}
8022
François Gaffieaaac0fd2018-11-22 17:56:39 +01008023status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8024 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008025 int index,
8026 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008027 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008028 int delayMs,
8029 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008030{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008031 // do not change actual attributes volume if the attributes is muted
8032 if (outputDesc->isMuted(volumeSource)) {
8033 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8034 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008035 return NO_ERROR;
8036 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008037
Eric Laurent5baf07c2024-01-11 16:57:27 +00008038 bool isVoiceVolSrc;
8039 bool isBtScoVolSrc;
8040 if (!isVolumeConsistentForCalls(
8041 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008042 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008043 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008044 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008045 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008046
jiabin9a3361e2019-10-01 09:38:30 -07008047 if (deviceTypes.empty()) {
8048 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008049 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008050 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008051 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008052 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008053
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008054 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8055 ALOGE("invalid volume index range");
8056 return BAD_VALUE;
8057 }
8058
jiabin9a3361e2019-10-01 09:38:30 -07008059 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8060 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008061 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008062 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008063 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8064 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008065 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008066 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008067 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008068 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8069 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008070
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008071 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008072 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8073 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8074 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008075 }
Eric Laurente552edb2014-03-10 17:42:56 -07008076 return NO_ERROR;
8077}
8078
Eric Laurent5baf07c2024-01-11 16:57:27 +00008079void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008080 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008081 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008082 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008083 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008084 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008085 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8086 } else {
8087 voiceVolume = index == 0 ? 0.0 : 1.0;
8088 }
8089 if (voiceVolume != mLastVoiceVolume) {
8090 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8091 mLastVoiceVolume = voiceVolume;
8092 }
8093}
8094
8095bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8096 const DeviceTypeSet& deviceTypes,
8097 bool& isVoiceVolSrc,
8098 bool& isBtScoVolSrc,
8099 const char* caller) {
8100 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8101 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8102 const bool isScoRequested = isScoRequestedForComm();
8103 const bool isHAUsed = isHearingAidUsedForComm();
8104
8105 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8106 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8107
8108 if ((callVolSrc != btScoVolSrc) &&
8109 ((isVoiceVolSrc && isScoRequested) ||
8110 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8111 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8112 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8113 volumeSource, isScoRequested ? " " : " not ");
8114 return false;
8115 }
8116 return true;
8117}
8118
Eric Laurentc75307b2015-03-17 15:29:32 -07008119void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008120 const DeviceTypeSet& deviceTypes,
8121 int delayMs,
8122 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008123{
jiabincd510522020-01-22 09:40:55 -08008124 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008125 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8126 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8127 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008128 curves.getVolumeIndex(deviceTypes),
8129 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008130 }
8131}
8132
François Gaffiec005e562018-11-06 15:04:49 +01008133void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8134 bool on,
8135 const sp<AudioOutputDescriptor>& outputDesc,
8136 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008137 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008138{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008139 std::vector<VolumeSource> sourcesToMute;
8140 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8141 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8142 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008143 VolumeSource source = toVolumeSource(attributes, false);
8144 if ((source != VOLUME_SOURCE_NONE) &&
8145 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8146 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008147 sourcesToMute.push_back(source);
8148 }
Eric Laurente552edb2014-03-10 17:42:56 -07008149 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008150 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008151 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008152 }
8153
Eric Laurente552edb2014-03-10 17:42:56 -07008154}
8155
François Gaffieaaac0fd2018-11-22 17:56:39 +01008156void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8157 bool on,
8158 const sp<AudioOutputDescriptor>& outputDesc,
8159 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008160 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008161{
jiabin9a3361e2019-10-01 09:38:30 -07008162 if (deviceTypes.empty()) {
8163 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008164 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008165 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008166 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008167 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008168 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008169 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008170 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8171 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008172 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008173 }
8174 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008175 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8176 // ignored
8177 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008178 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008179 if (!outputDesc->isMuted(volumeSource)) {
8180 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008181 return;
8182 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008183 if (outputDesc->decMuteCount(volumeSource) == 0) {
8184 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008185 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008186 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008187 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008188 delayMs);
8189 }
8190 }
8191}
8192
François Gaffie53615e22015-03-19 09:24:12 +01008193bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8194{
François Gaffiec005e562018-11-06 15:04:49 +01008195 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008196 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8197 return true;
8198 }
8199
8200 // has known usage?
8201 switch (paa->usage) {
8202 case AUDIO_USAGE_UNKNOWN:
8203 case AUDIO_USAGE_MEDIA:
8204 case AUDIO_USAGE_VOICE_COMMUNICATION:
8205 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8206 case AUDIO_USAGE_ALARM:
8207 case AUDIO_USAGE_NOTIFICATION:
8208 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8209 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8210 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8211 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8212 case AUDIO_USAGE_NOTIFICATION_EVENT:
8213 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8214 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8215 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8216 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008217 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008218 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008219 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008220 case AUDIO_USAGE_EMERGENCY:
8221 case AUDIO_USAGE_SAFETY:
8222 case AUDIO_USAGE_VEHICLE_STATUS:
8223 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008224 break;
8225 default:
8226 return false;
8227 }
8228 return true;
8229}
8230
François Gaffie2110e042015-03-24 08:41:51 +01008231audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8232{
8233 return mEngine->getForceUse(usage);
8234}
8235
Eric Laurent96d1dda2022-03-14 17:14:19 +01008236bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008237 return isStateInCall(mEngine->getPhoneState());
8238}
8239
Eric Laurent96d1dda2022-03-14 17:14:19 +01008240bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008241 return is_state_in_call(state);
8242}
8243
Eric Laurentf9cccec2022-11-16 19:12:00 +01008244bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008245 audio_mode_t mode = mEngine->getPhoneState();
8246 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008247 || (mode == AUDIO_MODE_CALL_SCREEN)
8248 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008249}
8250
Eric Laurentf9cccec2022-11-16 19:12:00 +01008251bool AudioPolicyManager::isInCallOrScreening() const {
8252 audio_mode_t mode = mEngine->getPhoneState();
8253 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8254}
8255
Eric Laurentd60560a2015-04-10 11:31:20 -07008256void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8257{
8258 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008259 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008260 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008261 sourceDesc->sinkDevice()->equals(deviceDesc))
8262 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008263 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008264 }
8265 }
8266
8267 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8268 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8269 bool release = false;
8270 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8271 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8272 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8273 source->ext.device.type == deviceDesc->type()) {
8274 release = true;
8275 }
8276 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008277 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008278 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8279 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8280 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008281 sink->ext.device.type == deviceDesc->type() &&
8282 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8283 || strncmp(sink->ext.device.address, address,
8284 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008285 release = true;
8286 }
8287 }
8288 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008289 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8290 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008291 }
8292 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008293
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008294 mInputs.clearSessionRoutesForDevice(deviceDesc);
8295
Francois Gaffie716e1432019-01-14 16:58:59 +01008296 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008297}
8298
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008299void AudioPolicyManager::modifySurroundFormats(
8300 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008301 std::unordered_set<audio_format_t> enforcedSurround(
8302 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008303 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008304 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008305 allSurround.insert(pair.first);
8306 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8307 }
Phil Burk09bc4612016-02-24 15:58:15 -08008308
8309 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8310 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008311 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008312 // This is the resulting set of formats depending on the surround mode:
8313 // 'all surround' = allSurround
8314 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8315 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8316 // 'manual surround' = mManualSurroundFormats
8317 // AUTO: formats v 'enforced surround'
8318 // ALWAYS: formats v 'all surround' v 'enforced surround'
8319 // NEVER: formats ^ 'non-surround'
8320 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008321
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008322 std::unordered_set<audio_format_t> formatSet;
8323 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8324 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008325 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008326 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008327 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008328 formatSet.insert(*formatIter);
8329 }
8330 }
8331 } else {
8332 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8333 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008334 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008335
jiabin81772902018-04-02 17:52:27 -07008336 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008337 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008338 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8339 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8340 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008341 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008342 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8343 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8344 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008345 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008346 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008347 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008348 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008349 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008350 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008351}
8352
jiabin06e4bab2019-07-29 10:13:34 -07008353void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8354 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008355 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8356 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8357
8358 // If NEVER, then remove support for channelMasks > stereo.
8359 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008360 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8361 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008362 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008363 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008364 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008365 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008366 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008367 }
8368 }
jiabin81772902018-04-02 17:52:27 -07008369 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8370 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8371 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008372 bool supports5dot1 = false;
8373 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008374 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008375 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8376 supports5dot1 = true;
8377 break;
8378 }
8379 }
8380 // If not then add 5.1 support.
8381 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008382 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008383 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008384 }
Phil Burk09bc4612016-02-24 15:58:15 -08008385 }
8386}
8387
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008388void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008389 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008390 const sp<IOProfile>& profile) {
8391 if (!profile->hasDynamicAudioProfile()) {
8392 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008393 }
François Gaffie112b0af2015-11-19 16:13:25 +01008394
jiabin12537fc2023-10-12 17:56:08 +00008395 audio_port_v7 devicePort;
8396 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008397
jiabin12537fc2023-10-12 17:56:08 +00008398 audio_port_v7 mixPort;
8399 profile->toAudioPort(&mixPort);
8400 mixPort.ext.mix.handle = ioHandle;
8401
8402 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8403 if (status != NO_ERROR) {
8404 ALOGE("%s failed to query the attributes of the mix port", __func__);
8405 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008406 }
jiabin12537fc2023-10-12 17:56:08 +00008407
8408 std::set<audio_format_t> supportedFormats;
8409 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8410 supportedFormats.insert(mixPort.audio_profiles[i].format);
8411 }
8412 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8413 mReportedFormatsMap[devDesc] = formats;
8414
8415 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8416 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8417 modifySurroundFormats(devDesc, &formats);
8418 size_t modifiedNumProfiles = 0;
8419 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8420 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8421 formats.end()) {
8422 // Skip the format that is not present after modifying surround formats.
8423 continue;
8424 }
8425 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8426 sizeof(struct audio_profile));
8427 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8428 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8429 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8430 modifySurroundChannelMasks(&channels);
8431 std::copy(channels.begin(), channels.end(),
8432 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8433 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8434 }
8435 mixPort.num_audio_profiles = modifiedNumProfiles;
8436 }
8437 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008438}
Eric Laurentd60560a2015-04-10 11:31:20 -07008439
Mikhail Naganovdc769682018-05-04 15:34:08 -07008440status_t AudioPolicyManager::installPatch(const char *caller,
8441 audio_patch_handle_t *patchHandle,
8442 AudioIODescriptorInterface *ioDescriptor,
8443 const struct audio_patch *patch,
8444 int delayMs)
8445{
8446 ssize_t index = mAudioPatches.indexOfKey(
8447 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8448 *patchHandle : ioDescriptor->getPatchHandle());
8449 sp<AudioPatch> patchDesc;
8450 status_t status = installPatch(
8451 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8452 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008453 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008454 }
8455 return status;
8456}
8457
8458status_t AudioPolicyManager::installPatch(const char *caller,
8459 ssize_t index,
8460 audio_patch_handle_t *patchHandle,
8461 const struct audio_patch *patch,
8462 int delayMs,
8463 uid_t uid,
8464 sp<AudioPatch> *patchDescPtr)
8465{
8466 sp<AudioPatch> patchDesc;
8467 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8468 if (index >= 0) {
8469 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008470 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008471 }
8472
8473 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8474 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8475 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8476 if (status == NO_ERROR) {
8477 if (index < 0) {
8478 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008479 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008480 } else {
8481 patchDesc->mPatch = *patch;
8482 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008483 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008484 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008485 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008486 }
8487 nextAudioPortGeneration();
8488 mpClientInterface->onAudioPatchListUpdate();
8489 }
8490 if (patchDescPtr) *patchDescPtr = patchDesc;
8491 return status;
8492}
8493
jiabinbce0c1d2020-10-05 11:20:18 -07008494bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8495{
8496 const TrackClientVector activeClients = output->getActiveClients();
8497 if (activeClients.empty()) {
8498 return true;
8499 }
8500 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8501 if (index < 0) {
8502 ALOGE("%s, no audio patch found while there are active clients on output %d",
8503 __func__, output->getId());
8504 return false;
8505 }
8506 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8507 DeviceVector routedDevices;
8508 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8509 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8510 patchDesc->mPatch.sinks[i].id);
8511 if (device == nullptr) {
8512 ALOGE("%s, no audio device found with id(%d)",
8513 __func__, patchDesc->mPatch.sinks[i].id);
8514 return false;
8515 }
8516 routedDevices.add(device);
8517 }
8518 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008519 if (client->isInvalid()) {
8520 // No need to take care about invalidated clients.
8521 continue;
8522 }
jiabinbce0c1d2020-10-05 11:20:18 -07008523 sp<DeviceDescriptor> preferredDevice =
8524 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8525 if (mEngine->getOutputDevicesForAttributes(
8526 client->attributes(), preferredDevice, false) == routedDevices) {
8527 return false;
8528 }
8529 }
8530 return true;
8531}
8532
8533sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008534 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008535 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8536 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008537{
8538 for (const auto& device : devices) {
8539 // TODO: This should be checking if the profile supports the device combo.
8540 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008541 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8542 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008543 return nullptr;
8544 }
8545 }
8546 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8547 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008548 status_t status = desc->open(halConfig, mixerConfig, devices,
8549 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008550 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008551 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008552 return nullptr;
8553 }
jiabin14b50cc2023-12-13 19:01:52 +00008554 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8555 auto portConfig = desc->getConfig();
8556 for (const auto& device : devices) {
8557 device->setPreferredConfig(&portConfig);
8558 }
8559 }
jiabinbce0c1d2020-10-05 11:20:18 -07008560
8561 // Here is where the out_set_parameters() for card & device gets called
8562 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8563 const audio_devices_t deviceType = device->type();
8564 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008565 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008566 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8567 mpClientInterface->setParameters(output, String8(param));
8568 free(param);
8569 }
jiabin12537fc2023-10-12 17:56:08 +00008570 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008571 if (!profile->hasValidAudioProfile()) {
8572 ALOGW("%s() missing param", __func__);
8573 desc->close();
8574 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008575 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8576 // Reopen the output with the best audio profile picked by APM when the profile supports
8577 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008578 desc->close();
8579 output = AUDIO_IO_HANDLE_NONE;
8580 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8581 profile->pickAudioProfile(
8582 config.sample_rate, config.channel_mask, config.format);
8583 config.offload_info.sample_rate = config.sample_rate;
8584 config.offload_info.channel_mask = config.channel_mask;
8585 config.offload_info.format = config.format;
8586
jiabina84c3d32022-12-02 18:59:55 +00008587 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008588 if (status != NO_ERROR) {
8589 return nullptr;
8590 }
8591 }
8592
8593 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008594
baek.kim -61c20122022-07-27 10:05:32 +00008595 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8596 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8597
jiabinbce0c1d2020-10-05 11:20:18 -07008598 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8599 sp<AudioPolicyMix> policyMix;
8600 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8601 policyMix->setOutput(desc);
8602 desc->mPolicyMix = policyMix;
8603 } else {
8604 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008605 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008606 }
8607
baek.kim -61c20122022-07-27 10:05:32 +00008608 } else if (hasPrimaryOutput() && speaker != nullptr
8609 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008610 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8611 // no duplicated output for:
8612 // - direct outputs
8613 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008614 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008615 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8616
8617 //TODO: configure audio effect output stage here
8618
8619 // open a duplicating output thread for the new output and the primary output
8620 sp<SwAudioOutputDescriptor> dupOutputDesc =
8621 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8622 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8623 if (status == NO_ERROR) {
8624 // add duplicated output descriptor
8625 addOutput(duplicatedOutput, dupOutputDesc);
8626 } else {
8627 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8628 mPrimaryOutput->mIoHandle, output);
8629 desc->close();
8630 removeOutput(output);
8631 nextAudioPortGeneration();
8632 return nullptr;
8633 }
8634 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008635 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8636 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8637 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008638 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008639 }
jiabinbce0c1d2020-10-05 11:20:18 -07008640 return desc;
8641}
8642
jiabinf1c73972022-04-14 16:28:52 -07008643status_t AudioPolicyManager::getDevicesForAttributes(
8644 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8645 // Devices are determined in the following precedence:
8646 //
8647 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8648 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8649 //
8650 // If no such dynamic policy then
8651 // 2) Devices containing an active client using setPreferredDevice
8652 // with same strategy as the attributes.
8653 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8654 //
8655 // If no corresponding active client with setPreferredDevice then
8656 // 3) Devices associated with the strategy determined by the attributes
8657 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8658 //
8659 // See related getOutputForAttrInt().
8660
8661 // check dynamic policies but only for primary descriptors (secondary not used for audible
8662 // audio routing, only used for duplication for playback capture)
8663 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008664 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008665 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008666 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8667 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8668 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008669 if (status != OK) {
8670 return status;
8671 }
8672
8673 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8674 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8675 // as they are unaffected by device/stream volume
8676 // (per SwAudioOutputDescriptor::isFixedVolume()).
8677 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8678 ) {
8679 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8680 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8681 devices.add(deviceDesc);
8682 } else {
8683 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8684 // which selects setPreferredDevice if active. This means forVolume call
8685 // will take an active setPreferredDevice, if such exists.
8686
8687 devices = mEngine->getOutputDevicesForAttributes(
8688 attr, nullptr /* preferredDevice */, false /* fromCache */);
8689 }
8690
8691 if (forVolume) {
8692 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8693 // for single volume control in AudioService (such relationship should exist if
8694 // SPEAKER_SAFE is present).
8695 //
8696 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8697 DeviceVector speakerSafeDevices =
8698 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8699 if (!speakerSafeDevices.isEmpty()) {
8700 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8701 devices.remove(speakerSafeDevices);
8702 }
8703 }
8704
8705 return NO_ERROR;
8706}
8707
8708status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8709 AudioProfileVector& audioProfiles,
8710 uint32_t flags,
8711 bool isInput) {
8712 for (const auto& hwModule : mHwModules) {
8713 // the MSD module checks for different conditions
8714 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8715 continue;
8716 }
8717 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8718 : hwModule->getOutputProfiles();
8719 for (const auto& profile : ioProfiles) {
8720 if (!profile->areAllDevicesSupported(devices) ||
8721 !profile->isCompatibleProfileForFlags(
8722 flags, false /*exactMatchRequiredForInputFlags*/)) {
8723 continue;
8724 }
8725 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8726 }
8727 }
8728
8729 if (!isInput) {
8730 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8731 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8732 if (msdModule != nullptr) {
8733 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8734 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8735 for (const auto &profile: msdModule->getOutputProfiles()) {
8736 if (!profile->asAudioPort()->isDirectOutput()) {
8737 continue;
8738 }
8739 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8740 }
8741 } else {
8742 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8743 }
8744 }
8745 }
8746
8747 return NO_ERROR;
8748}
8749
jiabin3ff8d7d2022-12-13 06:27:44 +00008750sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8751 const audio_config_t *config,
8752 audio_output_flags_t flags,
8753 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008754 closeOutput(outputDesc->mIoHandle);
8755 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8756 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8757 if (preferredOutput == nullptr) {
8758 ALOGE("%s failed to reopen output device=%d, caller=%s",
8759 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008760 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008761 return preferredOutput;
8762}
8763
8764void AudioPolicyManager::reopenOutputsWithDevices(
8765 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8766 for (const auto& [output, devices] : outputsToReopen) {
8767 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8768 closeOutput(output);
8769 openOutputWithProfileAndDevice(desc->mProfile, devices);
8770 }
jiabina84c3d32022-12-02 18:59:55 +00008771}
8772
jiabinc44b3462022-12-08 12:52:31 -08008773PortHandleVector AudioPolicyManager::getClientsForStream(
8774 audio_stream_type_t streamType) const {
8775 PortHandleVector clients;
8776 for (size_t i = 0; i < mOutputs.size(); ++i) {
8777 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8778 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8779 }
8780 return clients;
8781}
8782
8783void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8784 PortHandleVector clients;
8785 for (auto stream : streams) {
8786 PortHandleVector clientsForStream = getClientsForStream(stream);
8787 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8788 }
8789 mpClientInterface->invalidateTracks(clients);
8790}
8791
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008792} // namespace android