blob: 27614801baea9f97e2a91fedbb14fe4778f397b7 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Andy Hungf7786a42024-02-08 21:19:47 -0800132 ALOGE("Error %d while setting connected state for device %s",
133 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
Francois Gaffie716e1432019-01-14 16:58:59 +0100221 mHwModules.cleanUpForDevice(device);
222
jiabinc0048632023-04-27 22:04:31 +0000223 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000341 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
342 // If the device is using preferred mixer attributes, the output need to reopen
343 // with default configuration when the new selected devices are different from
344 // current routing devices
345 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
346 continue;
347 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530348 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700349 }
jiabinbce0c1d2020-10-05 11:20:18 -0700350 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000351 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700352 desc->supportsDevicesForPlayback(activeMediaDevices)) {
353 // Reopen the output to query the dynamic profiles when there is not active
354 // clients or all active clients will be rerouted. Otherwise, set the flag
355 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
356 // can be reopened to query dynamic profiles when all clients are inactive.
357 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000358 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700359 } else {
360 desc->mPendingReopenToQueryProfiles = true;
361 }
362 }
363 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
364 // Clear the flag that previously set for re-querying profiles.
365 desc->mPendingReopenToQueryProfiles = false;
366 }
367 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000368 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700369
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100371 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700372 }
373
Eric Laurent96d1dda2022-03-14 17:14:19 +0100374 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
375
Eric Laurent72aa32f2014-05-30 18:51:48 -0700376 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200399
Eric Laurent0dd51852019-04-19 18:18:58 -0700400 if (checkInputsForDevice(device, state) != NO_ERROR) {
401 mAvailableInputDevices.remove(device);
402
jiabinc0048632023-04-27 22:04:31 +0000403 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100404
405 mHwModules.cleanUpForDevice(device);
406
Eric Laurentd4692962014-05-05 18:13:44 -0700407 return INVALID_OPERATION;
408 }
409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700414 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return INVALID_OPERATION;
417 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
jiabinc0048632023-04-27 22:04:31 +0000421 // Notify the HAL to prepare to disconnect device
422 broadcastDeviceConnectionState(
423 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
François Gaffie11d30102018-11-02 16:09:09 +0100425 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700426
427 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428
jiabinc0048632023-04-27 22:04:31 +0000429 // Set Disconnect to HALs
430 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
431
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432 // remove device from mReportedFormatsMap cache
433 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700435
436 default:
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return BAD_VALUE;
439 }
440
Eric Laurent736a1022019-03-27 18:28:46 -0700441 // Propagate device availability to Engine
442 setEngineDeviceConnectionState(device, state);
443
Eric Laurent0dd51852019-04-19 18:18:58 -0700444 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700445 // As the input device list can impact the output device selection, update
446 // getDeviceForStrategy() cache
447 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700448
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100449 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200450 // Reconnect Audio Source
451 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
452 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
453 checkAudioSourceForAttributes(attributes);
454 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100456 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700457 }
458
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700461 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700462
François Gaffie11d30102018-11-02 16:09:09 +0100463 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return BAD_VALUE;
465}
466
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
468 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800469 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700470 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
471 devDescr->setName(device_name);
472 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100473}
474
Eric Laurent736a1022019-03-27 18:28:46 -0700475void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
476 audio_policy_dev_state_t state) {
477
478 // the Engine does not have to know about remote submix devices used by dynamic audio policies
479 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
480 return;
481 }
482 mEngine->setDeviceConnectionState(device, state);
483}
484
485
Eric Laurente0720872014-03-11 09:30:41 -0700486audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100487 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700488{
Eric Laurent634b7142016-04-20 13:48:02 -0700489 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
491 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700492 (strlen(device_address) != 0)/*matchAddress*/);
493
494 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100495 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700496 device, device_address);
497 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
498 }
François Gaffie53615e22015-03-19 09:24:12 +0100499
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 DeviceVector *deviceVector;
501
Eric Laurente552edb2014-03-10 17:42:56 -0700502 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 deviceVector = &mAvailableInputDevices;
506 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100507 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 }
Eric Laurent634b7142016-04-20 13:48:02 -0700510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 return (deviceVector->getDevice(
512 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800514}
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
517 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 const char *device_name,
519 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
522 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800524 // connect/disconnect only 1 device at a time
525 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
526
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700528 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530 // Nothing to do: device is not connected
531 return NO_ERROR;
532 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700535 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800536 // configure codecs.
537 // Handle two specific cases by sending a set parameter to
538 // configure A2DP codecs. No need to toggle device state.
539 // Case 1: A2DP active device switches from primary to primary
540 // module
541 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700543 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
545 if (availablePrimaryOutputDevices().contains(devDesc) &&
546 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 bool isA2dp = audio_is_a2dp_out_device(device);
548 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
549 : String8(AudioParameter::keyReconfigLeSupported);
550 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 int isReconfigSupported;
553 repliedParameters.getInt(supportKey, isReconfigSupported);
554 if (isReconfigSupported) {
555 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
556 : String8(AudioParameter::keyReconfigLe);
557 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 param.add(key, String8("true"));
559 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
560 devDesc->setEncodedFormat(encodedFormat);
561 return NO_ERROR;
562 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700563 }
564 }
cnx421bd2dcc42020-07-11 14:58:44 +0800565 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
566 for (size_t i = 0; i < mOutputs.size(); i++) {
567 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
568 // mute media strategies and delay device switch by the largest
569 // This avoid sending the music tail into the earpiece or headset.
570 setStrategyMute(musicStrategy, true, desc);
571 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
572 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
573 nullptr, true /*fromCache*/).types());
574 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 // Toggle the device state: UNAVAILABLE -> AVAILABLE
576 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100577 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800578 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 device_address, device_name,
580 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800581 if (status != NO_ERROR) {
582 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
583 status);
584 return status;
585 }
586
587 status = setDeviceConnectionState(device,
588 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800589 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800590 if (status != NO_ERROR) {
591 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
592 status);
593 return status;
594 }
595
596 return NO_ERROR;
597}
598
Pattydd807582021-11-04 21:01:03 +0800599status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
600 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800601{
Pattydd807582021-11-04 21:01:03 +0800602 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800603 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800604 std::unordered_set<audio_format_t> formatSet;
605 sp<HwModule> primaryModule =
606 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700607 if (primaryModule == nullptr) {
608 ALOGE("%s() unable to get primary module", __func__);
609 return NO_INIT;
610 }
Pattydd807582021-11-04 21:01:03 +0800611
612 DeviceTypeSet audioDeviceSet;
613
614 switch(device) {
615 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
616 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
617 break;
618 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800619 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
620 break;
621 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
622 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800623 break;
624 default:
625 ALOGE("%s() device type 0x%08x not supported", __func__, device);
626 return BAD_VALUE;
627 }
628
jiabin9a3361e2019-10-01 09:38:30 -0700629 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800630 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800631 for (const auto& device : declaredDevices) {
632 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800633 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800634 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800635 return status;
636}
637
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100638DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
639{
640 DeviceVector rxSinkdevices{};
641 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
642 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
643 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
644 auto rxSinkDevice = rxSinkdevices.itemAt(0);
645 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
646 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
647 // retrieve Rx Source device descriptor
648 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
649 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
650
651 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
652 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
653 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
654 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
655 return DeviceVector(rxSinkDevice);
656 }
657 }
658 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
659 // the device returned is not necessarily reachable via this output
660 // (filter later by setOutputDevices())
661 return getNewOutputDevices(mPrimaryOutput, fromCache);
662}
663
664status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
665{
François Gaffiedb1755b2023-09-01 11:50:35 +0200666 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
668 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
669 }
670 return INVALID_OPERATION;
671}
672
673status_t AudioPolicyManager::updateCallRoutingInternal(
674 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700675{
676 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100677 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700678 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200679 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700680 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700682 }
François Gaffie11d30102018-11-02 16:09:09 +0100683
Francois Gaffie716e1432019-01-14 16:58:59 +0100684 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100685 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200686
687 disconnectTelephonyAudioSource(mCallRxSourceClient);
688 disconnectTelephonyAudioSource(mCallTxSourceClient);
689
690 if (rxDevices.isEmpty()) {
691 ALOGW("%s() no selected output device", __func__);
692 return INVALID_OPERATION;
693 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000694 if (txSourceDevice == nullptr) {
695 ALOGE("%s() selected input device not available", __func__);
696 return INVALID_OPERATION;
697 }
François Gaffiec005e562018-11-06 15:04:49 +0100698
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100699 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100700 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700701
François Gaffie9eb18552018-11-05 10:33:26 +0100702 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700703 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100704 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700705 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100706 // retrieve Rx Source and Tx Sink device descriptors
707 sp<DeviceDescriptor> rxSourceDevice =
708 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
709 String8(),
710 AUDIO_FORMAT_DEFAULT);
711 sp<DeviceDescriptor> txSinkDevice =
712 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
713 String8(),
714 AUDIO_FORMAT_DEFAULT);
715
716 // RX and TX Telephony device are declared by Primary Audio HAL
717 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
718 (telephonyRxModule->getHalVersionMajor() >= 3)) {
719 if (rxSourceDevice == 0 || txSinkDevice == 0) {
720 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100721 ALOGE("%s() no telephony Tx and/or RX device", __func__);
722 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100723 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100724 // createAudioPatchInternal now supports both HW / SW bridging
725 createRxPatch = true;
726 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100727 } else {
728 // If the RX device is on the primary HW module, then use legacy routing method for
729 // voice calls via setOutputDevice() on primary output.
730 // Otherwise, create two audio patches for TX and RX path.
731 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
732 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733 // If the TX device is also on the primary HW module, setOutputDevice() will take care
734 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100735 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
736 (txSinkDevice != 0);
737 }
738 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
739 // Otherwise, create two audio patches for TX and RX path.
740 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200741 if (!hasPrimaryOutput()) {
742 ALOGW("%s() no primary output available", __func__);
743 return INVALID_OPERATION;
744 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530745 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700746 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200747 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800748 // If the TX device is on the primary HW module but RX device is
749 // on other HW module, SinkMetaData of telephony input should handle it
750 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700751 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700752 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100753 // terminate active capture if on the same HW module as the call TX source device
754 // FIXME: would be better to refine to only inputs whose profile connects to the
755 // call TX device but this information is not in the audio patch and logic here must be
756 // symmetric to the one in startInput()
757 for (const auto& activeDesc : mInputs.getActiveInputs()) {
758 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
759 closeActiveClients(activeDesc);
760 }
761 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200762 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100764 if (waitMs != nullptr) {
765 *waitMs = muteWaitMs;
766 }
767 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800768}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700769
Mikhail Naganov100f0122018-11-29 11:22:16 -0800770bool AudioPolicyManager::isDeviceOfModule(
771 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
772 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
773 if (module != 0) {
774 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
775 .indexOf(devDesc) != NAME_NOT_FOUND
776 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
777 .indexOf(devDesc) != NAME_NOT_FOUND;
778 }
779 return false;
780}
781
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200782void AudioPolicyManager::connectTelephonyRxAudioSource()
783{
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200785 const struct audio_port_config source = {
786 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
787 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
788 };
789 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100790
791 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
792 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
793 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
794 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 ALOGE_IF(mCallRxSourceClient == nullptr,
796 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200797}
798
Francois Gaffie601801d2021-06-22 13:27:39 +0200799void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200800{
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 if (clientDesc == nullptr) {
802 return;
803 }
804 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
805 "%s error stopping audio source", __func__);
806 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807}
808
809void AudioPolicyManager::connectTelephonyTxAudioSource(
810 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
811 uint32_t delayMs)
812{
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200814 if (srcDevice == nullptr || sinkDevice == nullptr) {
815 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
816 return;
817 }
818 PatchBuilder patchBuilder;
819 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
820 ALOGV("%s between source %s and sink %s", __func__,
821 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200822 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200823 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
824
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 struct audio_port_config source = {};
826 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100827 mCallTxSourceClient = new SourceClientDescriptor(
828 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
829 mCommunnicationStrategy, toVolumeSource(aa), true);
830 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
831
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200832 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
833 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200834 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
835 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200836 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
837 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200839 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200840}
841
Eric Laurente0720872014-03-11 09:30:41 -0700842void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700843{
844 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100845 // store previous phone state for management of sonification strategy below
846 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100847 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100848
849 if (mEngine->setPhoneState(state) != NO_ERROR) {
850 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700851 return;
852 }
François Gaffie2110e042015-03-24 08:41:51 +0100853 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700854 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700855 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700856 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800857 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
859
François Gaffie2110e042015-03-24 08:41:51 +0100860 /**
861 * Switching to or from incall state or switching between telephony and VoIP lead to force
862 * routing command.
863 */
Eric Laurent74b71512019-11-06 17:21:57 -0800864 bool force = ((isStateInCall(oldState) != isStateInCall(state))
865 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700866
867 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700868 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700869
Eric Laurente552edb2014-03-10 17:42:56 -0700870 int delayMs = 0;
871 if (isStateInCall(state)) {
872 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100873 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
874 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700875 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700877 // mute media and sonification strategies and delay device switch by the largest
878 // latency of any output where either strategy is active.
879 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100880 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
881 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
882 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700883 (delayMs < (int)desc->latency()*2)) {
884 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700885 }
François Gaffiec005e562018-11-06 15:04:49 +0100886 setStrategyMute(musicStrategy, true, desc);
887 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
888 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
889 nullptr, true /*fromCache*/).types());
890 setStrategyMute(sonificationStrategy, true, desc);
891 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
892 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
893 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700894 }
895 }
896
François Gaffiedb1755b2023-09-01 11:50:35 +0200897 if (state == AUDIO_MODE_IN_CALL) {
898 (void)updateCallRouting(false /*fromCache*/, delayMs);
899 } else {
900 if (oldState == AUDIO_MODE_IN_CALL) {
901 disconnectTelephonyAudioSource(mCallRxSourceClient);
902 disconnectTelephonyAudioSource(mCallTxSourceClient);
903 }
904 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100905 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
906 // force routing command to audio hardware when ending call
907 // even if no device change is needed
908 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
909 rxDevices = mPrimaryOutput->devices();
910 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530911 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700912 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700913 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700914
jiabin3ff8d7d2022-12-13 06:27:44 +0000915 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700916 // reevaluate routing on all outputs in case tracks have been started during the call
917 for (size_t i = 0; i < mOutputs.size(); i++) {
918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100919 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200920 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
921 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000922 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
923 // If the device is using preferred mixer attributes, the output need to reopen
924 // with default configuration when the new selected devices are different from
925 // current routing devices.
926 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
927 continue;
928 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530929 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200930 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700931 }
932 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000933 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700934
Eric Laurent96d1dda2022-03-14 17:14:19 +0100935 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 if (isStateInCall(state)) {
938 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800940 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700941 }
942
943 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100944 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
945 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700946}
947
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700948audio_mode_t AudioPolicyManager::getPhoneState() {
949 return mEngine->getPhoneState();
950}
951
Eric Laurente0720872014-03-11 09:30:41 -0700952void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100953 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700954{
François Gaffie2110e042015-03-24 08:41:51 +0100955 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700956 if (config == mEngine->getForceUse(usage)) {
957 return;
958 }
Eric Laurente552edb2014-03-10 17:42:56 -0700959
François Gaffie2110e042015-03-24 08:41:51 +0100960 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
961 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
962 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700963 }
François Gaffie2110e042015-03-24 08:41:51 +0100964 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
965 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
966 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700967
968 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700969 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800970
Eric Laurent22fcda22019-05-17 16:28:47 -0700971 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
972 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800973 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700974 }
975
Eric Laurentdc462862016-07-19 12:29:53 -0700976 //FIXME: workaround for truncated touch sounds
977 // to be removed when the problem is handled by system UI
978 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700979 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
980 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
981 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700982
983 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100984 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700985}
986
Eric Laurente0720872014-03-11 09:30:41 -0700987void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700988{
989 ALOGV("setSystemProperty() property %s, value %s", property, value);
990}
991
Dorin Drimusecc9f422022-03-09 17:57:40 +0100992// Find an MSD output profile compatible with the parameters passed.
993// When "directOnly" is set, restrict search to profiles for direct outputs.
994sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
995 const DeviceVector& devices,
996 uint32_t samplingRate,
997 audio_format_t format,
998 audio_channel_mask_t channelMask,
999 audio_output_flags_t flags,
1000 bool directOnly)
1001{
1002 flags = getRelevantFlags(flags, directOnly);
1003
1004 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1005 if (msdModule != nullptr) {
1006 // for the msd module check if there are patches to the output devices
1007 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1008 HwModuleCollection modules;
1009 modules.add(msdModule);
1010 return searchCompatibleProfileHwModules(
1011 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1012 flags, directOnly);
1013 }
1014 }
1015 return nullptr;
1016}
1017
Michael Chana94fbb22018-04-24 14:31:19 +10001018// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1019// search to profiles for direct outputs.
1020sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001021 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001022 uint32_t samplingRate,
1023 audio_format_t format,
1024 audio_channel_mask_t channelMask,
1025 audio_output_flags_t flags,
1026 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001027{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 flags = getRelevantFlags(flags, directOnly);
1029
1030 return searchCompatibleProfileHwModules(
1031 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1032}
1033
1034audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1035 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001036 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 // only retain flags that will drive the direct output profile selection
1038 // if explicitly requested
1039 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001040 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001041 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1042 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001043 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 return flags;
1045}
Eric Laurent861a6282015-05-18 15:40:16 -07001046
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1048 const HwModuleCollection& hwModules,
1049 const DeviceVector& devices,
1050 uint32_t samplingRate,
1051 audio_format_t format,
1052 audio_channel_mask_t channelMask,
1053 audio_output_flags_t flags,
1054 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001055 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001056 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001057 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001058 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059 samplingRate, NULL /*updatedSamplingRate*/,
1060 format, NULL /*updatedFormat*/,
1061 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001062 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 continue;
1064 }
1065 // reject profiles not corresponding to a device currently available
1066 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1067 continue;
1068 }
1069 // reject profiles if connected device does not support codec
1070 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1071 continue;
1072 }
1073 if (!directOnly) {
1074 return curProfile;
1075 }
1076
1077 // when searching for direct outputs, if several profiles are compatible, give priority
1078 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001079 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001080 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001081 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001082 }
1083 profile = curProfile;
1084 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1085 break;
1086 }
Eric Laurente552edb2014-03-10 17:42:56 -07001087 }
1088 }
Eric Laurent861a6282015-05-18 15:40:16 -07001089 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001090}
1091
Eric Laurentfa0f6742021-08-17 18:39:44 +02001092sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001093 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001094{
1095 for (const auto& hwModule : mHwModules) {
1096 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001097 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098 continue;
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001101 // reject profiles not corresponding to a device currently available
1102 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1103 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1104 continue;
1105 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1107 != devices.size()) {
1108 continue;
1109 }
1110 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001111 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1112 return curProfile;
1113 }
1114 }
1115 return nullptr;
1116}
1117
Eric Laurentf4e63452017-11-06 19:31:46 +00001118audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001119{
François Gaffiec005e562018-11-06 15:04:49 +01001120 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001121
1122 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1123 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1124 // format, flags, etc. This may result in some discrepancy for functions that utilize
1125 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1126 // and AudioSystem::getOutputSamplingRate().
1127
François Gaffie11d30102018-11-02 16:09:09 +01001128 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001129 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1130 if (stream == AUDIO_STREAM_MUSIC &&
1131 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1132 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1133 }
1134 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001135
François Gaffie11d30102018-11-02 16:09:09 +01001136 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1137 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001138 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001139}
1140
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1142 const audio_attributes_t *srcAttr,
1143 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001144{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001145 if (srcAttr != NULL) {
1146 if (!isValidAttributes(srcAttr)) {
1147 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1148 __func__,
1149 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1150 srcAttr->tags);
1151 return BAD_VALUE;
1152 }
1153 *dstAttr = *srcAttr;
1154 } else {
1155 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1156 ALOGE("%s: invalid stream type", __func__);
1157 return BAD_VALUE;
1158 }
François Gaffiec005e562018-11-06 15:04:49 +01001159 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001160 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001161
1162 // Only honor audibility enforced when required. The client will be
1163 // forced to reconnect if the forced usage changes.
1164 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001165 dstAttr->flags = static_cast<audio_flags_mask_t>(
1166 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001167 }
1168
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169 return NO_ERROR;
1170}
1171
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172status_t AudioPolicyManager::getOutputForAttrInt(
1173 audio_attributes_t *resultAttr,
1174 audio_io_handle_t *output,
1175 audio_session_t session,
1176 const audio_attributes_t *attr,
1177 audio_stream_type_t *stream,
1178 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001179 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180 audio_output_flags_t *flags,
1181 audio_port_handle_t *selectedDeviceId,
1182 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001183 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001185 bool *isSpatialized,
1186 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001187{
François Gaffiec005e562018-11-06 15:04:49 +01001188 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001189 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001190 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001191 const sp<DeviceDescriptor> requestedDevice =
1192 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1193
Eric Laurent8a1095a2019-11-08 14:44:16 -08001194 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001195 *isSpatialized = false;
1196
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001197 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1198 if (status != NO_ERROR) {
1199 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001200 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001201 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001202 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001203 }
François Gaffiec005e562018-11-06 15:04:49 +01001204 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001205
François Gaffiec005e562018-11-06 15:04:49 +01001206 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1207 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001208
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 bool usePrimaryOutputFromPolicyMixes = false;
1210
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1212 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1213 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001215 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1216 .channel_mask = config->channel_mask,
1217 .format = config->format,
1218 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001219 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001220 mAvailableOutputDevices, requestedDevice, primaryMix,
1221 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001222 if (status != OK) {
1223 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001224 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001225
Kevin Rocard153f92d2018-12-18 18:33:28 -08001226 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001227 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1228 && !audio_is_linear_pcm(config->format)) {
1229 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 return BAD_VALUE;
1231 }
1232 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001233 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001234 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1235 primaryMix->mDeviceAddress,
1236 AUDIO_FORMAT_DEFAULT);
1237 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001238 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001239 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1240 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001241 // if a direct output can be opened to deliver the track's multi-channel content to the
1242 // output rather than being downmixed by the primary output, then use this direct
1243 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1244 // mix.
1245 bool tryDirectForChannelMask = policyDesc != nullptr
1246 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1247 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001248 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001249 audio_io_handle_t newOutput;
1250 status = openDirectOutput(
1251 *stream, session, config,
1252 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001253 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001255 policyDesc = mOutputs.valueFor(newOutput);
1256 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001257 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001258 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001259 policyDesc = nullptr;
1260 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001261 }
1262 if (policyDesc != nullptr) {
1263 policyDesc->mPolicyMix = primaryMix;
1264 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001265 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1266 : AUDIO_PORT_HANDLE_NONE;
1267 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1268 // Remove direct flag as it is not on a direct output.
1269 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1270 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001271
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001272 ALOGV("getOutputForAttr() returns output %d", *output);
1273 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1274 *outputType = API_OUT_MIX_PLAYBACK;
1275 } else {
1276 *outputType = API_OUTPUT_LEGACY;
1277 }
1278 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001279 } else {
1280 if (policyMixDevice != nullptr) {
1281 ALOGE("%s, try to use primary mix but no output found", __func__);
1282 return INVALID_OPERATION;
1283 }
1284 // Fallback to default engine selection as the selected primary mix device is not
1285 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001286 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001287 }
François Gaffiec005e562018-11-06 15:04:49 +01001288 // Virtual sources must always be dynamicaly or explicitly routed
1289 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1290 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1291 return BAD_VALUE;
1292 }
1293 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1294 // in order to let the choice of the order to future vendor engine
1295 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001296
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001297 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001298 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001299 }
1300
Nadav Barb2f18162018-07-18 13:01:53 +03001301 // Set incall music only if device was explicitly set, and fallback to the device which is
1302 // chosen by the engine if not.
1303 // FIXME: provide a more generic approach which is not device specific and move this back
1304 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001305 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001306 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001307 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001308 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001309 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001310 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001311 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001312 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001313 }
1314 }
1315
François Gaffiec005e562018-11-06 15:04:49 +01001316 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1317 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1318 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001319
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001320 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001321 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001322 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001323 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001324 ALOGV("%s() Using MSD devices %s instead of devices %s",
1325 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001326 } else {
1327 *output = AUDIO_IO_HANDLE_NONE;
1328 }
1329 }
1330 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001331 sp<PreferredMixerAttributesInfo> info = nullptr;
1332 if (outputDevices.size() == 1) {
1333 info = getPreferredMixerAttributesInfo(
1334 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001335 mEngine->getProductStrategyForAttributes(*resultAttr),
1336 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001337 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1338 // and it is currently active.
1339 if (info != nullptr && info->getUid() != uid &&
1340 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1341 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001342 info = nullptr;
1343 }
1344 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001345 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001346 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001347 // The client will be active if the client is currently preferred mixer owner and the
1348 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001349 *isBitPerfect = (info != nullptr
1350 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001351 && info->getUid() == uid
1352 && *output != AUDIO_IO_HANDLE_NONE
1353 // When bit-perfect output is selected for the preferred mixer attributes owner,
1354 // only need to consider the config matches.
1355 && mOutputs.valueFor(*output)->isConfigurationMatched(
1356 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001357 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001358 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001359 AudioProfileVector profiles;
1360 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1361 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001362 const auto channels = profiles[0]->getChannels();
1363 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1364 config->channel_mask = *channels.begin();
1365 }
1366 const auto sampleRates = profiles[0]->getSampleRates();
1367 if (!sampleRates.empty() &&
1368 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1369 config->sample_rate = *sampleRates.begin();
1370 }
jiabinf1c73972022-04-14 16:28:52 -07001371 config->format = profiles[0]->getFormat();
1372 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001373 return INVALID_OPERATION;
1374 }
Paul McLeanaa981192015-03-21 09:55:15 -07001375
François Gaffiec005e562018-11-06 15:04:49 +01001376 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001377 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001378 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001379 *selectedDeviceId = outputDevice->getId();
1380 break;
1381 }
1382 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001383
Eric Laurent8a1095a2019-11-08 14:44:16 -08001384 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1385 *outputType = API_OUTPUT_TELEPHONY_TX;
1386 } else {
1387 *outputType = API_OUTPUT_LEGACY;
1388 }
1389
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001390 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1391
1392 return NO_ERROR;
1393}
1394
1395status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1396 audio_io_handle_t *output,
1397 audio_session_t session,
1398 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001399 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001400 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001401 audio_output_flags_t *flags,
1402 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001403 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001404 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001405 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001406 bool *isSpatialized,
1407 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001408{
1409 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1410 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1411 return INVALID_OPERATION;
1412 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001413 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001414 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001415 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001417 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001418 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001419 const sp<DeviceDescriptor> requestedDevice =
1420 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1421
1422 // Prevent from storing invalid requested device id in clients
1423 const audio_port_handle_t sanitizedRequestedPortId =
1424 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1425 *selectedDeviceId = sanitizedRequestedPortId;
1426
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001427 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001428 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001429 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1430 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001431 if (status != NO_ERROR) {
1432 return status;
1433 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001434 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001435 if (secondaryOutputs != nullptr) {
1436 for (auto &secondaryMix : secondaryMixes) {
1437 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1438 if (outputDesc != nullptr &&
1439 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1440 secondaryOutputs->push_back(outputDesc->mIoHandle);
1441 weakSecondaryOutputDescs.push_back(outputDesc);
1442 }
1443 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001444 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001445
Eric Laurent8fc147b2018-07-22 19:13:55 -07001446 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001447 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001448 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001449 };
jiabin4ef93452019-09-10 14:29:54 -07001450 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001451
Eric Laurentc209fe42020-06-05 18:11:23 -07001452 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001453 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001454 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001455 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001456 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001457 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001458 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001459 std::move(weakSecondaryOutputDescs),
1460 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001461 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001462
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001463 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1464 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001465
Eric Laurente83b55d2014-11-14 10:06:21 -08001466 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001467}
1468
Eric Laurentc529cf62020-04-17 18:19:10 -07001469status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1470 audio_session_t session,
1471 const audio_config_t *config,
1472 audio_output_flags_t flags,
1473 const DeviceVector &devices,
1474 audio_io_handle_t *output) {
1475
1476 *output = AUDIO_IO_HANDLE_NONE;
1477
1478 // skip direct output selection if the request can obviously be attached to a mixed output
1479 // and not explicitly requested
1480 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1481 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1482 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1483 return NAME_NOT_FOUND;
1484 }
1485
1486 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1487 // This prevents creating an offloaded track and tearing it down immediately after start
1488 // when audioflinger detects there is an active non offloadable effect.
1489 // FIXME: We should check the audio session here but we do not have it in this context.
1490 // This may prevent offloading in rare situations where effects are left active by apps
1491 // in the background.
1492 sp<IOProfile> profile;
1493 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1494 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1495 profile = getProfileForOutput(
1496 devices, config->sample_rate, config->format, config->channel_mask,
1497 flags, true /* directOnly */);
1498 }
1499
1500 if (profile == nullptr) {
1501 return NAME_NOT_FOUND;
1502 }
1503
1504 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1505 for (size_t i = 0; i < mOutputs.size(); i++) {
1506 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1507 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1508 // reuse direct output if currently open by the same client
1509 // and configured with same parameters
1510 if ((config->sample_rate == desc->getSamplingRate()) &&
1511 (config->format == desc->getFormat()) &&
1512 (config->channel_mask == desc->getChannelMask()) &&
1513 (session == desc->mDirectClientSession)) {
1514 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001515 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001516 mOutputs.keyAt(i), session);
1517 *output = mOutputs.keyAt(i);
1518 return NO_ERROR;
1519 }
1520 }
1521 }
1522
1523 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001524 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1525 return NAME_NOT_FOUND;
1526 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1527 // MMAP gracefully handles lack of an exclusive track resource by mixing
1528 // above the audio framework. For AAudio to know that the limit is reached,
1529 // return an error.
1530 return NAME_NOT_FOUND;
1531 } else {
1532 // Close outputs on this profile, if available, to free resources for this request
1533 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1534 const auto desc = mOutputs.valueAt(i);
1535 if (desc->mProfile == profile) {
1536 closeOutput(desc->mIoHandle);
1537 }
1538 }
1539 }
1540 }
1541
1542 // Unable to close streams to find free resources for this request
1543 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001544 return NAME_NOT_FOUND;
1545 }
1546
Atneya Nairb16666a2023-12-11 20:18:33 -08001547 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001548
Michael Chan6fb34492020-12-08 15:44:49 +11001549 // An MSD patch may be using the only output stream that can service this request. Release
1550 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001551 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001552
Eric Laurentf1f22e72021-07-13 14:04:14 +02001553 status_t status =
1554 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001555
1556 // only accept an output with the requested parameters
1557 if (status != NO_ERROR ||
1558 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1559 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1560 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1561 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1562 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1563 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1564 config->channel_mask, outputDesc->getChannelMask());
1565 if (*output != AUDIO_IO_HANDLE_NONE) {
1566 outputDesc->close();
1567 }
1568 // fall back to mixer output if possible when the direct output could not be open
1569 if (audio_is_linear_pcm(config->format) &&
1570 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1571 return NAME_NOT_FOUND;
1572 }
1573 *output = AUDIO_IO_HANDLE_NONE;
1574 return BAD_VALUE;
1575 }
1576 outputDesc->mDirectOpenCount = 1;
1577 outputDesc->mDirectClientSession = session;
1578
1579 addOutput(*output, outputDesc);
1580 mPreviousOutputs = mOutputs;
1581 ALOGV("%s returns new direct output %d", __func__, *output);
1582 mpClientInterface->onAudioPortListUpdate();
1583 return NO_ERROR;
1584}
1585
François Gaffie11d30102018-11-02 16:09:09 +01001586audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1587 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001588 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001589 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001590 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001591 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001592 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001593 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001594 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001595{
Andy Hungc88b0642018-04-27 15:42:35 -07001596 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001597
jiabine375d412019-02-26 12:54:53 -08001598 // Discard haptic channel mask when forcing muting haptic channels.
1599 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001600 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1601 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001602
Eric Laurente552edb2014-03-10 17:42:56 -07001603 // open a direct output if required by specified parameters
1604 //force direct flag if offload flag is set: offloading implies a direct output stream
1605 // and all common behaviors are driven by checking only the direct flag
1606 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001607 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1608 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001609 }
Nadav Bar766fb022018-01-07 12:18:03 +02001610 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1611 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001612 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001613
1614 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1615
Eric Laurente83b55d2014-11-14 10:06:21 -08001616 // only allow deep buffering for music stream type
1617 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001618 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001619 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001620 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001621 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1622 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001623 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001624 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001625 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001626 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001627 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001628 audio_is_linear_pcm(config->format) &&
1629 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001630 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001631 AUDIO_OUTPUT_FLAG_DIRECT);
1632 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001633 }
Eric Laurente552edb2014-03-10 17:42:56 -07001634
Carter Hsua3abb402021-10-26 11:11:20 +08001635 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1636 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1637 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1638 }
1639
Eric Laurentf9230d52024-01-26 18:49:09 +01001640 // Use the spatializer output if the content can be spatialized, no preferred mixer
1641 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001642 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001643 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001644 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001645 && prefMixerConfigInfo == nullptr
1646 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001647 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001648 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001649 }
1650
Eric Laurentc529cf62020-04-17 18:19:10 -07001651 audio_config_t directConfig = *config;
1652 directConfig.channel_mask = channelMask;
1653 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1654 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001655 return output;
1656 }
1657
Eric Laurent14cbfca2016-03-17 09:42:16 -07001658 // A request for HW A/V sync cannot fallback to a mixed output because time
1659 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001660 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001661 return AUDIO_IO_HANDLE_NONE;
1662 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001663 // A request for Tuner cannot fallback to a mixed output
1664 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1665 return AUDIO_IO_HANDLE_NONE;
1666 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001667
Eric Laurente552edb2014-03-10 17:42:56 -07001668 // ignoring channel mask due to downmix capability in mixer
1669
1670 // open a non direct output
1671
1672 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001673 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001674 // get which output is suitable for the specified stream. The actual
1675 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001676 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001677 if (prefMixerConfigInfo != nullptr) {
1678 for (audio_io_handle_t outputHandle : outputs) {
1679 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1680 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1681 output = outputHandle;
1682 break;
1683 }
1684 }
1685 if (output == AUDIO_IO_HANDLE_NONE) {
1686 // No output open with the preferred profile. Open a new one.
1687 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1688 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1689 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1690 config.format = prefMixerConfigInfo->getConfigBase().format;
1691 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1692 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1693 &config, prefMixerConfigInfo->getFlags());
1694 if (preferredOutput == nullptr) {
1695 ALOGE("%s failed to open output with preferred mixer config", __func__);
1696 } else {
1697 output = preferredOutput->mIoHandle;
1698 }
1699 }
1700 } else {
1701 // at this stage we should ignore the DIRECT flag as no direct output could be
1702 // found earlier
1703 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1704 output = selectOutput(
1705 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1706 }
Eric Laurente552edb2014-03-10 17:42:56 -07001707 }
François Gaffie11d30102018-11-02 16:09:09 +01001708 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001709 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001710 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001711
Eric Laurente552edb2014-03-10 17:42:56 -07001712 return output;
1713}
1714
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001715sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001716 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1717 mAvailableInputDevices);
1718 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1719}
1720
1721DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1722 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1723 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724}
1725
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001726const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001727 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001728 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1729 if (msdModule != 0) {
1730 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1731 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1732 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1733 const struct audio_port_config *source = &patch->mPatch.sources[j];
1734 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1735 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001736 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001737 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 }
1739 }
1740 }
1741 return msdPatches;
1742}
1743
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001744bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1745 ssize_t index = mAudioPatches.indexOfKey(handle);
1746 if (index < 0) {
1747 return false;
1748 }
1749 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1750 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1751 if (msdModule == nullptr) {
1752 return false;
1753 }
1754 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1755 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1756 return true;
1757 }
1758 index = getMsdOutputPatches().indexOfKey(handle);
1759 if (index < 0) {
1760 return false;
1761 }
1762 return true;
1763}
1764
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001765status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1766 const InputProfileCollection &inputProfiles,
1767 const OutputProfileCollection &outputProfiles,
1768 const sp<DeviceDescriptor> &sourceDevice,
1769 const sp<DeviceDescriptor> &sinkDevice,
1770 AudioProfileVector& sourceProfiles,
1771 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001774 return NO_INIT;
1775 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001777 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001778 return NO_INIT;
1779 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001781 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1782 inProfile->supportsDevice(sourceDevice)) {
1783 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001784 }
1785 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001786 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001787 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788 outProfile->supportsDevice(sinkDevice)) {
1789 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 }
1791 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001792 return NO_ERROR;
1793}
1794
1795status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1796 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1797 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1798{
Dean Wheatley16809da2022-12-09 14:55:46 +11001799 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1800 static const std::vector<audio_format_t> formatsOrder = {{
1801 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001802 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1803 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001804 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1805 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1806 // preferred).
1807 std::vector<audio_channel_mask_t> masks = {{
1808 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1809 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1810 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1811 // insert index masks (higher counts most preferred) as preferred over position masks
1812 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1813 masks.insert(
1814 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1815 }
1816 return masks;
1817 }();
1818
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001819 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001820 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1821 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001822 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1824 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001825 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 }
1827 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1828 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1829 sinkConfig->format = bestSinkConfig.format;
1830 // For encoded streams force direct flag to prevent downstream mixing.
1831 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1832 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001833 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1834 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001836 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1837 // raw and IEC61937 framed streams.
1838 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1839 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1840 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001841 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1842 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001843 sourceConfig->channel_mask =
1844 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1845 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1846 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001847 sourceConfig->format = bestSinkConfig.format;
1848 // Copy input stream directly without any processing (e.g. resampling).
1849 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1850 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1851 if (hwAvSync) {
1852 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1853 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1854 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1855 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1856 }
1857 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1858 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1859 sinkConfig->config_mask |= config_mask;
1860 sourceConfig->config_mask |= config_mask;
1861 return NO_ERROR;
1862}
1863
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001864PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1865 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001866{
1867 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001868 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1869 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1870 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1871 if (deviceModule == nullptr) {
1872 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1873 return patchBuilder;
1874 }
1875 const InputProfileCollection inputProfiles = msdIsSource ?
1876 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1877 const OutputProfileCollection outputProfiles = msdIsSource ?
1878 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1879
1880 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1881 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1882 device : getMsdAudioOutDevices().itemAt(0);
1883 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1884
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1886 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887 AudioProfileVector sourceProfiles;
1888 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1890 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001891 for (auto hwAvSync : { true, false }) {
1892 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1893 sourceProfiles, sinkProfiles) != NO_ERROR) {
1894 continue;
1895 }
1896 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1897 &sinkConfig) == NO_ERROR) {
1898 // Found a matching config. Re-create PatchBuilder with this config.
1899 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1900 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001902 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 " supporting PCM format conversion.", __func__);
1904 return patchBuilder;
1905}
1906
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001907status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001908 DeviceVector devices;
1909 if (outputDevices != nullptr && outputDevices->size() > 0) {
1910 devices.add(*outputDevices);
1911 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 // Use media strategy for unspecified output device. This should only
1913 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1914 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001915 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001916 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001917 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001918 }
Michael Chan6fb34492020-12-08 15:44:49 +11001919 std::vector<PatchBuilder> patchesToCreate;
1920 for (auto i = 0u; i < devices.size(); ++i) {
1921 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001923 }
1924 // Retain only the MSD patches associated with outputDevices request.
1925 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001926 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001927 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1928 auto retainedPatch = false;
1929 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1930 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1931 patchesToRemove.removeItemsAt(i);
1932 retainedPatch = true;
1933 break;
1934 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001935 }
Michael Chan6fb34492020-12-08 15:44:49 +11001936 if (retainedPatch) {
1937 it = patchesToCreate.erase(it);
1938 continue;
1939 }
1940 ++it;
1941 }
1942 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1943 return NO_ERROR;
1944 }
1945 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1946 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001947 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 }
Michael Chan6fb34492020-12-08 15:44:49 +11001949 status_t status = NO_ERROR;
1950 for (const auto &p : patchesToCreate) {
1951 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1952 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1953 char message[256];
1954 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1955 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1956 currStatus == NO_ERROR ? "Success" : "Error",
1957 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1958 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1959 if (currStatus == NO_ERROR) {
1960 ALOGD("%s", message);
1961 } else {
1962 ALOGE("%s", message);
1963 if (status == NO_ERROR) {
1964 status = currStatus;
1965 }
1966 }
1967 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001968 return status;
1969}
1970
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001971void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1972 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001973 for (size_t i = 0; i < msdPatches.size(); i++) {
1974 const auto& patch = msdPatches[i];
1975 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1976 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1977 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1978 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1979 releaseAudioPatch(patch->getHandle(), mUidCached);
1980 break;
1981 }
1982 }
1983 }
1984}
1985
Dorin Drimus94d94412022-02-02 09:05:02 +01001986bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001987 DeviceVector devicesToCheck =
1988 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001989 AudioPatchCollection msdPatches = getMsdOutputPatches();
1990 for (size_t i = 0; i < msdPatches.size(); i++) {
1991 const auto& patch = msdPatches[i];
1992 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1993 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1994 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1995 const auto& foundDevice = devicesToCheck.getDevice(
1996 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1997 if (foundDevice != nullptr) {
1998 devicesToCheck.remove(foundDevice);
1999 if (devicesToCheck.isEmpty()) {
2000 return true;
2001 }
2002 }
2003 }
2004 }
2005 }
2006 return false;
2007}
2008
Eric Laurente0720872014-03-11 09:30:41 -07002009audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002010 audio_output_flags_t flags,
2011 audio_format_t format,
2012 audio_channel_mask_t channelMask,
2013 uint32_t samplingRate,
2014 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002015{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2017 "%s called with format %#x", __func__, format);
2018
jiabinebb6af42020-06-09 17:31:17 -07002019 // Return the output that haptic-generating attached to when 1) session id is specified,
2020 // 2) haptic-generating effect exists for given session id and 3) the output that
2021 // haptic-generating effect attached to is in given outputs.
2022 if (sessionId != AUDIO_SESSION_NONE) {
2023 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2024 sessionId, FX_IID_HAPTICGENERATOR);
2025 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2026 return hapticGeneratingOutput;
2027 }
2028 }
2029
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 // Flags disqualifying an output: the match must happen before calling selectOutput()
2031 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2032 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2033
2034 // Flags expressing a functional request: must be honored in priority over
2035 // other criteria
2036 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2037 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002038 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2039 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002040 // Flags expressing a performance request: have lower priority than serving
2041 // requested sampling rate or channel mask
2042 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2043 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2044 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2045
2046 const audio_output_flags_t functionalFlags =
2047 (audio_output_flags_t)(flags & kFunctionalFlags);
2048 const audio_output_flags_t performanceFlags =
2049 (audio_output_flags_t)(flags & kPerformanceFlags);
2050
2051 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2052
Eric Laurente552edb2014-03-10 17:42:56 -07002053 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002054 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002055 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002056 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002057 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002058 // with tiebreak preferring the minimum number of extra functional flags
2059 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002060 // 3: the output supporting the exact channel mask
2061 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002062 // 5: the output with the highest sampling rate if the requested sample rate is
2063 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 // 6: the output with the highest number of requested performance flags
2065 // 7: the output with the bit depth the closest to the requested one
2066 // 8: the primary output
2067 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002068
Eric Laurent16c66dd2019-05-01 17:54:10 -07002069 // matching criteria values in priority order for best matching output so far
2070 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002071
Eric Laurent16c66dd2019-05-01 17:54:10 -07002072 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2073 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2074 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002075
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002076 for (audio_io_handle_t output : outputs) {
2077 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 // matching criteria values in priority order for current output
2079 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002080
Eric Laurent16c66dd2019-05-01 17:54:10 -07002081 if (outputDesc->isDuplicated()) {
2082 continue;
2083 }
2084 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2085 continue;
2086 }
Eric Laurent8838a382014-09-08 16:44:28 -07002087
Eric Laurent16c66dd2019-05-01 17:54:10 -07002088 // If haptic channel is specified, use the haptic output if present.
2089 // When using haptic output, same audio format and sample rate are required.
2090 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002091 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2093 continue;
2094 }
2095 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002096 && format == outputDesc->getFormat()
2097 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002098 currentMatchCriteria[0] = outputHapticChannelCount;
2099 }
2100
2101 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002102 const int matchingFunctionalFlags =
2103 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2104 const int totalFunctionalFlags =
2105 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2106 // Prefer matching functional flags, but subtract unnecessary functional flags.
2107 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002108
2109 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002110 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2111 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002112 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2113 channelCount <= outputChannelCount) {
2114 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002115 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2116 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002117 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002118 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002119 currentMatchCriteria[3] = outputChannelCount;
2120 }
2121
2122 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002123 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002124 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002125 }
2126
2127 // performance flags match
2128 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2129
2130 // format match
2131 if (format != AUDIO_FORMAT_INVALID) {
2132 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002133 PolicyAudioPort::kFormatDistanceMax -
2134 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135 }
2136
2137 // primary output match
2138 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2139
2140 // compare match criteria by priority then value
2141 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2142 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2143 bestMatchCriteria = currentMatchCriteria;
2144 bestOutput = output;
2145
2146 std::stringstream result;
2147 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2148 std::ostream_iterator<int>(result, " "));
2149 ALOGV("%s new bestOutput %d criteria %s",
2150 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002151 }
2152 }
2153
Eric Laurent16c66dd2019-05-01 17:54:10 -07002154 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002155}
2156
Eric Laurent8fc147b2018-07-22 19:13:55 -07002157status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002158{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002159 ALOGV("%s portId %d", __FUNCTION__, portId);
2160
2161 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2162 if (outputDesc == 0) {
2163 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002164 return BAD_VALUE;
2165 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002166 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002167
Eric Laurent8fc147b2018-07-22 19:13:55 -07002168 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002169 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002170
Eric Laurent733ce942017-12-07 12:18:25 -08002171 status_t status = outputDesc->start();
2172 if (status != NO_ERROR) {
2173 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002174 }
2175
Eric Laurent97ac8712018-07-27 18:59:02 -07002176 uint32_t delayMs;
2177 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002178
2179 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002180 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002181 if (status == DEAD_OBJECT) {
2182 sp<SwAudioOutputDescriptor> desc =
2183 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2184 if (desc == nullptr) {
2185 // This is not common, it may indicate something wrong with the HAL.
2186 ALOGE("%s unable to open output with default config", __func__);
2187 return status;
2188 }
2189 desc->mUsePreferredMixerAttributes = true;
2190 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002191 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002192 }
jiabina84c3d32022-12-02 18:59:55 +00002193
2194 // If the client is the first one active on preferred mixer parameters, reopen the output
2195 // if the current mixer parameters doesn't match the preferred one.
2196 if (outputDesc->devices().size() == 1) {
2197 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2198 outputDesc->devices()[0]->getId(), client->strategy());
2199 if (info != nullptr && info->getUid() == client->uid()) {
2200 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2201 info->getConfigBase(), info->getFlags())) {
2202 stopSource(outputDesc, client);
2203 outputDesc->stop();
2204 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2205 config.channel_mask = info->getConfigBase().channel_mask;
2206 config.sample_rate = info->getConfigBase().sample_rate;
2207 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002208 sp<SwAudioOutputDescriptor> desc =
2209 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2210 if (desc == nullptr) {
2211 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002212 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002213 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002214 // Intentionally return error to let the client side resending request for
2215 // creating and starting.
2216 return DEAD_OBJECT;
2217 }
2218 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002219 if (info->getActiveClientCount() == 1 &&
2220 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2221 // If it is first bit-perfect client, reroute all clients that will be routed to
2222 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2223 PortHandleVector clientsToInvalidate;
2224 for (size_t i = 0; i < mOutputs.size(); i++) {
2225 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002226 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002227 continue;
2228 }
2229 for (const auto& c : mOutputs[i]->getClientIterable()) {
2230 clientsToInvalidate.push_back(c->portId());
2231 }
2232 }
2233 if (!clientsToInvalidate.empty()) {
2234 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2235 __func__);
2236 mpClientInterface->invalidateTracks(clientsToInvalidate);
2237 }
2238 }
jiabina84c3d32022-12-02 18:59:55 +00002239 }
2240 }
2241
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002242 if (client->hasPreferredDevice()) {
2243 // playback activity with preferred device impacts routing occurred, inform upper layers
2244 mpClientInterface->onRoutingUpdated();
2245 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002246 if (delayMs != 0) {
2247 usleep(delayMs * 1000);
2248 }
2249
2250 return status;
2251}
2252
Eric Laurent96d1dda2022-03-14 17:14:19 +01002253bool AudioPolicyManager::isLeUnicastActive() const {
2254 if (isInCall()) {
2255 return true;
2256 }
2257 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2258}
2259
2260bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2261 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2262 return false;
2263 }
2264 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2265 ALOGV("%s active %d", __func__, active);
2266 return active;
2267}
2268
Eric Laurent97ac8712018-07-27 18:59:02 -07002269status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2270 const sp<TrackClientDescriptor>& client,
2271 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002272{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002273 // cannot start playback of STREAM_TTS if any other output is being used
2274 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002275
2276 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002277 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002278 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002279 auto clientStrategy = client->strategy();
2280 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002281 if (stream == AUDIO_STREAM_TTS) {
2282 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002283 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002284 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002285 return INVALID_OPERATION;
2286 } else {
2287 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2288 }
2289 } else {
2290 // some playback other than beacon starts
2291 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2292 }
2293
Eric Laurent77305a62016-07-25 16:39:22 -07002294 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002295 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002296 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002297
François Gaffie11d30102018-11-02 16:09:09 +01002298 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002299 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002300 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002301 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002302 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002303 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002304 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002305 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002306 } else {
2307 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002308 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002309 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2310 AUDIO_FORMAT_DEFAULT);
2311 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2312 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002313 }
2314
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002315 // requiresMuteCheck is false when we can bypass mute strategy.
2316 // It covers a common case when there is no materially active audio
2317 // and muting would result in unnecessary delay and dropped audio.
2318 const uint32_t outputLatencyMs = outputDesc->latency();
2319 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002320 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002321
Eric Laurente552edb2014-03-10 17:42:56 -07002322 // increment usage count for this stream on the requested output:
2323 // NOTE that the usage count is the same for duplicated output and hardware output which is
2324 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002325 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002326
2327 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002328 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002329 // Preferred device may be exclusive, use only if no other active clients on this output
2330 devices = DeviceVector(
2331 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2332 } else {
2333 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2334 }
François Gaffie11d30102018-11-02 16:09:09 +01002335 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002336 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002337 }
2338 }
Eric Laurente552edb2014-03-10 17:42:56 -07002339
François Gaffiec005e562018-11-06 15:04:49 +01002340 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002341 selectOutputForMusicEffects();
2342 }
2343
François Gaffie1c878552018-11-22 16:53:21 +01002344 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002345 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002346 if (devices.isEmpty()) {
2347 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002348 }
François Gaffiec005e562018-11-06 15:04:49 +01002349 bool shouldWait =
2350 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2351 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2352 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002353 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002354 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002355 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002356 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002357 // An output has a shared device if
2358 // - managed by the same hw module
2359 // - supports the currently selected device
2360 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002361 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002362
Eric Laurent77305a62016-07-25 16:39:22 -07002363 // force a device change if any other output is:
2364 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002365 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002366 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002367 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002368 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002369 // change the device currently selected by the other output.
2370 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002371 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002372 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002373 force = true;
2374 }
2375 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002376 // a notification so that audio focus effect can propagate, or that a mute/unmute
2377 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002378 const uint32_t latencyMs = desc->latency();
2379 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2380
2381 if (shouldWait && isActive && (waitMs < latencyMs)) {
2382 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002383 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002384
2385 // Require mute check if another output is on a shared device
2386 // and currently active to have proper drain and avoid pops.
2387 // Note restoring AudioTracks onto this output needs to invoke
2388 // a volume ramp if there is no mute.
2389 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002390 }
2391 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002392
jiabin3ff8d7d2022-12-13 06:27:44 +00002393 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2394 // If the output is open with preferred mixer attributes, but the routed device is
2395 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2396 // changed.
2397 return DEAD_OBJECT;
2398 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002399 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302400 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2401 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002402
Eric Laurente552edb2014-03-10 17:42:56 -07002403 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002404 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002405 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002406 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002407 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002408 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002409 outputDesc->useHwGain() /*force*/)) {
2410 // request AudioService to reinitialize the volume curves asynchronously
2411 ALOGE("checkAndSetVolume failed, requesting volume range init");
2412 mpClientInterface->onVolumeRangeInitRequest();
2413 };
Eric Laurente552edb2014-03-10 17:42:56 -07002414
2415 // update the outputs if starting an output with a stream that can affect notification
2416 // routing
2417 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002418
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002419 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002420 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002421 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002422 }
Eric Laurentdc462862016-07-19 12:29:53 -07002423
2424 if (waitMs > muteWaitMs) {
2425 *delayMs = waitMs - muteWaitMs;
2426 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002427
2428 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2429 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2430 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2431 // change occurs after the MixerThread starts and causes a stream volume
2432 // glitch.
2433 //
2434 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002435 }
Eric Laurentdc462862016-07-19 12:29:53 -07002436
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002437 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002438 mEngine->getForceUse(
2439 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002440 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002441 }
2442
Eric Laurent97ac8712018-07-27 18:59:02 -07002443 // Automatically enable the remote submix input when output is started on a re routing mix
2444 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002445 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2446 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2448 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2449 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002450 "remote-submix",
2451 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002452 }
2453
Eric Laurent96d1dda2022-03-14 17:14:19 +01002454 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2455
Eric Laurente552edb2014-03-10 17:42:56 -07002456 return NO_ERROR;
2457}
2458
Eric Laurent96d1dda2022-03-14 17:14:19 +01002459void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2460 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2461 bool isUnicastActive = isLeUnicastActive();
2462
2463 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002464 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002465 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2466 for (size_t i = 0; i < mOutputs.size(); i++) {
2467 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2468 if (desc != ignoredOutput && desc->isActive()
2469 && ((isUnicastActive &&
2470 !desc->devices().
2471 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2472 || (wasUnicastActive &&
2473 !desc->devices().getDevicesFromTypes(
2474 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2475 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2476 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002477 if (desc->mUsePreferredMixerAttributes && force) {
2478 // If the device is using preferred mixer attributes, the output need to reopen
2479 // with default configuration when the new selected devices are different from
2480 // current routing devices.
2481 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2482 continue;
2483 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302484 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002485 // re-apply device specific volume if not done by setOutputDevice()
2486 if (!force) {
2487 applyStreamVolumes(desc, newDevices.types(), delayMs);
2488 }
2489 }
2490 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002491 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002492 }
2493}
2494
Eric Laurent8fc147b2018-07-22 19:13:55 -07002495status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002496{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002497 ALOGV("%s portId %d", __FUNCTION__, portId);
2498
2499 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2500 if (outputDesc == 0) {
2501 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002502 return BAD_VALUE;
2503 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002504 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002505
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002506 if (client->hasPreferredDevice(true)) {
2507 // playback activity with preferred device impacts routing occurred, inform upper layers
2508 mpClientInterface->onRoutingUpdated();
2509 }
2510
Eric Laurent97ac8712018-07-27 18:59:02 -07002511 ALOGV("stopOutput() output %d, stream %d, session %d",
2512 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002513
Eric Laurent97ac8712018-07-27 18:59:02 -07002514 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002515
Eric Laurent733ce942017-12-07 12:18:25 -08002516 if (status == NO_ERROR ) {
2517 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002518 } else {
2519 return status;
2520 }
2521
2522 if (outputDesc->devices().size() == 1) {
2523 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2524 outputDesc->devices()[0]->getId(), client->strategy());
2525 if (info != nullptr && info->getUid() == client->uid()) {
2526 info->decreaseActiveClient();
2527 if (info->getActiveClientCount() == 0) {
2528 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2529 }
2530 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002531 }
2532 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002533}
2534
Eric Laurent97ac8712018-07-27 18:59:02 -07002535status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2536 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002537{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002538 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002539 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002540 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002541 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002542
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002543 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2544
François Gaffie1c878552018-11-22 16:53:21 +01002545 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2546 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002547 // Automatically disable the remote submix input when output is stopped on a
2548 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002549 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002550 if (isSingleDeviceType(
2551 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002552 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002553 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2555 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002556 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002557 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002558 }
2559 }
2560 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002561 if (client->hasPreferredDevice(true) &&
2562 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002563 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002564 forceDeviceUpdate = true;
2565 }
2566
Eric Laurente552edb2014-03-10 17:42:56 -07002567 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002568 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002569
Eric Laurente552edb2014-03-10 17:42:56 -07002570 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002571 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002572 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002573 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002574
2575 // If the routing does not change, if an output is routed on a device using HwGain
2576 // (aka setAudioPortConfig) and there are still active clients following different
2577 // volume group(s), force reapply volume
2578 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2579 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2580
Eric Laurente552edb2014-03-10 17:42:56 -07002581 // delay the device switch by twice the latency because stopOutput() is executed when
2582 // the track stop() command is received and at that time the audio track buffer can
2583 // still contain data that needs to be drained. The latency only covers the audio HAL
2584 // and kernel buffers. Also the latency does not always include additional delay in the
2585 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302586 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002587 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002588
2589 // force restoring the device selection on other active outputs if it differs from the
2590 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002591 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002592 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002593 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002594 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002595 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002596 desc->isActive() &&
2597 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002598 (newDevices != desc->devices())) {
2599 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2600 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002601
jiabin3ff8d7d2022-12-13 06:27:44 +00002602 if (desc->mUsePreferredMixerAttributes && force) {
2603 // If the device is using preferred mixer attributes, the output need to
2604 // reopen with default configuration when the new selected devices are
2605 // different from current routing devices.
2606 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2607 continue;
2608 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302609 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002610
Eric Laurent57de36c2016-09-28 16:59:11 -07002611 // re-apply device specific volume if not done by setOutputDevice()
2612 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002613 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002614 }
Eric Laurente552edb2014-03-10 17:42:56 -07002615 }
2616 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002617 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002618 // update the outputs if stopping one with a stream that can affect notification routing
2619 handleNotificationRoutingForStream(stream);
2620 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002621
2622 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2623 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002624 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002625 }
2626
François Gaffiec005e562018-11-06 15:04:49 +01002627 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002628 selectOutputForMusicEffects();
2629 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002630
2631 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2632
Eric Laurente552edb2014-03-10 17:42:56 -07002633 return NO_ERROR;
2634 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002635 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002636 return INVALID_OPERATION;
2637 }
2638}
2639
jiabinbce0c1d2020-10-05 11:20:18 -07002640bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002641{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002642 ALOGV("%s portId %d", __FUNCTION__, portId);
2643
2644 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2645 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002646 // If an output descriptor is closed due to a device routing change,
2647 // then there are race conditions with releaseOutput from tracks
2648 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2649 // destroyed shortly thereafter.
2650 //
2651 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002652 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002653 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002654 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002655
2656 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002657
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302658 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2659 if (outputDesc->isClientActive(client)) {
2660 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2661 stopOutput(portId);
2662 }
2663
Eric Laurent8fc147b2018-07-22 19:13:55 -07002664 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2665 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002666 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002667 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002668 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002669 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002670 if (--outputDesc->mDirectOpenCount == 0) {
2671 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002672 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002673 }
2674 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302675
Andy Hung39efb7a2018-09-26 15:39:28 -07002676 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002677 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2678 // The output is pending reopened to query dynamic profiles and
2679 // there is no active clients
2680 closeOutput(outputDesc->mIoHandle);
2681 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2682 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2683 if (newOutputDesc == nullptr) {
2684 ALOGE("%s failed to open output", __func__);
2685 }
2686 return true;
2687 }
2688 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002689}
2690
Eric Laurentcaf7f482014-11-25 17:50:47 -08002691status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2692 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002693 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002694 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002695 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002696 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002697 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002698 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002699 input_type_t *inputType,
2700 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002701{
François Gaffiec005e562018-11-06 15:04:49 +01002702 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002703 "flags %#x attributes=%s requested device ID %d",
2704 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2705 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002706
Eric Laurentad2e7b92017-09-14 20:06:42 -07002707 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002708 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002709 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002710 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002711 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002712 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002713 sp<RecordClientDescriptor> clientDesc;
2714 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002715 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002717
2718 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2719 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2720 return INVALID_OPERATION;
2721 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002722
Francois Gaffie716e1432019-01-14 16:58:59 +01002723 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2724 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002725 }
2726
Paul McLean466dc8e2015-04-17 13:15:36 -06002727 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002728 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002729 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002730
Eric Laurentad2e7b92017-09-14 20:06:42 -07002731 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2732 // possible
2733 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2734 *input != AUDIO_IO_HANDLE_NONE) {
2735 ssize_t index = mInputs.indexOfKey(*input);
2736 if (index < 0) {
2737 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2738 status = BAD_VALUE;
2739 goto error;
2740 }
2741 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002742 RecordClientVector clients = inputDesc->getClientsForSession(session);
2743 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002744 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2745 status = BAD_VALUE;
2746 goto error;
2747 }
2748 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2749 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002750 // corresponds to a new client and is only permitted from the same UID.
2751 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002752 if (clients.size() > 1) {
2753 for (const auto& client : clients) {
2754 // The client map is ordered by key values (portId) and portIds are allocated
2755 // incrementaly. So the first client in this list is the one opened by audio flinger
2756 // when the mmap stream is created and should be ignored as it does not correspond
2757 // to an actual client
2758 if (client == *clients.cbegin()) {
2759 continue;
2760 }
2761 if (uid != client->uid() && !client->isSilenced()) {
2762 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2763 uid, client->portId(), client->uid());
2764 status = INVALID_OPERATION;
2765 goto error;
2766 }
Eric Laurent331679c2018-04-16 17:03:16 -07002767 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002768 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002769 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002770 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002771
Eric Laurentfecbceb2021-02-09 14:46:43 +01002772 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002773 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002774 }
2775
2776 *input = AUDIO_IO_HANDLE_NONE;
2777 *inputType = API_INPUT_INVALID;
2778
Francois Gaffie716e1432019-01-14 16:58:59 +01002779 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002780 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002781 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002782 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002783 ALOGW("%s could not find input mix for attr %s",
2784 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002785 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002786 }
jiabinc1de2df2019-05-07 14:26:40 -07002787 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2788 String8(attr->tags + strlen("addr=")),
2789 AUDIO_FORMAT_DEFAULT);
2790 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002791 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002792 __func__, attributes.source, attributes.tags);
2793 status = BAD_VALUE;
2794 goto error;
2795 }
2796
Kevin Rocard25f9b052019-02-27 15:08:54 -08002797 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2798 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2799 } else {
2800 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2801 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002802 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002803 if (explicitRoutingDevice != nullptr) {
2804 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002805 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002806 // Prevent from storing invalid requested device id in clients
2807 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002808 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002809 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2810 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002811 }
François Gaffie11d30102018-11-02 16:09:09 +01002812 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002813 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002814 status = BAD_VALUE;
2815 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002816 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002817 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2818 *inputType = API_INPUT_MIX_CAPTURE;
2819 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002820 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2821 // there is an external policy, but this input is attached to a mix of recorders,
2822 // meaning it receives audio injected into the framework, so the recorder doesn't
2823 // know about it and is therefore considered "legacy"
2824 *inputType = API_INPUT_LEGACY;
2825 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002826 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002827 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002828 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002829 } else {
2830 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002831 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002832
Eric Laurent599c7582015-12-07 18:05:55 -08002833 }
2834
François Gaffiec005e562018-11-06 15:04:49 +01002835 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002836 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002837 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002838 AudioProfileVector profiles;
2839 status_t ret = getProfilesForDevices(
2840 DeviceVector(device), profiles, flags, true /*isInput*/);
2841 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002842 const auto channels = profiles[0]->getChannels();
2843 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2844 config->channel_mask = *channels.begin();
2845 }
2846 const auto sampleRates = profiles[0]->getSampleRates();
2847 if (!sampleRates.empty() &&
2848 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2849 config->sample_rate = *sampleRates.begin();
2850 }
jiabinf1c73972022-04-14 16:28:52 -07002851 config->format = profiles[0]->getFormat();
2852 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002853 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002854 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002855
Eric Laurent8f42ea12018-08-08 09:08:25 -07002856exit:
2857
François Gaffiec005e562018-11-06 15:04:49 +01002858 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2859 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002860
Francois Gaffie716e1432019-01-14 16:58:59 +01002861 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002862 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002863 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002864
Mikhail Naganov2996f672019-04-18 12:29:59 -07002865 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002866 requestedDeviceId, attributes.source, flags,
2867 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002868 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002869 // Move (if found) effect for the client session to its input
2870 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002871 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002872
2873 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2874 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002875
Eric Laurent599c7582015-12-07 18:05:55 -08002876 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002877
2878error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002879 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002880}
2881
2882
François Gaffie11d30102018-11-02 16:09:09 +01002883audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002884 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002885 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002886 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002887 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002888 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002889{
2890 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002891 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002892 bool isSoundTrigger = false;
2893
François Gaffiec005e562018-11-06 15:04:49 +01002894 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002895 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2896 if (index >= 0) {
2897 input = mSoundTriggerSessions.valueFor(session);
2898 isSoundTrigger = true;
2899 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2900 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2901 } else {
2902 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002903 }
François Gaffiec005e562018-11-06 15:04:49 +01002904 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002905 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002906 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002907 }
2908
Carter Hsua3abb402021-10-26 11:11:20 +08002909 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2910 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2911 }
2912
Eric Laurentfe231122017-11-17 17:48:06 -08002913 // sampling rate and flags may be updated by getInputProfile
2914 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2915 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002916 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002917 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002918 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002919 // find a compatible input profile (not necessarily identical in parameters)
2920 sp<IOProfile> profile = getInputProfile(
2921 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2922 if (profile == nullptr) {
2923 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002924 }
jiabin2fd710d2022-05-02 23:20:22 +00002925
Glenn Kasten05ddca52016-02-11 08:17:12 -08002926 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002927 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002928 if (samplingRate == 0) {
2929 samplingRate = profileSamplingRate;
2930 }
Eric Laurente552edb2014-03-10 17:42:56 -07002931
Eric Laurent322b4d22015-04-03 15:57:54 -07002932 if (profile->getModuleHandle() == 0) {
2933 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002934 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002935 }
2936
Eric Laurentec376dc2021-04-08 20:41:22 +02002937 // Reuse an already opened input if a client with the same session ID already exists
2938 // on that input
2939 for (size_t i = 0; i < mInputs.size(); i++) {
2940 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2941 if (desc->mProfile != profile) {
2942 continue;
2943 }
2944 RecordClientVector clients = desc->clientsList();
2945 for (const auto &client : clients) {
2946 if (session == client->session()) {
2947 return desc->mIoHandle;
2948 }
2949 }
2950 }
2951
Eric Laurent3974e3b2017-12-07 17:58:43 -08002952 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002953 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002954 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002955 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002956 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002957 continue;
2958 }
2959 // if sound trigger, reuse input if used by other sound trigger on same session
2960 // else
2961 // reuse input if active client app is not in IDLE state
2962 //
2963 RecordClientVector clients = desc->clientsList();
2964 bool doClose = false;
2965 for (const auto& client : clients) {
2966 if (isSoundTrigger != client->isSoundTrigger()) {
2967 continue;
2968 }
2969 if (client->isSoundTrigger()) {
2970 if (session == client->session()) {
2971 return desc->mIoHandle;
2972 }
2973 continue;
2974 }
2975 if (client->active() && client->appState() != APP_STATE_IDLE) {
2976 return desc->mIoHandle;
2977 }
2978 doClose = true;
2979 }
2980 if (doClose) {
2981 closeInput(desc->mIoHandle);
2982 } else {
2983 i++;
2984 }
2985 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002986 }
2987
Eric Laurentfe231122017-11-17 17:48:06 -08002988 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002989
Eric Laurentfe231122017-11-17 17:48:06 -08002990 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2991 lConfig.sample_rate = profileSamplingRate;
2992 lConfig.channel_mask = profileChannelMask;
2993 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002994
François Gaffie11d30102018-11-02 16:09:09 +01002995 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002996
2997 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002998 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002999 (profileSamplingRate != lConfig.sample_rate) ||
3000 !audio_formats_match(profileFormat, lConfig.format) ||
3001 (profileChannelMask != lConfig.channel_mask)) {
3002 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003003 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003004 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003005 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003006 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003007 }
Eric Laurent599c7582015-12-07 18:05:55 -08003008 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003009 }
3010
Eric Laurentc722f302014-12-10 11:21:49 -08003011 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003012
Eric Laurent599c7582015-12-07 18:05:55 -08003013 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003014 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003015
Eric Laurent599c7582015-12-07 18:05:55 -08003016 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003017}
3018
Eric Laurent4eb58f12018-12-07 16:41:02 -08003019status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003020{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003021 ALOGV("%s portId %d", __FUNCTION__, portId);
3022
3023 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3024 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003026 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003027 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003028 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003029 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030 if (client->active()) {
3031 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3032 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003033 }
3034
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 audio_session_t session = client->session();
3036
Eric Laurent4eb58f12018-12-07 16:41:02 -08003037 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038
Eric Laurent4eb58f12018-12-07 16:41:02 -08003039 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003040
Eric Laurent4eb58f12018-12-07 16:41:02 -08003041 status_t status = inputDesc->start();
3042 if (status != NO_ERROR) {
3043 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003044 }
Eric Laurente552edb2014-03-10 17:42:56 -07003045
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003046 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003047 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003049
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 // indicate active capture to sound trigger service if starting capture from a mic on
3051 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003052 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003053 if (device != nullptr) {
3054 status = setInputDevice(input, device, true /* force */);
3055 } else {
3056 ALOGW("%s no new input device can be found for descriptor %d",
3057 __FUNCTION__, inputDesc->getId());
3058 status = BAD_VALUE;
3059 }
Eric Laurente552edb2014-03-10 17:42:56 -07003060
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003061 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003062 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003064 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003065 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3066 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003068 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003069
François Gaffie11d30102018-11-02 16:09:09 +01003070 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3071 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003073 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003075
Eric Laurent8f42ea12018-08-08 09:08:25 -07003076 // automatically enable the remote submix output when input is started if not
3077 // used by a policy mix of type MIX_TYPE_RECORDERS
3078 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003079 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003080 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003081 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003083 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3084 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003085 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 if (address != "") {
3087 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3088 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003089 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003090 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003091 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003092 } else if (status != NO_ERROR) {
3093 // Restore client activity state.
3094 inputDesc->setClientActive(client, false);
3095 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003096 }
3097
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003098 ALOGV("%s input %d source = %d status = %d exit",
3099 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003100
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003101 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003102}
3103
Eric Laurent8fc147b2018-07-22 19:13:55 -07003104status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003105{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003106 ALOGV("%s portId %d", __FUNCTION__, portId);
3107
3108 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3109 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003111 return BAD_VALUE;
3112 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003113 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003114 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 if (!client->active()) {
3116 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003117 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003118 }
Carter Hsue6139d52021-07-08 10:30:20 +08003119 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003121
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 inputDesc->stop();
3123 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003124 auto current_source = inputDesc->source();
3125 setInputDevice(input, getNewInputDevice(inputDesc),
3126 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003127 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003128 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003130 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003131 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3132 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003133 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003134 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003135
3136 // automatically disable the remote submix output when input is stopped if not
3137 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003138 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003139 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003140 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003141 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003142 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3143 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 }
3145 if (address != "") {
3146 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3147 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003148 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003149 }
3150 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003151 resetInputDevice(input);
3152
3153 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3154 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003155 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3156 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003157 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003158 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003159 }
3160 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003161 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003162 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003163}
3164
Eric Laurent8fc147b2018-07-22 19:13:55 -07003165void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003166{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003167 ALOGV("%s portId %d", __FUNCTION__, portId);
3168
3169 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3170 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003171 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003172 return;
3173 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003174 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003175 audio_io_handle_t input = inputDesc->mIoHandle;
3176
Eric Laurent8f42ea12018-08-08 09:08:25 -07003177 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003178
Andy Hung39efb7a2018-09-26 15:39:28 -07003179 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003180 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003181 if (inputDesc->getClientCount() > 0) {
3182 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003183 return;
3184 }
3185
Eric Laurent05b90f82014-08-27 15:32:29 -07003186 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003187 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003188 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003189}
3190
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003192{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003193 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003194
3195 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003196 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003197 }
3198}
3199
Eric Laurent8f42ea12018-08-08 09:08:25 -07003200void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3201{
3202 stopInput(portId);
3203 releaseInput(portId);
3204}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003205
Eric Laurent0dd51852019-04-19 18:18:58 -07003206void AudioPolicyManager::checkCloseInputs() {
3207 // After connecting or disconnecting an input device, close input if:
3208 // - it has no client (was just opened to check profile) OR
3209 // - none of its supported devices are connected anymore OR
3210 // - one of its clients cannot be routed to one of its supported
3211 // devices anymore. Otherwise update device selection
3212 std::vector<audio_io_handle_t> inputsToClose;
3213 for (size_t i = 0; i < mInputs.size(); i++) {
3214 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3215 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003216 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003217 inputsToClose.push_back(mInputs.keyAt(i));
3218 } else {
3219 bool close = false;
3220 for (const auto& client : input->clientsList()) {
3221 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003222 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3223 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003224 if (!input->supportedDevices().contains(device)) {
3225 close = true;
3226 break;
3227 }
3228 }
3229 if (close) {
3230 inputsToClose.push_back(mInputs.keyAt(i));
3231 } else {
3232 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3233 }
3234 }
3235 }
3236
3237 for (const audio_io_handle_t handle : inputsToClose) {
3238 ALOGV("%s closing input %d", __func__, handle);
3239 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003240 }
Eric Laurentd4692962014-05-05 18:13:44 -07003241}
3242
François Gaffie251c7f02018-11-07 10:41:08 +01003243void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003244{
3245 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003246 if (indexMin < 0 || indexMax < 0) {
3247 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3248 return;
3249 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003250 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003251
3252 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003253 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3254 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003255 continue;
3256 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003257 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003258 }
Eric Laurente552edb2014-03-10 17:42:56 -07003259}
3260
Eric Laurente0720872014-03-11 09:30:41 -07003261status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003262 int index,
3263 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003264{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003265 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003266 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3267 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3268 return NO_ERROR;
3269 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003270 ALOGV("%s: stream %s attributes=%s", __func__,
3271 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003272 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003273}
3274
Eric Laurente0720872014-03-11 09:30:41 -07003275status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003276 int *index,
3277 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003278{
François Gaffiec005e562018-11-06 15:04:49 +01003279 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3280 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003281 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003282 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003283 deviceTypes = mEngine->getOutputDevicesForStream(
3284 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003285 }
jiabin9a3361e2019-10-01 09:38:30 -07003286 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003287}
3288
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003289status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003290 int index,
3291 audio_devices_t device)
3292{
3293 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003294 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3295 if (group == VOLUME_GROUP_NONE) {
3296 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003297 return BAD_VALUE;
3298 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003299 ALOGV("%s: group %d matching with %s index %d",
3300 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003301 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003302 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003303 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003304 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3305 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3306 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3307 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003308 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3309
3310 status = setVolumeCurveIndex(index, device, curves);
3311 if (status != NO_ERROR) {
3312 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3313 return status;
3314 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003315
jiabin9a3361e2019-10-01 09:38:30 -07003316 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003317 auto curCurvAttrs = curves.getAttributes();
3318 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3319 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003320 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003321 } else if (!curves.getStreamTypes().empty()) {
3322 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003323 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003324 } else {
3325 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3326 return BAD_VALUE;
3327 }
jiabin9a3361e2019-10-01 09:38:30 -07003328 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3329 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003330
François Gaffiecfe17322018-11-07 13:41:29 +01003331 // update volume on all outputs and streams matching the following:
3332 // - The requested stream (or a stream matching for volume control) is active on the output
3333 // - The device (or devices) selected by the engine for this stream includes
3334 // the requested device
3335 // - For non default requested device, currently selected device on the output is either the
3336 // requested device or one of the devices selected by the engine for this stream
3337 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3338 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003339 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003340 for (size_t i = 0; i < mOutputs.size(); i++) {
3341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003342 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003343
jiabin9a3361e2019-10-01 09:38:30 -07003344 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3345 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003346 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003347
3348 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003349 continue;
3350 }
3351 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3352 curDevices.find(device) == curDevices.end()) {
3353 continue;
3354 }
3355 bool applyVolume = false;
3356 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3357 curSrcDevices.insert(device);
3358 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003359 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3360 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003361 } else {
3362 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3363 }
3364 if (!applyVolume) {
3365 continue; // next output
3366 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003367 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3368 // If a higher priority strategy is active, and the output is routed to a device with a
3369 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003370 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003371 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003372 // If the volume source is active with higher priority source, ensure at least Sw Muted
3373 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003374 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3375 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3376 false /*preferredDevice*/);
3377 if (activeClients.empty()) {
3378 continue;
3379 }
3380 bool isPreempted = false;
3381 bool isHigherPriority = productStrategy < strategy;
3382 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003383 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003384 ALOGV("%s: Strategy=%d (\nrequester:\n"
3385 " group %d, volumeGroup=%d attributes=%s)\n"
3386 " higher priority source active:\n"
3387 " volumeGroup=%d attributes=%s) \n"
3388 " on output %zu, bailing out", __func__, productStrategy,
3389 group, group, toString(attributes).c_str(),
3390 client->volumeSource(), toString(client->attributes()).c_str(), i);
3391 applyVolume = false;
3392 isPreempted = true;
3393 break;
3394 }
3395 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003396 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003397 applyVolume = true;
3398 }
3399 }
3400 if (isPreempted || applyVolume) {
3401 break;
3402 }
3403 }
3404 if (!applyVolume) {
3405 continue; // next output
3406 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003407 }
François Gaffieed91f582020-01-31 10:35:37 +01003408 //FIXME: workaround for truncated touch sounds
3409 // delayed volume change for system stream to be removed when the problem is
3410 // handled by system UI
3411 status_t volStatus = checkAndSetVolume(
3412 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003413 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003414 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3415 if (volStatus != NO_ERROR) {
3416 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003417 }
3418 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003419
3420 // update voice volume if the an active call route exists
3421 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3422 && (curSrcDevices.find(
3423 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3424 != curSrcDevices.end())) {
3425 bool isVoiceVolSrc;
3426 bool isBtScoVolSrc;
3427 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3428 isVoiceVolSrc, isBtScoVolSrc, __func__)
3429 && (isVoiceVolSrc || isBtScoVolSrc)) {
3430 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3431 }
3432 }
3433
François Gaffiecfe17322018-11-07 13:41:29 +01003434 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3435 return status;
3436}
3437
François Gaffieaaac0fd2018-11-22 17:56:39 +01003438status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003439 audio_devices_t device,
3440 IVolumeCurves &volumeCurves)
3441{
3442 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3443 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003444 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3445 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003446 (index > volumeCurves.getVolumeIndexMax())) {
3447 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3448 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3449 return BAD_VALUE;
3450 }
3451 if (!audio_is_output_device(device)) {
3452 return BAD_VALUE;
3453 }
3454
3455 // Force max volume if stream cannot be muted
3456 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3457
François Gaffieaaac0fd2018-11-22 17:56:39 +01003458 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003459 volumeCurves.addCurrentVolumeIndex(device, index);
3460 return NO_ERROR;
3461}
3462
3463status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3464 int &index,
3465 audio_devices_t device)
3466{
3467 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3468 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003469 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003470 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003471 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003472 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003473 }
jiabin9a3361e2019-10-01 09:38:30 -07003474 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003475}
3476
3477status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3478 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003479 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003480{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003481 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003482 return BAD_VALUE;
3483 }
jiabin9a3361e2019-10-01 09:38:30 -07003484 index = curves.getVolumeIndex(deviceTypes);
3485 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003486 return NO_ERROR;
3487}
3488
3489status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3490 int &index)
3491{
3492 index = getVolumeCurves(attr).getVolumeIndexMin();
3493 return NO_ERROR;
3494}
3495
3496status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3497 int &index)
3498{
3499 index = getVolumeCurves(attr).getVolumeIndexMax();
3500 return NO_ERROR;
3501}
3502
Eric Laurent36829f92017-04-07 19:04:42 -07003503audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003504{
3505 // select one output among several suitable for global effects.
3506 // The priority is as follows:
3507 // 1: An offloaded output. If the effect ends up not being offloadable,
3508 // AudioFlinger will invalidate the track and the offloaded output
3509 // will be closed causing the effect to be moved to a PCM output.
3510 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003511 // 3: The primary output
3512 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003513
François Gaffiec005e562018-11-06 15:04:49 +01003514 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3515 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003516 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003517
Eric Laurent36829f92017-04-07 19:04:42 -07003518 if (outputs.size() == 0) {
3519 return AUDIO_IO_HANDLE_NONE;
3520 }
Eric Laurente552edb2014-03-10 17:42:56 -07003521
Eric Laurent36829f92017-04-07 19:04:42 -07003522 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3523 bool activeOnly = true;
3524
3525 while (output == AUDIO_IO_HANDLE_NONE) {
3526 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3527 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3528 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3529
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003530 for (audio_io_handle_t output : outputs) {
3531 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003532 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003533 continue;
3534 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003535 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3536 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003537 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003538 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003539 }
3540 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003541 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003542 }
3543 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003544 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003545 }
3546 }
3547 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3548 output = outputOffloaded;
3549 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3550 output = outputDeepBuffer;
3551 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3552 output = outputPrimary;
3553 } else {
3554 output = outputs[0];
3555 }
3556 activeOnly = false;
3557 }
3558
3559 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003560 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3561 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003562 mMusicEffectOutput = output;
3563 }
3564
3565 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003566 return output;
3567}
3568
Eric Laurent36829f92017-04-07 19:04:42 -07003569audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3570{
3571 return selectOutputForMusicEffects();
3572}
3573
Eric Laurente0720872014-03-11 09:30:41 -07003574status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003575 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003576 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003577 int session,
3578 int id)
3579{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003580 if (session != AUDIO_SESSION_DEVICE) {
3581 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003582 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003583 index = mInputs.indexOfKey(io);
3584 if (index < 0) {
3585 ALOGW("registerEffect() unknown io %d", io);
3586 return INVALID_OPERATION;
3587 }
Eric Laurente552edb2014-03-10 17:42:56 -07003588 }
3589 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003590 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3591 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3592 || strategy == PRODUCT_STRATEGY_NONE));
3593 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003594}
3595
Eric Laurentc241b0d2018-11-28 09:08:49 -08003596status_t AudioPolicyManager::unregisterEffect(int id)
3597{
3598 if (mEffects.getEffect(id) == nullptr) {
3599 return INVALID_OPERATION;
3600 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003601 if (mEffects.isEffectEnabled(id)) {
3602 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3603 setEffectEnabled(id, false);
3604 }
3605 return mEffects.unregisterEffect(id);
3606}
3607
3608status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3609{
3610 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3611 if (effect == nullptr) {
3612 return INVALID_OPERATION;
3613 }
3614
3615 status_t status = mEffects.setEffectEnabled(id, enabled);
3616 if (status == NO_ERROR) {
3617 mInputs.trackEffectEnabled(effect, enabled);
3618 }
3619 return status;
3620}
3621
Eric Laurent6c796322019-04-09 14:13:17 -07003622
3623status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3624{
3625 mEffects.moveEffects(ids, io);
3626 return NO_ERROR;
3627}
3628
Eric Laurentc75307b2015-03-17 15:29:32 -07003629bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3630{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003631 auto vs = toVolumeSource(stream, false);
3632 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003633}
3634
3635bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3636{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003637 auto vs = toVolumeSource(stream, false);
3638 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003639}
3640
Eric Laurente0720872014-03-11 09:30:41 -07003641bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003642{
3643 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003644 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003645 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003646 return true;
3647 }
3648 }
3649 return false;
3650}
3651
Eric Laurent275e8e92014-11-30 15:14:47 -08003652// Register a list of custom mixes with their attributes and format.
3653// When a mix is registered, corresponding input and output profiles are
3654// added to the remote submix hw module. The profile contains only the
3655// parameters (sampling rate, format...) specified by the mix.
3656// The corresponding input remote submix device is also connected.
3657//
3658// When a remote submix device is connected, the address is checked to select the
3659// appropriate profile and the corresponding input or output stream is opened.
3660//
3661// When capture starts, getInputForAttr() will:
3662// - 1 look for a mix matching the address passed in attribtutes tags if any
3663// - 2 if none found, getDeviceForInputSource() will:
3664// - 2.1 look for a mix matching the attributes source
3665// - 2.2 if none found, default to device selection by policy rules
3666// At this time, the corresponding output remote submix device is also connected
3667// and active playback use cases can be transferred to this mix if needed when reconnecting
3668// after AudioTracks are invalidated
3669//
3670// When playback starts, getOutputForAttr() will:
3671// - 1 look for a mix matching the address passed in attribtutes tags if any
3672// - 2 if none found, look for a mix matching the attributes usage
3673// - 3 if none found, default to device and output selection by policy rules.
3674
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003675status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003676{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003677 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3678 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003679 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003680 sp<HwModule> rSubmixModule;
3681 // examine each mix's route type
3682 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003683 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003684 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3685 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3686 ALOGE("Unsupported Policy Mix %zu of %zu: "
3687 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3688 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003689 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003690 break;
3691 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003692 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3693 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003694 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003695 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3696 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003697 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003698 rSubmixModule = mHwModules.getModuleFromName(
3699 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3700 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003701 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003702 i);
3703 res = INVALID_OPERATION;
3704 break;
3705 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003706 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003707
Eric Laurent97ac8712018-07-27 18:59:02 -07003708 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003709 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003710 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003711 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003712 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3713 } else {
3714 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3715 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003716 }
François Gaffie036e1e92015-03-19 10:16:24 +01003717
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003718 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003719 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003720 res = INVALID_OPERATION;
3721 break;
3722 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003723 audio_config_t outputConfig = mix.mFormat;
3724 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003725 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3726 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003727 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3728 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003729 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003730 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3731 audio_is_linear_pcm(outputConfig.format)
3732 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003733 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003734 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3735 audio_is_linear_pcm(inputConfig.format)
3736 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003737
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003738 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003739 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003740 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003741 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003742 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003743 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003744 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003745 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3746 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003747 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003748 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003749 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003750
3751 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3752 mix.mDeviceType, mix.mDeviceAddress,
3753 String8(), AUDIO_FORMAT_DEFAULT);
3754 if (device == nullptr) {
3755 res = INVALID_OPERATION;
3756 break;
3757 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003758
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003759 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003760 // First try to find an already opened output supporting the device
3761 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003763
Eric Laurentc529cf62020-04-17 18:19:10 -07003764 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003765 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003766 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003767 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003768 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003769 } else {
3770 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003771 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003772 }
3773 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003774 // If no output found, try to find a direct output profile supporting the device
3775 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3776 sp<HwModule> module = mHwModules[i];
3777 for (size_t j = 0;
3778 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3779 j++) {
3780 sp<IOProfile> profile = module->getOutputProfiles()[j];
3781 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3782 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3783 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003784 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003785 res = INVALID_OPERATION;
3786 } else {
3787 foundOutput = true;
3788 }
3789 }
3790 }
3791 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003792 if (res != NO_ERROR) {
3793 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003794 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003795 res = INVALID_OPERATION;
3796 break;
3797 } else if (!foundOutput) {
3798 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003799 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 res = INVALID_OPERATION;
3801 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003802 } else {
3803 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003804 }
Eric Laurentc722f302014-12-10 11:21:49 -08003805 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003806 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003807 if (res != NO_ERROR) {
3808 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003809 } else if (checkOutputs) {
3810 checkForDeviceAndOutputChanges();
3811 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003812 }
3813 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003814}
3815
3816status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3817{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003818 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003819 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003820 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003821 sp<HwModule> rSubmixModule;
3822 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003823 for (const auto& mix : mixes) {
3824 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003825
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003826 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003827 rSubmixModule = mHwModules.getModuleFromName(
3828 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3829 if (rSubmixModule == 0) {
3830 res = INVALID_OPERATION;
3831 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003832 }
3833 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003834
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003835 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003836
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003837 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003838 res = INVALID_OPERATION;
3839 continue;
3840 }
3841
Kevin Rocard04ed0462019-05-02 17:53:24 -07003842 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003843 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003844 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3845 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003846 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003847 AUDIO_FORMAT_DEFAULT);
3848 if (res != OK) {
3849 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003850 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003851 }
3852 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003853 }
jiabin5740f082019-08-19 15:08:30 -07003854 rSubmixModule->removeOutputProfile(address.c_str());
3855 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003856
Kevin Rocard153f92d2018-12-18 18:33:28 -08003857 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003858 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003859 res = INVALID_OPERATION;
3860 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003861 } else {
3862 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003864 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003865 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003866 if (res == NO_ERROR && checkOutputs) {
3867 checkForDeviceAndOutputChanges();
3868 updateCallAndOutputRouting();
3869 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003870 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003871}
3872
Marvin Raminbdefaf02023-11-01 09:10:32 +01003873status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3874 if (!audio_flags::audio_mix_test_api()) {
3875 return INVALID_OPERATION;
3876 }
3877
3878 _aidl_return.clear();
3879 _aidl_return.reserve(mPolicyMixes.size());
3880 for (const auto &policyMix: mPolicyMixes) {
3881 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3882 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3883 policyMix->mCbFlags);
3884 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
3885 }
3886
3887 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3888 return OK;
3889}
3890
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003891status_t AudioPolicyManager::updatePolicyMix(
3892 const AudioMix& mix,
3893 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3894 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3895 if (res == NO_ERROR) {
3896 checkForDeviceAndOutputChanges();
3897 updateCallAndOutputRouting();
3898 }
3899 return res;
3900}
3901
Mikhail Naganov100f0122018-11-29 11:22:16 -08003902void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3903{
3904 size_t i = 0;
3905 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3906 for (const auto& fmt : mManualSurroundFormats) {
3907 if (i++ != 0) dst->append(", ");
3908 std::string sfmt;
3909 FormatConverter::toString(fmt, sfmt);
3910 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3911 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3912 }
3913}
3914
Eric Laurentc529cf62020-04-17 18:19:10 -07003915// Returns true if all devices types match the predicate and are supported by one HW module
3916bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003917 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003918 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003919 const char *context,
3920 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003921 for (size_t i = 0; i < devices.size(); i++) {
3922 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003923 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003924 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003925 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003926 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003927 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003928 return false;
3929 }
3930 }
3931 return true;
3932}
3933
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003934void AudioPolicyManager::changeOutputDevicesMuteState(
3935 const AudioDeviceTypeAddrVector& devices) {
3936 ALOGVV("%s() num devices %zu", __func__, devices.size());
3937
3938 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3939 getSoftwareOutputsForDevices(devices);
3940
3941 for (size_t i = 0; i < outputs.size(); i++) {
3942 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3943 DeviceVector prevDevices = outputDesc->devices();
3944 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3945 }
3946}
3947
3948std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3949 const AudioDeviceTypeAddrVector& devices) const
3950{
3951 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3952 DeviceVector deviceDescriptors;
3953 for (size_t j = 0; j < devices.size(); j++) {
3954 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3955 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3956 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3957 ALOGE("%s: device type %#x address %s not supported or not an output device",
3958 __func__, devices[j].mType, devices[j].getAddress());
3959 continue;
3960 }
3961 deviceDescriptors.add(desc);
3962 }
3963 for (size_t i = 0; i < mOutputs.size(); i++) {
3964 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3965 continue;
3966 }
3967 outputs.push_back(mOutputs.valueAt(i));
3968 }
3969 return outputs;
3970}
3971
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003972status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003973 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003974 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003975 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3976 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003977 }
3978 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003979 if (res != NO_ERROR) {
3980 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3981 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003982 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003983
3984 checkForDeviceAndOutputChanges();
3985 updateCallAndOutputRouting();
3986
3987 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003988}
3989
3990status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3991 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003992 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3993 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003994 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003995 __FUNCTION__, uid);
3996 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003997 }
3998
Eric Laurentc529cf62020-04-17 18:19:10 -07003999 checkForDeviceAndOutputChanges();
4000 updateCallAndOutputRouting();
4001
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004002 return res;
4003}
4004
Eric Laurent2517af32020-11-25 15:31:27 +01004005
jiabin0a488932020-08-07 17:32:40 -07004006status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4007 device_role_t role,
4008 const AudioDeviceTypeAddrVector &devices) {
4009 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4010 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004011
Eric Laurentc529cf62020-04-17 18:19:10 -07004012 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004013 return BAD_VALUE;
4014 }
jiabin0a488932020-08-07 17:32:40 -07004015 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004016 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004017 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4018 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004019 return status;
4020 }
4021
4022 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004023
4024 bool forceVolumeReeval = false;
4025 // FIXME: workaround for truncated touch sounds
4026 // to be removed when the problem is handled by system UI
4027 uint32_t delayMs = 0;
4028 if (strategy == mCommunnicationStrategy) {
4029 forceVolumeReeval = true;
4030 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4031 updateInputRouting();
4032 }
4033 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004034
4035 return NO_ERROR;
4036}
4037
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004038void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4039 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004040{
4041 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004042 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004043 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004044 // Only apply special touch sound delay once
4045 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004046 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004047 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004048 for (size_t i = 0; i < mOutputs.size(); i++) {
4049 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4050 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004051 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4052 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004053 // As done in setDeviceConnectionState, we could also fix default device issue by
4054 // preventing the force re-routing in case of default dev that distinguishes on address.
4055 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004056 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004057 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4058 // If the device is using preferred mixer attributes, the output need to reopen
4059 // with default configuration when the new selected devices are different from
4060 // current routing devices.
4061 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4062 continue;
4063 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304064
4065 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4066 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004067 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004068 // Only apply special touch sound delay once
4069 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004070 }
4071 if (forceVolumeReeval && !newDevices.isEmpty()) {
4072 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4073 }
4074 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004075 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004076 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004077}
4078
Eric Laurent2517af32020-11-25 15:31:27 +01004079void AudioPolicyManager::updateInputRouting() {
4080 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304081 // Skip for hotword recording as the input device switch
4082 // is handled within sound trigger HAL
4083 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4084 continue;
4085 }
Eric Laurent2517af32020-11-25 15:31:27 +01004086 auto newDevice = getNewInputDevice(activeDesc);
4087 // Force new input selection if the new device can not be reached via current input
4088 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4089 setInputDevice(activeDesc->mIoHandle, newDevice);
4090 } else {
4091 closeInput(activeDesc->mIoHandle);
4092 }
4093 }
4094}
4095
Paul Wang5d7cdb52022-11-22 09:45:06 +00004096status_t
4097AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4098 device_role_t role,
4099 const AudioDeviceTypeAddrVector &devices) {
4100 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4101 dumpAudioDeviceTypeAddrVector(devices).c_str());
4102
Eric Laurent78fedbf2023-03-09 14:40:44 +01004103 if (!areAllDevicesSupported(
4104 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004105 return BAD_VALUE;
4106 }
4107 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4108 if (status != NO_ERROR) {
4109 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4110 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4111 return status;
4112 }
4113
4114 checkForDeviceAndOutputChanges();
4115
4116 bool forceVolumeReeval = false;
4117 // TODO(b/263479999): workaround for truncated touch sounds
4118 // to be removed when the problem is handled by system UI
4119 uint32_t delayMs = 0;
4120 if (strategy == mCommunnicationStrategy) {
4121 forceVolumeReeval = true;
4122 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4123 updateInputRouting();
4124 }
4125 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4126
4127 return NO_ERROR;
4128}
4129
4130status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4131 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004132{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004133 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004134
Paul Wang5d7cdb52022-11-22 09:45:06 +00004135 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004136 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004137 ALOGW_IF(status != NAME_NOT_FOUND,
4138 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004139 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004140 return status;
4141 }
4142
4143 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004144
4145 bool forceVolumeReeval = false;
4146 // FIXME: workaround for truncated touch sounds
4147 // to be removed when the problem is handled by system UI
4148 uint32_t delayMs = 0;
4149 if (strategy == mCommunnicationStrategy) {
4150 forceVolumeReeval = true;
4151 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4152 updateInputRouting();
4153 }
4154 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004155
4156 return NO_ERROR;
4157}
4158
jiabin0a488932020-08-07 17:32:40 -07004159status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4160 device_role_t role,
4161 AudioDeviceTypeAddrVector &devices) {
4162 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004163}
4164
Jiabin Huang3b98d322020-09-03 17:54:16 +00004165status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4166 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4167 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4168 dumpAudioDeviceTypeAddrVector(devices).c_str());
4169
Mikhail Naganov55773032020-10-01 15:08:13 -07004170 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004171 return BAD_VALUE;
4172 }
4173 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4174 ALOGW_IF(status != NO_ERROR,
4175 "Engine could not set preferred devices %s for audio source %d role %d",
4176 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4177
4178 return status;
4179}
4180
4181status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4182 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4183 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4184 dumpAudioDeviceTypeAddrVector(devices).c_str());
4185
Mikhail Naganov55773032020-10-01 15:08:13 -07004186 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004187 return BAD_VALUE;
4188 }
4189 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4190 ALOGW_IF(status != NO_ERROR,
4191 "Engine could not add preferred devices %s for audio source %d role %d",
4192 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4193
Eric Laurent2517af32020-11-25 15:31:27 +01004194 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004195 return status;
4196}
4197
4198status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4199 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4200{
4201 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4202 dumpAudioDeviceTypeAddrVector(devices).c_str());
4203
Eric Laurent78fedbf2023-03-09 14:40:44 +01004204 if (!areAllDevicesSupported(
4205 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004206 return BAD_VALUE;
4207 }
4208
4209 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4210 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004211 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004212 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004213 if (status == NO_ERROR) {
4214 updateInputRouting();
4215 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004216 return status;
4217}
4218
4219status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4220 device_role_t role) {
4221 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4222
4223 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004224 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004225 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004226 if (status == NO_ERROR) {
4227 updateInputRouting();
4228 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004229 return status;
4230}
4231
4232status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4233 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4234 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4235}
4236
Oscar Azucena90e77632019-11-27 17:12:28 -08004237status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004238 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004239 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004240 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4241 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004242 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004243 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4244 if (status != NO_ERROR) {
4245 ALOGE("%s() could not set device affinity for userId %d",
4246 __FUNCTION__, userId);
4247 return status;
4248 }
4249
4250 // reevaluate outputs for all devices
4251 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004252 changeOutputDevicesMuteState(devices);
4253 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4254 true /* skipDelays */);
4255 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004256
4257 return NO_ERROR;
4258}
4259
4260status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004261 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004262 AudioDeviceTypeAddrVector devices;
4263 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004264 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4265 if (status != NO_ERROR) {
4266 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4267 __FUNCTION__, userId);
4268 return status;
4269 }
4270
4271 // reevaluate outputs for all devices
4272 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004273 changeOutputDevicesMuteState(devices);
4274 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4275 true /* skipDelays */);
4276 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004277
4278 return NO_ERROR;
4279}
4280
Andy Hungc29d82b2018-10-05 12:23:17 -07004281void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004282{
Andy Hungc29d82b2018-10-05 12:23:17 -07004283 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004284 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004285 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004286 std::string stateLiteral;
4287 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004288 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004289 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4290 "communications", "media", "record", "dock", "system",
4291 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4292 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4293 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004294 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4295 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4296 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4297 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4298 dst->append(" (MANUAL: ");
4299 dumpManualSurroundFormats(dst);
4300 dst->append(")");
4301 }
4302 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004303 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004304 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4305 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004306 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004307 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004308
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004309 dst->append("\n");
4310 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4311 dst->append("\n");
4312 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004313 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004314 mOutputs.dump(dst);
4315 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004316 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004317 mAudioPatches.dump(dst);
4318 mPolicyMixes.dump(dst);
4319 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004320
Kevin Rocardb99cc752019-03-21 20:52:24 -07004321 dst->appendFormat(" AllowedCapturePolicies:\n");
4322 for (auto& policy : mAllowedCapturePolicies) {
4323 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4324 }
4325
jiabina84c3d32022-12-02 18:59:55 +00004326 dst->appendFormat(" Preferred mixer audio configuration:\n");
4327 for (const auto it : mPreferredMixerAttrInfos) {
4328 dst->appendFormat(" - device port id: %d\n", it.first);
4329 for (const auto preferredMixerInfoIt : it.second) {
4330 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4331 preferredMixerInfoIt.second->dump(dst);
4332 }
4333 }
4334
François Gaffiec005e562018-11-06 15:04:49 +01004335 dst->appendFormat("\nPolicy Engine dump:\n");
4336 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004337}
4338
4339status_t AudioPolicyManager::dump(int fd)
4340{
4341 String8 result;
4342 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004343 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004344 return NO_ERROR;
4345}
4346
Kevin Rocardb99cc752019-03-21 20:52:24 -07004347status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4348{
4349 mAllowedCapturePolicies[uid] = capturePolicy;
4350 return NO_ERROR;
4351}
4352
Eric Laurente552edb2014-03-10 17:42:56 -07004353// This function checks for the parameters which can be offloaded.
4354// This can be enhanced depending on the capability of the DSP and policy
4355// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004356audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004357{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004358 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004359 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004360 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004361 offloadInfo.format,
4362 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4363 offloadInfo.has_video);
4364
jiabin2b9d5a12021-12-10 01:06:29 +00004365 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004366 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004367 }
4368
4369 // See if there is a profile to support this.
4370 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004371 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004372 offloadInfo.sample_rate,
4373 offloadInfo.format,
4374 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004375 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4376 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004377 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4378 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4379 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004380 if (profile == nullptr) {
4381 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4382 }
4383 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4384 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4385 }
4386 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004387}
4388
Michael Chana94fbb22018-04-24 14:31:19 +10004389bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4390 const audio_attributes_t& attributes) {
4391 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004392 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004393 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4394 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004395 config.sample_rate,
4396 config.format,
4397 config.channel_mask,
4398 output_flags,
4399 true /* directOnly */);
4400 ALOGV("%s() profile %sfound with name: %s, "
4401 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4402 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004403 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004404 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004405
4406 // also try the MSD module if compatible profile not found
4407 if (profile == nullptr) {
4408 profile = getMsdProfileForOutput(outputDevices,
4409 config.sample_rate,
4410 config.format,
4411 config.channel_mask,
4412 output_flags,
4413 true /* directOnly */);
4414 ALOGV("%s() MSD profile %sfound with name: %s, "
4415 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4416 __FUNCTION__, profile != 0 ? "" : "NOT ",
4417 (profile != 0 ? profile->getTagName().c_str() : "null"),
4418 config.sample_rate, config.format, config.channel_mask, output_flags);
4419 }
4420 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004421}
4422
jiabin2b9d5a12021-12-10 01:06:29 +00004423bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4424 bool durationIgnored) {
4425 if (mMasterMono) {
4426 return false; // no offloading if mono is set.
4427 }
4428
4429 // Check if offload has been disabled
4430 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4431 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4432 return false;
4433 }
4434
4435 // Check if stream type is music, then only allow offload as of now.
4436 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4437 {
4438 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4439 return false;
4440 }
4441
4442 //TODO: enable audio offloading with video when ready
4443 const bool allowOffloadWithVideo =
4444 property_get_bool("audio.offload.video", false /* default_value */);
4445 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4446 ALOGV("%s: has_video == true, returning false", __func__);
4447 return false;
4448 }
4449
4450 //If duration is less than minimum value defined in property, return false
4451 const int min_duration_secs = property_get_int32(
4452 "audio.offload.min.duration.secs", -1 /* default_value */);
4453 if (!durationIgnored) {
4454 if (min_duration_secs >= 0) {
4455 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4456 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4457 __func__, min_duration_secs);
4458 return false;
4459 }
4460 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4461 ALOGV("%s: Offload denied by duration < default min(=%u)",
4462 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4463 return false;
4464 }
4465 }
4466
4467 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4468 // creating an offloaded track and tearing it down immediately after start when audioflinger
4469 // detects there is an active non offloadable effect.
4470 // FIXME: We should check the audio session here but we do not have it in this context.
4471 // This may prevent offloading in rare situations where effects are left active by apps
4472 // in the background.
4473 if (mEffects.isNonOffloadableEffectEnabled()) {
4474 return false;
4475 }
4476
4477 return true;
4478}
4479
4480audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4481 const audio_config_t *config) {
4482 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4483 offloadInfo.format = config->format;
4484 offloadInfo.sample_rate = config->sample_rate;
4485 offloadInfo.channel_mask = config->channel_mask;
4486 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4487 offloadInfo.has_video = false;
4488 offloadInfo.is_streaming = false;
4489 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4490
4491 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4492 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4493 audio_flags_to_audio_output_flags(attr->flags, &flags);
4494 // only retain flags that will drive compressed offload or passthrough
4495 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4496 if (offloadPossible) {
4497 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4498 }
4499 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4500
Dorin Drimusfae3c642022-03-17 18:36:30 +01004501 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004502 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004503 DeviceVector outputDevices = engineOutputDevices;
4504 // the MSD module checks for different conditions and output devices
4505 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4506 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4507 continue;
4508 }
4509 outputDevices = getMsdAudioOutDevices();
4510 }
jiabin2b9d5a12021-12-10 01:06:29 +00004511 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004512 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004513 config->sample_rate, nullptr /*updatedSamplingRate*/,
4514 config->format, nullptr /*updatedFormat*/,
4515 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004516 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004517 continue;
4518 }
4519 // reject profiles not corresponding to a device currently available
4520 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4521 continue;
4522 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004523 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4524 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004525 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004526 != AUDIO_DIRECT_NOT_SUPPORTED) {
4527 // Already reports offload gapless supported. No need to report offload support.
4528 continue;
4529 }
4530 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4531 != AUDIO_OUTPUT_FLAG_NONE) {
4532 // If offload gapless is reported, no need to report offload support.
4533 directMode = (audio_direct_mode_t) ((directMode &
4534 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4535 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4536 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004537 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004538 }
4539 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004540 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004541 }
4542 }
4543 }
4544 return directMode;
4545}
4546
Dorin Drimusf2196d82022-01-03 12:11:18 +01004547status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4548 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004549 if (mEffects.isNonOffloadableEffectEnabled()) {
4550 return OK;
4551 }
jiabinf1c73972022-04-14 16:28:52 -07004552 DeviceVector devices;
4553 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004554 if (status != OK) {
4555 return status;
4556 }
4557 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4558 if (devices.empty()) {
4559 return OK; // no output devices for the attributes
4560 }
jiabinf1c73972022-04-14 16:28:52 -07004561 return getProfilesForDevices(devices, audioProfilesVector,
4562 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004563}
4564
jiabina84c3d32022-12-02 18:59:55 +00004565status_t AudioPolicyManager::getSupportedMixerAttributes(
4566 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4567 ALOGV("%s, portId=%d", __func__, portId);
4568 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4569 if (deviceDescriptor == nullptr) {
4570 ALOGE("%s the requested device is currently unavailable", __func__);
4571 return BAD_VALUE;
4572 }
jiabin96daffc2023-05-11 17:51:55 +00004573 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4574 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4575 deviceDescriptor->type());
4576 return BAD_VALUE;
4577 }
jiabina84c3d32022-12-02 18:59:55 +00004578 for (const auto& hwModule : mHwModules) {
4579 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4580 if (curProfile->supportsDevice(deviceDescriptor)) {
4581 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4582 }
4583 }
4584 }
4585 return NO_ERROR;
4586}
4587
4588status_t AudioPolicyManager::setPreferredMixerAttributes(
4589 const audio_attributes_t *attr,
4590 audio_port_handle_t portId,
4591 uid_t uid,
4592 const audio_mixer_attributes_t *mixerAttributes) {
4593 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4594 "mixerBehavior=%d}, uid=%d, portId=%u",
4595 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4596 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4597 mixerAttributes->mixer_behavior, uid, portId);
4598 if (attr->usage != AUDIO_USAGE_MEDIA) {
4599 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4600 return BAD_VALUE;
4601 }
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 }
4607 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4608 ALOGE("%s(%d), type=%d, is not a usb output device",
4609 __func__, portId, deviceDescriptor->type());
4610 return BAD_VALUE;
4611 }
4612
4613 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4614 audio_flags_to_audio_output_flags(attr->flags, &flags);
4615 flags = (audio_output_flags_t) (flags |
4616 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4617 sp<IOProfile> profile = nullptr;
4618 DeviceVector devices(deviceDescriptor);
4619 for (const auto& hwModule : mHwModules) {
4620 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4621 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004622 && curProfile->getCompatibilityScore(
4623 devices,
4624 mixerAttributes->config.sample_rate,
4625 nullptr /*updatedSamplingRate*/,
4626 mixerAttributes->config.format,
4627 nullptr /*updatedFormat*/,
4628 mixerAttributes->config.channel_mask,
4629 nullptr /*updatedChannelMask*/,
4630 flags,
4631 false /*exactMatchRequiredForInputFlags*/)
4632 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004633 profile = curProfile;
4634 break;
4635 }
4636 }
4637 }
4638 if (profile == nullptr) {
4639 ALOGE("%s, there is no compatible profile found", __func__);
4640 return BAD_VALUE;
4641 }
4642
4643 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4644 sp<PreferredMixerAttributesInfo>::make(
4645 uid, portId, profile, flags, *mixerAttributes);
4646 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4647 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4648
4649 // If 1) there is any client from the preferred mixer configuration owner that is currently
4650 // active and matches the strategy and 2) current output is on the preferred device and the
4651 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4652 // configuration.
4653 std::vector<audio_io_handle_t> outputsToReopen;
4654 for (size_t i = 0; i < mOutputs.size(); i++) {
4655 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004656 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4657 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4658 output->mUsePreferredMixerAttributes = true;
4659 } else {
4660 for (const auto &client: output->getActiveClients()) {
4661 if (client->uid() == uid && client->strategy() == strategy) {
4662 client->setIsInvalid();
4663 outputsToReopen.push_back(output->mIoHandle);
4664 }
jiabina84c3d32022-12-02 18:59:55 +00004665 }
4666 }
4667 }
4668 }
4669 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4670 config.sample_rate = mixerAttributes->config.sample_rate;
4671 config.channel_mask = mixerAttributes->config.channel_mask;
4672 config.format = mixerAttributes->config.format;
4673 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004674 sp<SwAudioOutputDescriptor> desc =
4675 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4676 if (desc == nullptr) {
4677 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4678 continue;
4679 }
4680 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004681 }
4682
4683 return NO_ERROR;
4684}
4685
4686sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004687 audio_port_handle_t devicePortId,
4688 product_strategy_t strategy,
4689 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004690 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4691 if (it == mPreferredMixerAttrInfos.end()) {
4692 return nullptr;
4693 }
jiabind9a58d32023-06-01 17:57:30 +00004694 if (activeBitPerfectPreferred) {
4695 for (auto [strategy, info] : it->second) {
4696 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4697 && info->getActiveClientCount() != 0) {
4698 return info;
4699 }
4700 }
jiabina84c3d32022-12-02 18:59:55 +00004701 }
jiabind9a58d32023-06-01 17:57:30 +00004702 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4703 return strategyMatchedMixerAttrInfoIt == it->second.end()
4704 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004705}
4706
4707status_t AudioPolicyManager::getPreferredMixerAttributes(
4708 const audio_attributes_t *attr,
4709 audio_port_handle_t portId,
4710 audio_mixer_attributes_t* mixerAttributes) {
4711 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4712 portId, mEngine->getProductStrategyForAttributes(*attr));
4713 if (info == nullptr) {
4714 return NAME_NOT_FOUND;
4715 }
4716 *mixerAttributes = info->getMixerAttributes();
4717 return NO_ERROR;
4718}
4719
4720status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4721 audio_port_handle_t portId,
4722 uid_t uid) {
4723 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4724 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4725 if (preferredMixerAttrInfo == nullptr) {
4726 return NAME_NOT_FOUND;
4727 }
4728 if (preferredMixerAttrInfo->getUid() != uid) {
4729 ALOGE("%s, requested uid=%d, owned uid=%d",
4730 __func__, uid, preferredMixerAttrInfo->getUid());
4731 return PERMISSION_DENIED;
4732 }
4733 mPreferredMixerAttrInfos[portId].erase(strategy);
4734 if (mPreferredMixerAttrInfos[portId].empty()) {
4735 mPreferredMixerAttrInfos.erase(portId);
4736 }
4737
4738 // Reconfig existing output
4739 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4740 for (size_t i = 0; i < mOutputs.size(); i++) {
4741 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4742 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4743 }
4744 }
4745 for (const auto output : potentialOutputsToReopen) {
4746 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4747 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4748 preferredMixerAttrInfo->getFlags())) {
4749 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4750 }
4751 }
4752 return NO_ERROR;
4753}
4754
Eric Laurent6a94d692014-05-20 11:18:06 -07004755status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4756 audio_port_type_t type,
4757 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004758 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 unsigned int *generation)
4760{
jiabin19cdba52020-11-24 11:28:58 -08004761 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4762 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 return BAD_VALUE;
4764 }
4765 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004766 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 *num_ports = 0;
4768 }
4769
4770 size_t portsWritten = 0;
4771 size_t portsMax = *num_ports;
4772 *num_ports = 0;
4773 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004774 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4775 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004777 for (const auto& dev : mAvailableOutputDevices) {
4778 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004779 continue;
4780 }
4781 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004782 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004783 }
4784 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004786 }
4787 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004788 for (const auto& dev : mAvailableInputDevices) {
4789 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004790 continue;
4791 }
4792 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004793 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004794 }
4795 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004796 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 }
4798 }
4799 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4800 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4801 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4802 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4803 }
4804 *num_ports += mInputs.size();
4805 }
4806 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004807 size_t numOutputs = 0;
4808 for (size_t i = 0; i < mOutputs.size(); i++) {
4809 if (!mOutputs[i]->isDuplicated()) {
4810 numOutputs++;
4811 if (portsWritten < portsMax) {
4812 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4813 }
4814 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004815 }
Eric Laurent84c70242014-06-23 08:46:27 -07004816 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 }
4818 }
jiabina84c3d32022-12-02 18:59:55 +00004819
Eric Laurent6a94d692014-05-20 11:18:06 -07004820 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004821 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004822 return NO_ERROR;
4823}
4824
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004825status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4826 std::vector<media::AudioPortFw>* _aidl_return) {
4827 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4828 audio_port_v7 port;
4829 dev->toAudioPort(&port);
4830 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4831 _aidl_return->push_back(std::move(aidlPort));
4832 return OK;
4833 };
4834
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004835 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004836 for (const auto& dev : module->getDeclaredDevices()) {
4837 if (role == media::AudioPortRole::NONE ||
4838 ((role == media::AudioPortRole::SOURCE)
4839 == audio_is_input_device(dev->type()))) {
4840 RETURN_STATUS_IF_ERROR(pushPort(dev));
4841 }
4842 }
4843 }
4844 return OK;
4845}
4846
jiabin19cdba52020-11-24 11:28:58 -08004847status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004848{
Eric Laurent99fcae42018-05-17 16:59:18 -07004849 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4850 return BAD_VALUE;
4851 }
4852 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4853 if (dev != 0) {
4854 dev->toAudioPort(port);
4855 return NO_ERROR;
4856 }
4857 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4858 if (dev != 0) {
4859 dev->toAudioPort(port);
4860 return NO_ERROR;
4861 }
4862 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4863 if (out != 0) {
4864 out->toAudioPort(port);
4865 return NO_ERROR;
4866 }
4867 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4868 if (in != 0) {
4869 in->toAudioPort(port);
4870 return NO_ERROR;
4871 }
4872 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004873}
4874
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004875status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4876 audio_patch_handle_t *handle,
4877 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004878{
François Gaffieafd4cea2019-11-18 15:50:22 +01004879 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004880 if (handle == NULL || patch == NULL) {
4881 return BAD_VALUE;
4882 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004883 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004884 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004885 return BAD_VALUE;
4886 }
4887 // only one source per audio patch supported for now
4888 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 return INVALID_OPERATION;
4890 }
Eric Laurent874c42872014-08-08 15:13:39 -07004891 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004892 return INVALID_OPERATION;
4893 }
Eric Laurent874c42872014-08-08 15:13:39 -07004894 for (size_t i = 0; i < patch->num_sinks; i++) {
4895 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4896 return INVALID_OPERATION;
4897 }
4898 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004899
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004900 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4901 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4902 if (srcDevice == nullptr || sinkDevice == nullptr) {
4903 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4904 return BAD_VALUE;
4905 }
4906 ALOGV("%s between source %s and sink %s", __func__,
4907 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4908 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4909 // Default attributes, default volume priority, not to infer with non raw audio patches.
4910 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4911 const struct audio_port_config *source = &patch->sources[0];
4912 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004913 new SourceClientDescriptor(
4914 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4915 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4916 true);
4917 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004918
4919 status_t status =
4920 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4921
4922 if (status != NO_ERROR) {
4923 return INVALID_OPERATION;
4924 }
4925 mAudioSources.add(portId, sourceDesc);
4926 return NO_ERROR;
4927}
4928
4929status_t AudioPolicyManager::connectAudioSourceToSink(
4930 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4931 const struct audio_patch *patch,
4932 audio_patch_handle_t &handle,
4933 uid_t uid, uint32_t delayMs)
4934{
4935 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4936 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4937 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4938 return INVALID_OPERATION;
4939 }
4940 sourceDesc->connect(handle, sinkDevice);
4941 if (isMsdPatch(handle)) {
4942 return NO_ERROR;
4943 }
4944 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4945 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4946 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4947 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4948 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4949 goto FailurePatchAdded;
4950 }
4951 status = swOutput->start();
4952 if (status != NO_ERROR) {
4953 goto FailureSourceAdded;
4954 }
4955 swOutput->addClient(sourceDesc);
4956 status = startSource(swOutput, sourceDesc, &delayMs);
4957 if (status != NO_ERROR) {
4958 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4959 goto FailureSourceActive;
4960 }
4961 if (delayMs != 0) {
4962 usleep(delayMs * 1000);
4963 }
4964 return NO_ERROR;
4965
4966FailureSourceActive:
4967 swOutput->stop();
4968 releaseOutput(sourceDesc->portId());
4969FailureSourceAdded:
4970 sourceDesc->setSwOutput(nullptr);
4971FailurePatchAdded:
4972 releaseAudioPatchInternal(handle);
4973 return INVALID_OPERATION;
4974}
4975
4976status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4977 audio_patch_handle_t *handle,
4978 uid_t uid, uint32_t delayMs,
4979 const sp<SourceClientDescriptor>& sourceDesc)
4980{
4981 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 sp<AudioPatch> patchDesc;
4983 ssize_t index = mAudioPatches.indexOfKey(*handle);
4984
François Gaffieafd4cea2019-11-18 15:50:22 +01004985 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4986 patch->sources[0].role,
4987 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004988#if LOG_NDEBUG == 0
4989 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4991 patch->sinks[i].role,
4992 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004993 }
4994#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004995
4996 if (index >= 0) {
4997 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004998 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4999 __func__, mUidCached, patchDesc->getUid(), uid);
5000 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 return INVALID_OPERATION;
5002 }
5003 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005004 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 }
5006
5007 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005008 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005010 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 return BAD_VALUE;
5012 }
Eric Laurent84c70242014-06-23 08:46:27 -07005013 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5014 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 if (patchDesc != 0) {
5016 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005017 ALOGV("%s source id differs for patch current id %d new id %d",
5018 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005019 return BAD_VALUE;
5020 }
5021 }
Eric Laurent874c42872014-08-08 15:13:39 -07005022 DeviceVector devices;
5023 for (size_t i = 0; i < patch->num_sinks; i++) {
5024 // Only support mix to devices connection
5025 // TODO add support for mix to mix connection
5026 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005027 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005028 return INVALID_OPERATION;
5029 }
5030 sp<DeviceDescriptor> devDesc =
5031 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5032 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005033 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005034 return BAD_VALUE;
5035 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005036
jiabin66acc432024-02-06 00:57:36 +00005037 if (outputDesc->mProfile->getCompatibilityScore(
5038 DeviceVector(devDesc),
5039 patch->sources[0].sample_rate,
5040 nullptr, // updatedSamplingRate
5041 patch->sources[0].format,
5042 nullptr, // updatedFormat
5043 patch->sources[0].channel_mask,
5044 nullptr, // updatedChannelMask
5045 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005046 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005047 return INVALID_OPERATION;
5048 }
5049 devices.add(devDesc);
5050 }
5051 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 return INVALID_OPERATION;
5053 }
Eric Laurent874c42872014-08-08 15:13:39 -07005054
Eric Laurent6a94d692014-05-20 11:18:06 -07005055 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005056 ALOGV("%s setting device %s on output %d",
5057 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305058 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 index = mAudioPatches.indexOfKey(*handle);
5060 if (index >= 0) {
5061 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005062 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005063 }
5064 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 patchDesc->setUid(uid);
5066 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005067 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005068 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 return INVALID_OPERATION;
5070 }
5071 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5072 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5073 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005074 // only one sink supported when connecting an input device to a mix
5075 if (patch->num_sinks > 1) {
5076 return INVALID_OPERATION;
5077 }
François Gaffie53615e22015-03-19 09:24:12 +01005078 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 if (inputDesc == NULL) {
5080 return BAD_VALUE;
5081 }
5082 if (patchDesc != 0) {
5083 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5084 return BAD_VALUE;
5085 }
5086 }
François Gaffie11d30102018-11-02 16:09:09 +01005087 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005088 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005089 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005090 return BAD_VALUE;
5091 }
5092
jiabin66acc432024-02-06 00:57:36 +00005093 if (inputDesc->mProfile->getCompatibilityScore(
5094 DeviceVector(device),
5095 patch->sinks[0].sample_rate,
5096 nullptr, /*updatedSampleRate*/
5097 patch->sinks[0].format,
5098 nullptr, /*updatedFormat*/
5099 patch->sinks[0].channel_mask,
5100 nullptr, /*updatedChannelMask*/
5101 // FIXME for the parameter type,
5102 // and the NONE
5103 (audio_output_flags_t)
5104 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005105 return INVALID_OPERATION;
5106 }
5107 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005108 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005109 device->toString().c_str(), inputDesc->mIoHandle);
5110 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005111 index = mAudioPatches.indexOfKey(*handle);
5112 if (index >= 0) {
5113 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005114 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005115 }
5116 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005117 patchDesc->setUid(uid);
5118 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005120 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 return INVALID_OPERATION;
5122 }
5123 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5124 // device to device connection
5125 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005126 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005127 return BAD_VALUE;
5128 }
5129 }
François Gaffie11d30102018-11-02 16:09:09 +01005130 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005131 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005132 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005133 return BAD_VALUE;
5134 }
Eric Laurent874c42872014-08-08 15:13:39 -07005135
Eric Laurent6a94d692014-05-20 11:18:06 -07005136 //update source and sink with our own data as the data passed in the patch may
5137 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005138 PatchBuilder patchBuilder;
5139 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005140
5141 // if first sink is to MSD, establish single MSD patch
5142 if (getMsdAudioOutDevices().contains(
5143 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5144 ALOGV("%s patching to MSD", __FUNCTION__);
5145 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5146 goto installPatch;
5147 }
5148
François Gaffieafd4cea2019-11-18 15:50:22 +01005149 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5150 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005151
Eric Laurent874c42872014-08-08 15:13:39 -07005152 for (size_t i = 0; i < patch->num_sinks; i++) {
5153 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005154 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005155 return INVALID_OPERATION;
5156 }
François Gaffie11d30102018-11-02 16:09:09 +01005157 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005158 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005159 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005160 return BAD_VALUE;
5161 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005162 audio_port_config sinkPortConfig = {};
5163 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5164 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005165
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005166 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5167 // volume management purpose (tracking activity)
5168 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5169 // in config XML to reach the sink so that is can be declared as available.
5170 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005171 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005172 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005173 // take care of dynamic routing for SwOutput selection,
5174 audio_attributes_t attributes = sourceDesc->attributes();
5175 audio_stream_type_t stream = sourceDesc->stream();
5176 audio_attributes_t resultAttr;
5177 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5178 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005179 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5180 config.channel_mask =
5181 (audio_channel_mask_get_representation(sourceMask)
5182 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5183 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005184 config.format = sourceDesc->config().format;
5185 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5186 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5187 bool isRequestedDeviceForExclusiveUse = false;
5188 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005189 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005190 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005191 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5192 &stream, sourceDesc->uid(), &config, &flags,
5193 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005194 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005195 if (output == AUDIO_IO_HANDLE_NONE) {
5196 ALOGV("%s no output for device %s",
5197 __FUNCTION__, sinkDevice->toString().c_str());
5198 return INVALID_OPERATION;
5199 }
5200 outputDesc = mOutputs.valueFor(output);
5201 if (outputDesc->isDuplicated()) {
5202 ALOGE("%s output is duplicated", __func__);
5203 return INVALID_OPERATION;
5204 }
François Gaffie7e39df22022-04-26 12:48:49 +02005205 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5206 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005207 } else {
5208 // Same for "raw patches" aka created from createAudioPatch API
5209 SortedVector<audio_io_handle_t> outputs =
5210 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5211 // if the sink device is reachable via an opened output stream, request to
5212 // go via this output stream by adding a second source to the patch
5213 // description
5214 output = selectOutput(outputs);
5215 if (output == AUDIO_IO_HANDLE_NONE) {
5216 ALOGE("%s no output available for internal patch sink", __func__);
5217 return INVALID_OPERATION;
5218 }
5219 outputDesc = mOutputs.valueFor(output);
5220 if (outputDesc->isDuplicated()) {
5221 ALOGV("%s output for device %s is duplicated",
5222 __func__, sinkDevice->toString().c_str());
5223 return INVALID_OPERATION;
5224 }
François Gaffie7e39df22022-04-26 12:48:49 +02005225 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005226 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005227 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005228 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005229 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005230 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005231 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5232 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005233 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5234 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005235 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005236 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005237 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005238 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005239 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005240 return INVALID_OPERATION;
5241 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005242 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005243 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005244 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005245 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005246 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005247 srcMixPortConfig.ext.mix.usecase.stream =
5248 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005249 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5250 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005251 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005252 }
Eric Laurent83b88082014-06-20 18:31:16 -07005253 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 }
5255 // TODO: check from routing capabilities in config file and other conflicting patches
5256
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005257installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 status_t status = installPatch(
5259 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005260 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005261 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 return INVALID_OPERATION;
5263 }
5264 } else {
5265 return BAD_VALUE;
5266 }
5267 } else {
5268 return BAD_VALUE;
5269 }
5270 return NO_ERROR;
5271}
5272
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005273status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005274{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005275 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 ssize_t index = mAudioPatches.indexOfKey(handle);
5277
5278 if (index < 0) {
5279 return BAD_VALUE;
5280 }
5281 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005282 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5283 __func__, mUidCached, patchDesc->getUid(), uid);
5284 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 return INVALID_OPERATION;
5286 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005287 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5288 for (size_t i = 0; i < mAudioSources.size(); i++) {
5289 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5290 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5291 portId = sourceDesc->portId();
5292 break;
5293 }
5294 }
5295 return portId != AUDIO_PORT_HANDLE_NONE ?
5296 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005297}
Eric Laurent6a94d692014-05-20 11:18:06 -07005298
François Gaffieafd4cea2019-11-18 15:50:22 +01005299status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005300 uint32_t delayMs,
5301 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005302{
5303 ALOGV("%s patch %d", __func__, handle);
5304 if (mAudioPatches.indexOfKey(handle) < 0) {
5305 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5306 return BAD_VALUE;
5307 }
5308 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005310 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005312 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005314 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005315 return BAD_VALUE;
5316 }
5317
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305318 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005319 getNewOutputDevices(outputDesc, true /*fromCache*/),
5320 true,
5321 0,
5322 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5324 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005325 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005327 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005328 return BAD_VALUE;
5329 }
5330 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005331 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 true,
5333 NULL);
5334 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005335 status_t status =
5336 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5337 ALOGV("%s patch panel returned %d patchHandle %d",
5338 __func__, status, patchDesc->getAfHandle());
5339 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005341 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005342 // SW or HW Bridge
5343 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5344 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005345 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005346 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5347 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5348 outputDesc = sourceDesc->swOutput().promote();
5349 }
5350 if (outputDesc == nullptr) {
5351 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5352 // releaseOutput has already called closeOutput in case of direct output
5353 return NO_ERROR;
5354 }
François Gaffie7e39df22022-04-26 12:48:49 +02005355 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005356 // While using a HwBridge, force reconsidering device only if not reusing an existing
5357 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005358 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005359 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5360 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5361 // Reconsider device only for cases:
5362 // 1 / Active Output
5363 // 2 / Inactive Output previously hosting HwBridge
5364 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5365 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5366 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305367 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005368 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5369 outputDesc->devices(),
5370 force,
5371 0,
5372 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 } else {
5374 return BAD_VALUE;
5375 }
5376 } else {
5377 return BAD_VALUE;
5378 }
5379 return NO_ERROR;
5380}
5381
5382status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5383 struct audio_patch *patches,
5384 unsigned int *generation)
5385{
François Gaffie53615e22015-03-19 09:24:12 +01005386 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 return BAD_VALUE;
5388 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005389 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005390 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005391}
5392
Eric Laurente1715a42014-05-20 11:30:42 -07005393status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005394{
Eric Laurente1715a42014-05-20 11:30:42 -07005395 ALOGV("setAudioPortConfig()");
5396
5397 if (config == NULL) {
5398 return BAD_VALUE;
5399 }
5400 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5401 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005402 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5403 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005404 }
5405
Eric Laurenta121f902014-06-03 13:32:54 -07005406 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005407 if (config->type == AUDIO_PORT_TYPE_MIX) {
5408 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005409 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005410 if (outputDesc == NULL) {
5411 return BAD_VALUE;
5412 }
Eric Laurent84c70242014-06-23 08:46:27 -07005413 ALOG_ASSERT(!outputDesc->isDuplicated(),
5414 "setAudioPortConfig() called on duplicated output %d",
5415 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005416 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005417 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005418 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005419 if (inputDesc == NULL) {
5420 return BAD_VALUE;
5421 }
Eric Laurenta121f902014-06-03 13:32:54 -07005422 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005423 } else {
5424 return BAD_VALUE;
5425 }
5426 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5427 sp<DeviceDescriptor> deviceDesc;
5428 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5429 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5430 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5431 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5432 } else {
5433 return BAD_VALUE;
5434 }
5435 if (deviceDesc == NULL) {
5436 return BAD_VALUE;
5437 }
Eric Laurenta121f902014-06-03 13:32:54 -07005438 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005439 } else {
5440 return BAD_VALUE;
5441 }
5442
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005443 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005444 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5445 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005446 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005447 audioPortConfig->toAudioPortConfig(&newConfig, config);
5448 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005449 }
Eric Laurenta121f902014-06-03 13:32:54 -07005450 if (status != NO_ERROR) {
5451 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005452 }
Eric Laurente1715a42014-05-20 11:30:42 -07005453
5454 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005455}
5456
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005457void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5458{
Eric Laurentd60560a2015-04-10 11:31:20 -07005459 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005460 clearAudioPatches(uid);
5461 clearSessionRoutes(uid);
5462}
5463
Eric Laurent6a94d692014-05-20 11:18:06 -07005464void AudioPolicyManager::clearAudioPatches(uid_t uid)
5465{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005466 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005468 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005469 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005470 }
5471 }
5472}
5473
François Gaffiec005e562018-11-06 15:04:49 +01005474void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005475{
François Gaffiec005e562018-11-06 15:04:49 +01005476 // Take the first attributes following the product strategy as it is used to retrieve the routed
5477 // device. All attributes wihin a strategy follows the same "routing strategy"
5478 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5479 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005480 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005481 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005482 for (size_t j = 0; j < mOutputs.size(); j++) {
5483 if (mOutputs.keyAt(j) == ouptutToSkip) {
5484 continue;
5485 }
5486 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005487 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005488 continue;
5489 }
5490 // If the default device for this strategy is on another output mix,
5491 // invalidate all tracks in this strategy to force re connection.
5492 // Otherwise select new device on the output mix.
5493 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005494 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005495 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005496 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5497 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5498 // If the device is using preferred mixer attributes, the output need to reopen
5499 // with default configuration when the new selected devices are different from
5500 // current routing devices.
5501 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5502 continue;
5503 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305504 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005505 }
5506 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005507 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005508}
5509
5510void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5511{
5512 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005513 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005514 for (size_t i = 0; i < mOutputs.size(); i++) {
5515 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005516 for (const auto& client : outputDesc->getClientIterable()) {
5517 if (client->hasPreferredDevice() && client->uid() == uid) {
5518 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005519 auto clientStrategy = client->strategy();
5520 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5521 end(affectedStrategies)) {
5522 continue;
5523 }
5524 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005525 }
5526 }
5527 }
5528 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005529 for (const auto& strategy : affectedStrategies) {
5530 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005531 }
5532
5533 // remove input routes associated with this uid
5534 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005535 for (size_t i = 0; i < mInputs.size(); i++) {
5536 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005537 for (const auto& client : inputDesc->getClientIterable()) {
5538 if (client->hasPreferredDevice() && client->uid() == uid) {
5539 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5540 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005541 }
5542 }
5543 }
5544 // reroute inputs if necessary
5545 SortedVector<audio_io_handle_t> inputsToClose;
5546 for (size_t i = 0; i < mInputs.size(); i++) {
5547 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005548 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005549 inputsToClose.add(inputDesc->mIoHandle);
5550 }
5551 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005552 for (const auto& input : inputsToClose) {
5553 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005554 }
5555}
5556
Eric Laurentd60560a2015-04-10 11:31:20 -07005557void AudioPolicyManager::clearAudioSources(uid_t uid)
5558{
5559 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005560 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5561 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005562 stopAudioSource(mAudioSources.keyAt(i));
5563 }
5564 }
5565}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005566
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005567status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5568 audio_io_handle_t *ioHandle,
5569 audio_devices_t *device)
5570{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005571 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5572 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005573 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005574 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5575 if (deviceDesc == nullptr) {
5576 return INVALID_OPERATION;
5577 }
5578 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005579
François Gaffiedf372692015-03-19 10:43:27 +01005580 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005581}
5582
Eric Laurentd60560a2015-04-10 11:31:20 -07005583status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005584 const audio_attributes_t *attributes,
5585 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005586 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005587{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005588 ALOGV("%s", __FUNCTION__);
5589 *portId = AUDIO_PORT_HANDLE_NONE;
5590
5591 if (source == NULL || attributes == NULL || portId == NULL) {
5592 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5593 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005594 return BAD_VALUE;
5595 }
5596
Eric Laurentd60560a2015-04-10 11:31:20 -07005597 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5598 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005599 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5600 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005601 return INVALID_OPERATION;
5602 }
5603
François Gaffie11d30102018-11-02 16:09:09 +01005604 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005605 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005606 String8(source->ext.device.address),
5607 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005608 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005609 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005610 return BAD_VALUE;
5611 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005612
jiabin4ef93452019-09-10 14:29:54 -07005613 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005614
François Gaffieaaac0fd2018-11-22 17:56:39 +01005615 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005616 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005617 mEngine->getStreamTypeForAttributes(*attributes),
5618 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005619 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005620
5621 status_t status = connectAudioSource(sourceDesc);
5622 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005623 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005624 }
5625 return status;
5626}
5627
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005628status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005629{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005630 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005631
5632 // make sure we only have one patch per source.
5633 disconnectAudioSource(sourceDesc);
5634
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005635 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005636 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5637 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5638 sourceDesc->srcDevice()->type(),
5639 String8(sourceDesc->srcDevice()->address().c_str()),
5640 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005641 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005642 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005643 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005644 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005645 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5646 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5647 return INVALID_OPERATION;
5648 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005649 PatchBuilder patchBuilder;
5650 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5651 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005652
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005653 return connectAudioSourceToSink(
5654 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005655}
5656
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005657status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005658{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005659 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5660 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005661 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005662 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005663 return BAD_VALUE;
5664 }
5665 status_t status = disconnectAudioSource(sourceDesc);
5666
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005667 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005668 return status;
5669}
5670
Andy Hung2ddee192015-12-18 17:34:44 -08005671status_t AudioPolicyManager::setMasterMono(bool mono)
5672{
5673 if (mMasterMono == mono) {
5674 return NO_ERROR;
5675 }
5676 mMasterMono = mono;
5677 // if enabling mono we close all offloaded devices, which will invalidate the
5678 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5679 // for recreating the new AudioTrack as non-offloaded PCM.
5680 //
5681 // If disabling mono, we leave all tracks as is: we don't know which clients
5682 // and tracks are able to be recreated as offloaded. The next "song" should
5683 // play back offloaded.
5684 if (mMasterMono) {
5685 Vector<audio_io_handle_t> offloaded;
5686 for (size_t i = 0; i < mOutputs.size(); ++i) {
5687 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5688 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5689 offloaded.push(desc->mIoHandle);
5690 }
5691 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005692 for (const auto& handle : offloaded) {
5693 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005694 }
5695 }
5696 // update master mono for all remaining outputs
5697 for (size_t i = 0; i < mOutputs.size(); ++i) {
5698 updateMono(mOutputs.keyAt(i));
5699 }
5700 return NO_ERROR;
5701}
5702
5703status_t AudioPolicyManager::getMasterMono(bool *mono)
5704{
5705 *mono = mMasterMono;
5706 return NO_ERROR;
5707}
5708
Eric Laurentac9cef52017-06-09 15:46:26 -07005709float AudioPolicyManager::getStreamVolumeDB(
5710 audio_stream_type_t stream, int index, audio_devices_t device)
5711{
jiabin9a3361e2019-10-01 09:38:30 -07005712 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005713}
5714
jiabin81772902018-04-02 17:52:27 -07005715status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5716 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005717 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005718{
Kriti Dang6537def2021-03-02 13:46:59 +01005719 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5720 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005721 return BAD_VALUE;
5722 }
Kriti Dang6537def2021-03-02 13:46:59 +01005723 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5724 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005725
5726 size_t formatsWritten = 0;
5727 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005728
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005729 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005730 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5731 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005732 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005733 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005734 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005735 bool formatEnabled = true;
5736 switch (forceUse) {
5737 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005738 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005739 break;
5740 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5741 formatEnabled = false;
5742 break;
5743 default: // AUTO or ALWAYS => true
5744 break;
jiabin81772902018-04-02 17:52:27 -07005745 }
5746 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5747 }
jiabin81772902018-04-02 17:52:27 -07005748 }
5749 return NO_ERROR;
5750}
5751
Kriti Dang6537def2021-03-02 13:46:59 +01005752status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5753 audio_format_t *surroundFormats) {
5754 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5755 return BAD_VALUE;
5756 }
5757 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5758 __func__, *numSurroundFormats, surroundFormats);
5759
5760 size_t formatsWritten = 0;
5761 size_t formatsMax = *numSurroundFormats;
5762 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5763
5764 // Return formats from all device profiles that have already been resolved by
5765 // checkOutputsForDevice().
5766 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5767 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5768 audio_devices_t deviceType = device->type();
5769 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5770 // returns formats reported by HDMI devices.
5771 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5772 continue;
5773 }
5774 // Formats reported by sink devices
5775 std::unordered_set<audio_format_t> formatset;
5776 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5777 formatset.insert(it->second.begin(), it->second.end());
5778 }
5779
5780 // Formats hard-coded in the in policy configuration file (if any).
5781 FormatVector encodedFormats = device->encodedFormats();
5782 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5783 // Filter the formats which are supported by the vendor hardware.
5784 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005785 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005786 formats.insert(*it);
5787 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005788 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005789 if (pair.second.count(*it) != 0) {
5790 formats.insert(pair.first);
5791 break;
5792 }
5793 }
5794 }
5795 }
5796 }
5797 *numSurroundFormats = formats.size();
5798 for (const auto& format: formats) {
5799 if (formatsWritten < formatsMax) {
5800 surroundFormats[formatsWritten++] = format;
5801 }
5802 }
5803 return NO_ERROR;
5804}
5805
jiabin81772902018-04-02 17:52:27 -07005806status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5807{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005808 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005809 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5810 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005811 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005812 return BAD_VALUE;
5813 }
5814
Mikhail Naganov100f0122018-11-29 11:22:16 -08005815 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5816 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005817 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005818 return INVALID_OPERATION;
5819 }
5820
Mikhail Naganov100f0122018-11-29 11:22:16 -08005821 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005822 return NO_ERROR;
5823 }
5824
Mikhail Naganov100f0122018-11-29 11:22:16 -08005825 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005826 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005827 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005828 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005829 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005830 }
5831 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005832 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005833 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005834 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005835 }
5836 }
5837
5838 sp<SwAudioOutputDescriptor> outputDesc;
5839 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005840 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5841 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005842 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5843 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005844 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005845 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005846 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5847 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5848 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005849 name.c_str(),
5850 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005851 if (status != NO_ERROR) {
5852 continue;
5853 }
5854 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5855 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5856 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005857 name.c_str(),
5858 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005859 profileUpdated |= (status == NO_ERROR);
5860 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005861 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005862 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005863 AUDIO_DEVICE_IN_HDMI);
5864 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5865 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005866 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005867 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005868 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5869 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5870 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005871 name.c_str(),
5872 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005873 if (status != NO_ERROR) {
5874 continue;
5875 }
5876 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5877 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5878 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005879 name.c_str(),
5880 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005881 profileUpdated |= (status == NO_ERROR);
5882 }
5883
jiabin81772902018-04-02 17:52:27 -07005884 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005885 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005886 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005887 }
5888
5889 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5890}
5891
Eric Laurent5ada82e2019-08-29 17:53:54 -07005892void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005893{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005894 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005895 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005896 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005897 }
5898}
5899
jiabin6012f912018-11-02 17:06:30 -07005900bool AudioPolicyManager::isHapticPlaybackSupported()
5901{
5902 for (const auto& hwModule : mHwModules) {
5903 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5904 for (const auto &outProfile : outputProfiles) {
5905 struct audio_port audioPort;
5906 outProfile->toAudioPort(&audioPort);
5907 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5908 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5909 return true;
5910 }
5911 }
5912 }
5913 }
5914 return false;
5915}
5916
Carter Hsu325a8eb2022-01-19 19:56:51 +08005917bool AudioPolicyManager::isUltrasoundSupported()
5918{
5919 bool hasUltrasoundOutput = false;
5920 bool hasUltrasoundInput = false;
5921 for (const auto& hwModule : mHwModules) {
5922 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5923 if (!hasUltrasoundOutput) {
5924 for (const auto &outProfile : outputProfiles) {
5925 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5926 hasUltrasoundOutput = true;
5927 break;
5928 }
5929 }
5930 }
5931
5932 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5933 if (!hasUltrasoundInput) {
5934 for (const auto &inputProfile : inputProfiles) {
5935 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5936 hasUltrasoundInput = true;
5937 break;
5938 }
5939 }
5940 }
5941
5942 if (hasUltrasoundOutput && hasUltrasoundInput)
5943 return true;
5944 }
5945 return false;
5946}
5947
Atneya Nair698f5ef2022-12-15 16:15:09 -08005948bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5949{
5950 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5951 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5952 for (const auto& hwModule : mHwModules) {
5953 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5954 for (const auto &inputProfile : inputProfiles) {
5955 if ((inputProfile->getFlags() & mask) == mask) {
5956 return true;
5957 }
5958 }
5959 }
5960 return false;
5961}
5962
Eric Laurent8340e672019-11-06 11:01:08 -08005963bool AudioPolicyManager::isCallScreenModeSupported()
5964{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005965 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005966}
5967
5968
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005969status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005970{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005971 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005972 if (!sourceDesc->isConnected()) {
5973 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5974 return NO_ERROR;
5975 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005976 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5977 if (swOutput != 0) {
5978 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005979 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005980 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005981 }
jiabinbce0c1d2020-10-05 11:20:18 -07005982 if (releaseOutput(sourceDesc->portId())) {
5983 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5984 // no need to release audio patch here but just return NO_ERROR.
5985 return NO_ERROR;
5986 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005987 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005988 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005989 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005990 // close Hwoutput and remove from mHwOutputs
5991 } else {
5992 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5993 }
5994 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005995 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005996 sourceDesc->disconnect();
5997 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005998}
5999
François Gaffiec005e562018-11-06 15:04:49 +01006000sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6001 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006002{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006003 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006004 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006005 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006006 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006007 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6008 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006009 source = sourceDesc;
6010 break;
6011 }
6012 }
6013 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006014}
6015
Eric Laurentb4f42a92022-01-17 17:37:31 +01006016bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006017 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006018 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006019{
6020 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6021 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006022 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006023 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006024 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6025 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6026 return false;
6027 }
6028 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6029 return false;
6030 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006031 }
6032
Eric Laurentd332bc82023-08-04 11:45:23 +02006033 // The caller can have the audio config criteria ignored by either passing a null ptr or
6034 // the AUDIO_CONFIG_INITIALIZER value.
6035 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006036 // some positional channel masks and PCM format and for stereo if low latency performance
6037 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006038
6039 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006040 static const bool stereo_spatialization_enabled =
6041 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006042 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006043 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006044 ? audio_channel_mask_contains_stereo(config->channel_mask)
6045 : audio_is_channel_mask_spatialized(config->channel_mask);
6046 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006047 return false;
6048 }
6049 if (!audio_is_linear_pcm(config->format)) {
6050 return false;
6051 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006052 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6053 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6054 return false;
6055 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006056 }
6057
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006058 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006059 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006060 if (profile == nullptr) {
6061 return false;
6062 }
6063
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006064 return true;
6065}
6066
6067void AudioPolicyManager::checkVirtualizerClientRoutes() {
6068 std::set<audio_stream_type_t> streamsToInvalidate;
6069 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006070 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6071 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006072 audio_attributes_t attr = client->attributes();
6073 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6074 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6075 audio_config_base_t clientConfig = client->config();
6076 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006077 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006078 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006079 streamsToInvalidate.insert(client->stream());
6080 }
6081 }
6082 }
6083
jiabinc44b3462022-12-08 12:52:31 -08006084 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006085}
6086
Eric Laurente191d1b2022-04-15 11:59:25 +02006087
6088bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6089 const sp<SwAudioOutputDescriptor>& outputDesc) {
6090 if (outputDesc->isDuplicated()) {
6091 return false;
6092 }
6093 DeviceVector devices = outputDesc->supportedDevices();
6094 for (size_t i = 0; i < mOutputs.size(); i++) {
6095 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6096 if (desc == outputDesc || desc->isDuplicated()) {
6097 continue;
6098 }
6099 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6100 if (!sharedDevices.isEmpty()
6101 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6102 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6103 return false;
6104 }
6105 }
6106 return true;
6107}
6108
6109
Eric Laurentfa0f6742021-08-17 18:39:44 +02006110status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006111 const audio_attributes_t *attr,
6112 audio_io_handle_t *output) {
6113 *output = AUDIO_IO_HANDLE_NONE;
6114
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006115 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6116 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6117 audio_config_t *configPtr = nullptr;
6118 audio_config_t config;
6119 if (mixerConfig != nullptr) {
6120 config = audio_config_initializer(mixerConfig);
6121 configPtr = &config;
6122 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006123 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006124 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006125 return BAD_VALUE;
6126 }
6127
6128 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006129 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006130 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006131 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006132 return BAD_VALUE;
6133 }
6134
Eric Laurente191d1b2022-04-15 11:59:25 +02006135 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006136 for (size_t i = 0; i < mOutputs.size(); i++) {
6137 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006138 if (!desc->isDuplicated()
6139 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6140 spatializerOutputs.push_back(desc);
6141 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006142 }
6143 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006144 mSpatializerOutput.clear();
6145 bool outputsChanged = false;
6146 for (const auto& desc : spatializerOutputs) {
6147 if (desc->mProfile == profile
6148 && (configPtr == nullptr
6149 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6150 mSpatializerOutput = desc;
6151 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6152 } else {
6153 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6154 " and devices %s", __func__, desc->mIoHandle,
6155 configPtr != nullptr ? configPtr->channel_mask : 0,
6156 devices.toString().c_str());
6157 closeOutput(desc->mIoHandle);
6158 outputsChanged = true;
6159 }
Eric Laurent39095982021-08-24 18:29:27 +02006160 }
6161
Eric Laurente191d1b2022-04-15 11:59:25 +02006162 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006163 sp<SwAudioOutputDescriptor> desc =
6164 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006165 if (desc != nullptr) {
6166 mSpatializerOutput = desc;
6167 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006168 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006169 }
6170
6171 checkVirtualizerClientRoutes();
6172
Eric Laurente191d1b2022-04-15 11:59:25 +02006173 if (outputsChanged) {
6174 mPreviousOutputs = mOutputs;
6175 mpClientInterface->onAudioPortListUpdate();
6176 }
6177
6178 if (mSpatializerOutput == nullptr) {
6179 ALOGV("%s could not open spatializer output with requested config", __func__);
6180 return BAD_VALUE;
6181 }
Eric Laurent39095982021-08-24 18:29:27 +02006182 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006183 ALOGV("%s returning new spatializer output %d", __func__, *output);
6184 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006185}
6186
Eric Laurentfa0f6742021-08-17 18:39:44 +02006187status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6188 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006189 return INVALID_OPERATION;
6190 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006191 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006192 return BAD_VALUE;
6193 }
Eric Laurent39095982021-08-24 18:29:27 +02006194
Eric Laurente191d1b2022-04-15 11:59:25 +02006195 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6196 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6197 closeOutput(mSpatializerOutput->mIoHandle);
6198 //from now on mSpatializerOutput is null
6199 checkVirtualizerClientRoutes();
6200 }
Eric Laurent39095982021-08-24 18:29:27 +02006201
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006202 return NO_ERROR;
6203}
6204
Eric Laurente552edb2014-03-10 17:42:56 -07006205// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006206// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006207// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006208uint32_t AudioPolicyManager::nextAudioPortGeneration()
6209{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006210 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006211}
6212
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006213AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006214 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006215 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006216 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006217 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006218 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006219 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006220 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006221 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006222 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006223 mAudioPortGeneration(1),
6224 mBeaconMuteRefCount(0),
6225 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006226 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006227 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006228 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006229 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006230{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006231}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006232
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006233status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006234 if (mEngine == nullptr) {
6235 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006236 }
6237 mEngine->setObserver(this);
6238 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006239 if (status != NO_ERROR) {
6240 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6241 return status;
6242 }
François Gaffie2110e042015-03-24 08:41:51 +01006243
jiabin29230182023-04-04 21:02:36 +00006244 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6245 // at the end of this function.
6246 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006247 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6248 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6249
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006250 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006251 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006252 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006253
Eric Laurent3a4311c2014-03-17 12:00:47 -07006254 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006255 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6256 defaultOutputDevice == nullptr ||
6257 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6258 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6259 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006260 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006261 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006262 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006263
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006264 // Silence ALOGV statements
6265 property_set("log.tag." LOG_TAG, "D");
6266
Eric Laurente552edb2014-03-10 17:42:56 -07006267 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006268 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006269}
6270
Eric Laurente0720872014-03-11 09:30:41 -07006271AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006272{
Eric Laurente552edb2014-03-10 17:42:56 -07006273 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006274 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006275 }
6276 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006277 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006278 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006279 mAvailableOutputDevices.clear();
6280 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006281 mOutputs.clear();
6282 mInputs.clear();
6283 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006284 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006285 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006286}
6287
Eric Laurente0720872014-03-11 09:30:41 -07006288status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006289{
Eric Laurent87ffa392015-05-22 10:32:38 -07006290 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006291}
6292
Eric Laurente552edb2014-03-10 17:42:56 -07006293// ---
6294
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006295void AudioPolicyManager::onNewAudioModulesAvailable()
6296{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006297 DeviceVector newDevices;
6298 onNewAudioModulesAvailableInt(&newDevices);
6299 if (!newDevices.empty()) {
6300 nextAudioPortGeneration();
6301 mpClientInterface->onAudioPortListUpdate();
6302 }
6303}
6304
6305void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6306{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006307 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006308 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6309 continue;
6310 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006311 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006312 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6313 handle != AUDIO_MODULE_HANDLE_NONE) {
6314 hwModule->setHandle(handle);
6315 } else {
6316 ALOGW("could not load HW module %s", hwModule->getName());
6317 continue;
6318 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006319 }
6320 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006321 // open all output streams needed to access attached devices.
6322 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006323 // This also validates mAvailableOutputDevices list
6324 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6325 if (!outProfile->canOpenNewIo()) {
6326 ALOGE("Invalid Output profile max open count %u for profile %s",
6327 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6328 continue;
6329 }
6330 if (!outProfile->hasSupportedDevices()) {
6331 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6332 continue;
6333 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006334 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6335 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006336 mTtsOutputAvailable = true;
6337 }
6338
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006339 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006340 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006341 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006342 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6343 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006344 } else {
6345 // choose first device present in profile's SupportedDevices also part of
6346 // mAvailableOutputDevices.
6347 if (availProfileDevices.isEmpty()) {
6348 continue;
6349 }
6350 supportedDevice = availProfileDevices.itemAt(0);
6351 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006352 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006353 continue;
6354 }
6355 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6356 mpClientInterface);
6357 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006358 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6359 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006360 AUDIO_STREAM_DEFAULT,
6361 AUDIO_OUTPUT_FLAG_NONE, &output);
6362 if (status != NO_ERROR) {
6363 ALOGW("Cannot open output stream for devices %s on hw module %s",
6364 supportedDevice->toString().c_str(), hwModule->getName());
6365 continue;
6366 }
6367 for (const auto &device : availProfileDevices) {
6368 // give a valid ID to an attached device once confirmed it is reachable
6369 if (!device->isAttached()) {
6370 device->attach(hwModule);
6371 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006372 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006373 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006374 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6375 }
6376 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006377 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006378 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6379 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006380 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006381 }
Eric Laurent39095982021-08-24 18:29:27 +02006382 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006383 outputDesc->close();
6384 } else {
6385 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306386 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006387 DeviceVector(supportedDevice),
6388 true,
6389 0,
6390 NULL);
6391 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006392 }
6393 // open input streams needed to access attached devices to validate
6394 // mAvailableInputDevices list
6395 for (const auto& inProfile : hwModule->getInputProfiles()) {
6396 if (!inProfile->canOpenNewIo()) {
6397 ALOGE("Invalid Input profile max open count %u for profile %s",
6398 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6399 continue;
6400 }
6401 if (!inProfile->hasSupportedDevices()) {
6402 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6403 continue;
6404 }
6405 // chose first device present in profile's SupportedDevices also part of
6406 // available input devices
6407 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006408 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006409 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006410 ALOGV("%s: Input device list is empty! for profile %s",
6411 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006412 continue;
6413 }
6414 sp<AudioInputDescriptor> inputDesc =
6415 new AudioInputDescriptor(inProfile, mpClientInterface);
6416
6417 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6418 status_t status = inputDesc->open(nullptr,
6419 availProfileDevices.itemAt(0),
6420 AUDIO_SOURCE_MIC,
6421 AUDIO_INPUT_FLAG_NONE,
6422 &input);
6423 if (status != NO_ERROR) {
6424 ALOGW("Cannot open input stream for device %s on hw module %s",
6425 availProfileDevices.toString().c_str(),
6426 hwModule->getName());
6427 continue;
6428 }
6429 for (const auto &device : availProfileDevices) {
6430 // give a valid ID to an attached device once confirmed it is reachable
6431 if (!device->isAttached()) {
6432 device->attach(hwModule);
6433 device->importAudioPortAndPickAudioProfile(inProfile, true);
6434 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006435 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006436 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6437 }
6438 }
6439 inputDesc->close();
6440 }
6441 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006442
6443 // Check if spatializer outputs can be closed until used.
6444 // mOutputs vector never contains duplicated outputs at this point.
6445 std::vector<audio_io_handle_t> outputsClosed;
6446 for (size_t i = 0; i < mOutputs.size(); i++) {
6447 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6448 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6449 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6450 outputsClosed.push_back(desc->mIoHandle);
6451 desc->close();
6452 }
6453 }
6454 for (auto output : outputsClosed) {
6455 removeOutput(output);
6456 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006457}
6458
Eric Laurent98e38192018-02-15 18:31:53 -08006459void AudioPolicyManager::addOutput(audio_io_handle_t output,
6460 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006461{
Eric Laurent1c333e22014-05-20 10:48:17 -07006462 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006463 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006464 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006465 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006466 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006467}
6468
François Gaffie53615e22015-03-19 09:24:12 +01006469void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6470{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006471 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6472 ALOGV("%s: removing primary output", __func__);
6473 mPrimaryOutput = nullptr;
6474 }
François Gaffie53615e22015-03-19 09:24:12 +01006475 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006476 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006477}
6478
Eric Laurent98e38192018-02-15 18:31:53 -08006479void AudioPolicyManager::addInput(audio_io_handle_t input,
6480 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006481{
Eric Laurent1c333e22014-05-20 10:48:17 -07006482 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006483 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006484}
Eric Laurente552edb2014-03-10 17:42:56 -07006485
François Gaffie11d30102018-11-02 16:09:09 +01006486status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006487 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006488 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006489{
François Gaffie11d30102018-11-02 16:09:09 +01006490 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006491 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006492 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006493
François Gaffie11d30102018-11-02 16:09:09 +01006494 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006495 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006496 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006497 }
Eric Laurente552edb2014-03-10 17:42:56 -07006498
Eric Laurent3b73df72014-03-11 09:06:29 -07006499 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006500 // first call getAudioPort to get the supported attributes from the HAL
6501 struct audio_port_v7 port = {};
6502 device->toAudioPort(&port);
6503 status_t status = mpClientInterface->getAudioPort(&port);
6504 if (status == NO_ERROR) {
6505 device->importAudioPort(port);
6506 }
6507
6508 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006509 for (size_t i = 0; i < mOutputs.size(); i++) {
6510 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006511 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006512 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006513 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6514 mOutputs.keyAt(i), device->toString().c_str());
6515 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006516 }
6517 }
6518 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006519 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006520 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006521 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6522 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006523 if (profile->supportsDevice(device)) {
6524 profiles.add(profile);
6525 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6526 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006527 }
6528 }
6529 }
6530
Eric Laurent7b279bb2015-12-14 10:18:23 -08006531 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006532
Eric Laurente552edb2014-03-10 17:42:56 -07006533 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006534 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006535 return BAD_VALUE;
6536 }
6537
6538 // open outputs for matching profiles if needed. Direct outputs are also opened to
6539 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6540 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006541 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006542
6543 // nothing to do if one output is already opened for this profile
6544 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006545 for (j = 0; j < outputs.size(); j++) {
6546 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006547 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006548 // matching profile: save the sample rates, format and channel masks supported
6549 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006550 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006551 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006552 }
Eric Laurente552edb2014-03-10 17:42:56 -07006553 break;
6554 }
6555 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006556 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006557 continue;
6558 }
6559
Eric Laurent3974e3b2017-12-07 17:58:43 -08006560 if (!profile->canOpenNewIo()) {
6561 ALOGW("Max Output number %u already opened for this profile %s",
6562 profile->maxOpenCount, profile->getTagName().c_str());
6563 continue;
6564 }
6565
Eric Laurent83efe1c2017-07-09 16:51:08 -07006566 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006567 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006568 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6569 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006570 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006571 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006572 profiles.removeAt(profile_index);
6573 profile_index--;
6574 } else {
6575 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006576 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006577 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006578 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6579 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006580 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006581 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006582
François Gaffie11d30102018-11-02 16:09:09 +01006583 if (device_distinguishes_on_address(deviceType)) {
6584 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6585 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306586 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6587 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006588 }
Eric Laurente552edb2014-03-10 17:42:56 -07006589 ALOGV("checkOutputsForDevice(): adding output %d", output);
6590 }
6591 }
6592
6593 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006594 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006595 return BAD_VALUE;
6596 }
Eric Laurentd4692962014-05-05 18:13:44 -07006597 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006598 // check if one opened output is not needed any more after disconnecting one device
6599 for (size_t i = 0; i < mOutputs.size(); i++) {
6600 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006601 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006602 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006603 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006604 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006605 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006606 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006607 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6608 mOutputs.keyAt(i));
6609 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006610 }
Eric Laurente552edb2014-03-10 17:42:56 -07006611 }
6612 }
Eric Laurentd4692962014-05-05 18:13:44 -07006613 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006614 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006615 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6616 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006617 if (!profile->supportsDevice(device)) {
6618 continue;
6619 }
6620 ALOGV("checkOutputsForDevice(): "
6621 "clearing direct output profile %zu on module %s",
6622 j, hwModule->getName());
6623 profile->clearAudioProfiles();
6624 if (!profile->hasDynamicAudioProfile()) {
6625 continue;
6626 }
6627 // When a device is disconnected, if there is an IOProfile that contains dynamic
6628 // profiles and supports the disconnected device, call getAudioPort to repopulate
6629 // the capabilities of the devices that is supported by the IOProfile.
6630 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6631 if (supportedDevice == device ||
6632 !mAvailableOutputDevices.contains(supportedDevice)) {
6633 continue;
6634 }
6635 struct audio_port_v7 port;
6636 supportedDevice->toAudioPort(&port);
6637 status_t status = mpClientInterface->getAudioPort(&port);
6638 if (status == NO_ERROR) {
6639 supportedDevice->importAudioPort(port);
6640 }
Eric Laurente552edb2014-03-10 17:42:56 -07006641 }
6642 }
6643 }
6644 }
6645 return NO_ERROR;
6646}
6647
François Gaffie11d30102018-11-02 16:09:09 +01006648status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006649 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006650{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006651 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006652
François Gaffie11d30102018-11-02 16:09:09 +01006653 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006654 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006655 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006656 }
6657
Eric Laurentd4692962014-05-05 18:13:44 -07006658 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006659 // first call getAudioPort to get the supported attributes from the HAL
6660 struct audio_port_v7 port = {};
6661 device->toAudioPort(&port);
6662 status_t status = mpClientInterface->getAudioPort(&port);
6663 if (status == NO_ERROR) {
6664 device->importAudioPort(port);
6665 }
6666
Eric Laurent0dd51852019-04-19 18:18:58 -07006667 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006668 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006669 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006670 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006671 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006672 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006673 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006674
François Gaffie11d30102018-11-02 16:09:09 +01006675 if (profile->supportsDevice(device)) {
6676 profiles.add(profile);
6677 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6678 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006679 }
6680 }
6681 }
6682
Eric Laurent0dd51852019-04-19 18:18:58 -07006683 if (profiles.isEmpty()) {
6684 ALOGW("%s: No input profile available for device %s",
6685 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006686 return BAD_VALUE;
6687 }
6688
6689 // open inputs for matching profiles if needed. Direct inputs are also opened to
6690 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6691 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6692
Eric Laurent1c333e22014-05-20 10:48:17 -07006693 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006694
Eric Laurentd4692962014-05-05 18:13:44 -07006695 // nothing to do if one input is already opened for this profile
6696 size_t input_index;
6697 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6698 desc = mInputs.valueAt(input_index);
6699 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006700 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006701 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006702 }
Eric Laurentd4692962014-05-05 18:13:44 -07006703 break;
6704 }
6705 }
6706 if (input_index != mInputs.size()) {
6707 continue;
6708 }
6709
Eric Laurent3974e3b2017-12-07 17:58:43 -08006710 if (!profile->canOpenNewIo()) {
6711 ALOGW("Max Input number %u already opened for this profile %s",
6712 profile->maxOpenCount, profile->getTagName().c_str());
6713 continue;
6714 }
6715
Eric Laurentfe231122017-11-17 17:48:06 -08006716 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006717 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006718 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006719
Eric Laurentcf2c0212014-07-25 16:20:43 -07006720 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006721 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006722 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006723 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006724 mpClientInterface->setParameters(input, String8(param));
6725 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006726 }
jiabin12537fc2023-10-12 17:56:08 +00006727 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006728 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006729 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006730 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006731 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006732 }
6733
Eric Laurent0dd51852019-04-19 18:18:58 -07006734 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006735 addInput(input, desc);
6736 }
6737 } // endif input != 0
6738
Eric Laurentcf2c0212014-07-25 16:20:43 -07006739 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006740 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006741 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006742 profiles.removeAt(profile_index);
6743 profile_index--;
6744 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006745 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006746 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006747 }
Eric Laurentd4692962014-05-05 18:13:44 -07006748 ALOGV("checkInputsForDevice(): adding input %d", input);
6749 }
6750 } // end scan profiles
6751
6752 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006753 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006754 return BAD_VALUE;
6755 }
6756 } else {
6757 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006758 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006759 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006760 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006761 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006762 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006763 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006764 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006765 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6766 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006767 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006768 }
6769 }
6770 }
6771 } // end disconnect
6772
6773 return NO_ERROR;
6774}
6775
6776
Eric Laurente0720872014-03-11 09:30:41 -07006777void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006778{
6779 ALOGV("closeOutput(%d)", output);
6780
François Gaffie1c878552018-11-22 16:53:21 +01006781 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6782 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006783 ALOGW("closeOutput() unknown output %d", output);
6784 return;
6785 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006786 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006787 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006788
Eric Laurente552edb2014-03-10 17:42:56 -07006789 // look for duplicated outputs connected to the output being removed.
6790 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006791 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6792 if (dupOutput->isDuplicated() &&
6793 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6794 sp<SwAudioOutputDescriptor> remainingOutput =
6795 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006796 // As all active tracks on duplicated output will be deleted,
6797 // and as they were also referenced on the other output, the reference
6798 // count for their stream type must be adjusted accordingly on
6799 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006800 const bool wasActive = remainingOutput->isActive();
6801 // Note: no-op on the closing output where all clients has already been set inactive
6802 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006803 // stop() will be a no op if the output is still active but is needed in case all
6804 // active streams refcounts where cleared above
6805 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006806 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006807 }
Eric Laurente552edb2014-03-10 17:42:56 -07006808 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6809 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6810
6811 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006812 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006813 }
6814 }
6815
Eric Laurent05b90f82014-08-27 15:32:29 -07006816 nextAudioPortGeneration();
6817
François Gaffie1c878552018-11-22 16:53:21 +01006818 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006819 if (index >= 0) {
6820 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006821 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6822 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006823 mAudioPatches.removeItemsAt(index);
6824 mpClientInterface->onAudioPatchListUpdate();
6825 }
6826
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006827 if (closingOutputWasActive) {
6828 closingOutput->stop();
6829 }
François Gaffie1c878552018-11-22 16:53:21 +01006830 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006831 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6832 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6833 for (const auto device : closingOutput->devices()) {
6834 device->setPreferredConfig(nullptr);
6835 }
6836 }
Eric Laurente552edb2014-03-10 17:42:56 -07006837
François Gaffie53615e22015-03-19 09:24:12 +01006838 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006839 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006840 if (closingOutput == mSpatializerOutput) {
6841 mSpatializerOutput.clear();
6842 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006843
6844 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6845 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006846 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006847 bool directOutputOpen = false;
6848 for (size_t i = 0; i < mOutputs.size(); i++) {
6849 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6850 directOutputOpen = true;
6851 break;
6852 }
6853 }
6854 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006855 ALOGV("no direct outputs open, reset MSD patches");
6856 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6857 // how output devices for patching are resolved. Avoid by caching and reusing the
6858 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6859 // devices to patch to. This may be complicated by the fact that devices may become
6860 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006861 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006862 }
6863 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006864}
6865
6866void AudioPolicyManager::closeInput(audio_io_handle_t input)
6867{
6868 ALOGV("closeInput(%d)", input);
6869
6870 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6871 if (inputDesc == NULL) {
6872 ALOGW("closeInput() unknown input %d", input);
6873 return;
6874 }
6875
Eric Laurent6a94d692014-05-20 11:18:06 -07006876 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006877
François Gaffie11d30102018-11-02 16:09:09 +01006878 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006879 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006880 if (index >= 0) {
6881 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006882 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6883 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006884 mAudioPatches.removeItemsAt(index);
6885 mpClientInterface->onAudioPatchListUpdate();
6886 }
6887
François Gaffie6ebbce02023-07-19 13:27:53 +02006888 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006889 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006890 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006891
François Gaffie11d30102018-11-02 16:09:09 +01006892 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6893 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006894 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006895 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006896 }
Eric Laurente552edb2014-03-10 17:42:56 -07006897}
6898
François Gaffie11d30102018-11-02 16:09:09 +01006899SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6900 const DeviceVector &devices,
6901 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006902{
6903 SortedVector<audio_io_handle_t> outputs;
6904
François Gaffie11d30102018-11-02 16:09:09 +01006905 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006906 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006907 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006908 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006909 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006910 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006911 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006912 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006913 outputs.add(openOutputs.keyAt(i));
6914 }
6915 }
6916 return outputs;
6917}
6918
Mikhail Naganov37977152018-07-11 15:54:44 -07006919void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6920{
6921 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6922 // output is suspended before any tracks are moved to it
6923 checkA2dpSuspend();
6924 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006925 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006926 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006927 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006928 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006929 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6930 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6931 // configuration changes will ultimately be rerouted correctly. We can still avoid
6932 // unnecessary rerouting by caching and reusing the arguments to
6933 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6934 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006935 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006936 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006937 // an event that changed routing likely occurred, inform upper layers
6938 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006939}
6940
François Gaffiec005e562018-11-06 15:04:49 +01006941bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6942 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006943{
François Gaffiec005e562018-11-06 15:04:49 +01006944 return mEngine->getProductStrategyForAttributes(lAttr) ==
6945 mEngine->getProductStrategyForAttributes(rAttr);
6946}
6947
Francois Gaffieff1eb522020-05-06 18:37:04 +02006948void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6949{
6950 for (size_t i = 0; i < mAudioSources.size(); i++) {
6951 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6952 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006953 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006954 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006955 connectAudioSource(sourceDesc);
6956 }
6957 }
6958}
6959
6960void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6961{
6962 for (size_t i = 0; i < mAudioSources.size(); i++) {
6963 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6964 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6965 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6966 disconnectAudioSource(sourceDesc);
6967 }
6968 }
6969}
6970
François Gaffiec005e562018-11-06 15:04:49 +01006971void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6972{
6973 auto psId = mEngine->getProductStrategyForAttributes(attr);
6974
6975 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6976 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006977
François Gaffie11d30102018-11-02 16:09:09 +01006978 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6979 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006980
Eric Laurentc209fe42020-06-05 18:11:23 -07006981 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006982 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006983 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006984 // take into account dynamic audio policies related changes: if a client is now associated
6985 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006986 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006987 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6988 if (desc->isDuplicated()) {
6989 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006990 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006991 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6992 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6993 continue;
6994 }
6995 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006996 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006997 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6998 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6999 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007000 if (status != OK) {
7001 continue;
7002 }
yucliuf4de36d2020-09-14 14:57:56 -07007003 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007004 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007005 maxLatency = desc->latency();
7006 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007007 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007008 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007009 }
7010 }
7011
Eric Laurent56ed8842022-11-15 16:04:41 +01007012 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007013 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7014 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007015 for (audio_io_handle_t srcOut : srcOutputs) {
7016 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007017 if (desc == nullptr) continue;
7018
7019 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007020 maxLatency = desc->latency();
7021 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007022
Eric Laurent56ed8842022-11-15 16:04:41 +01007023 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007024 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007025 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007026 // a client on a non direct outputs has necessarily a linear PCM format
7027 // so we can call selectOutput() safely
7028 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7029 client->flags(),
7030 client->config().format,
7031 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007032 client->config().sample_rate,
7033 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007034 if (newOutput != srcOut) {
7035 invalidate = true;
7036 break;
7037 }
7038 } else {
7039 sp<IOProfile> profile = getProfileForOutput(newDevices,
7040 client->config().sample_rate,
7041 client->config().format,
7042 client->config().channel_mask,
7043 client->flags(),
7044 true /* directOnly */);
7045 if (profile != desc->mProfile) {
7046 invalidate = true;
7047 break;
7048 }
7049 }
7050 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007051 // mute strategy while moving tracks from one output to another
7052 if (invalidate) {
7053 invalidatedOutputs.push_back(desc);
7054 if (desc->isStrategyActive(psId)) {
7055 setStrategyMute(psId, true, desc);
7056 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7057 newDevices.types());
7058 }
Eric Laurente552edb2014-03-10 17:42:56 -07007059 }
François Gaffiec005e562018-11-06 15:04:49 +01007060 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007061 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007062 connectAudioSource(source);
7063 }
Eric Laurente552edb2014-03-10 17:42:56 -07007064 }
7065
Eric Laurent56ed8842022-11-15 16:04:41 +01007066 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7067 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7068 std::to_string(srcOutputs[0]).c_str(),
7069 std::to_string(dstOutputs[0]).c_str());
7070
François Gaffiec005e562018-11-06 15:04:49 +01007071 // Move effects associated to this stream from previous output to new output
7072 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007073 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007074 }
François Gaffiec005e562018-11-06 15:04:49 +01007075 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007076 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007077 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007078 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007079 desc->setTracksInvalidatedStatusByStrategy(psId);
7080 }
Eric Laurente552edb2014-03-10 17:42:56 -07007081 }
7082 }
7083}
7084
Eric Laurente0720872014-03-11 09:30:41 -07007085void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007086{
François Gaffiec005e562018-11-06 15:04:49 +01007087 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7088 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7089 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007090 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007091 }
Eric Laurente552edb2014-03-10 17:42:56 -07007092}
7093
Kevin Rocard153f92d2018-12-18 18:33:28 -08007094void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007095 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007096 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007097 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007098 for (size_t i = 0; i < mOutputs.size(); i++) {
7099 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7100 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007101 sp<AudioPolicyMix> primaryMix;
7102 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007103 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007104 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7105 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7106 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007107 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7108 for (auto &secondaryMix : secondaryMixes) {
7109 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7110 if (outputDesc != nullptr &&
7111 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7112 secondaryDescs.push_back(outputDesc);
7113 }
7114 }
7115
jiabinc44b3462022-12-08 12:52:31 -08007116 if (status != OK &&
7117 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7118 // When it failed to query secondary output, only invalidate the client that is not
7119 // MMAP. The reason is that MMAP stream will not support secondary output.
7120 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007121 } else if (!std::equal(
7122 client->getSecondaryOutputs().begin(),
7123 client->getSecondaryOutputs().end(),
7124 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007125 if (!audio_is_linear_pcm(client->config().format)) {
7126 // If the format is not PCM, the tracks should be invalidated to get correct
7127 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007128 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007129 } else {
7130 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7131 std::vector<audio_io_handle_t> secondaryOutputIds;
7132 for (const auto &secondaryDesc: secondaryDescs) {
7133 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7134 weakSecondaryDescs.push_back(secondaryDesc);
7135 }
7136 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7137 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007138 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007139 }
7140 }
7141 }
jiabin10a03f12021-05-07 23:46:28 +00007142 if (!trackSecondaryOutputs.empty()) {
7143 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7144 }
jiabinc44b3462022-12-08 12:52:31 -08007145 if (!clientsToInvalidate.empty()) {
7146 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7147 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007148 }
7149}
7150
Eric Laurent2517af32020-11-25 15:31:27 +01007151bool AudioPolicyManager::isScoRequestedForComm() const {
7152 AudioDeviceTypeAddrVector devices;
7153 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7154 for (const auto &device : devices) {
7155 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7156 return true;
7157 }
7158 }
7159 return false;
7160}
7161
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007162bool AudioPolicyManager::isHearingAidUsedForComm() const {
7163 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7164 true /*fromCache*/);
7165 for (const auto &device : devices) {
7166 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7167 return true;
7168 }
7169 }
7170 return false;
7171}
7172
7173
Eric Laurente0720872014-03-11 09:30:41 -07007174void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007175{
François Gaffie53615e22015-03-19 09:24:12 +01007176 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007177 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007178 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007179 return;
7180 }
7181
Eric Laurent3a4311c2014-03-17 12:00:47 -07007182 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007183 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7184 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007185 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007186
7187 // if suspended, restore A2DP output if:
7188 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007189 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007190 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007191 //
Eric Laurentf732e072016-08-03 19:30:28 -07007192 // if not suspended, suspend A2DP output if:
7193 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007194 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007195 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007196 //
7197 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007198 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007199 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007200 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007201 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007202
7203 mpClientInterface->restoreOutput(a2dpOutput);
7204 mA2dpSuspended = false;
7205 }
7206 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007207 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007208 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007209 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007210 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007211
7212 mpClientInterface->suspendOutput(a2dpOutput);
7213 mA2dpSuspended = true;
7214 }
7215 }
7216}
7217
François Gaffie11d30102018-11-02 16:09:09 +01007218DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7219 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007220{
François Gaffiedb1755b2023-09-01 11:50:35 +02007221 if (outputDesc == nullptr) {
7222 return DeviceVector{};
7223 }
François Gaffie11d30102018-11-02 16:09:09 +01007224
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007225 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007226 if (index >= 0) {
7227 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007228 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007229 ALOGV("%s device %s forced by patch %d", __func__,
7230 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7231 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007232 }
7233 }
7234
Dean Wheatley514b4312020-06-17 21:45:00 +10007235 // Do not retrieve engine device for outputs through MSD
7236 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7237 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7238 return outputDesc->devices();
7239 }
7240
Eric Laurent97ac8712018-07-27 18:59:02 -07007241 // Honor explicit routing requests only if no client using default routing is active on this
7242 // input: a specific app can not force routing for other apps by setting a preferred device.
7243 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007244 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007245 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007246 if (device != nullptr) {
7247 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007248 }
7249
François Gaffiea807ef92018-11-05 10:44:33 +01007250 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7251 // of setForceUse / Default Bus device here
7252 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7253 if (device != nullptr) {
7254 return DeviceVector(device);
7255 }
7256
François Gaffiedb1755b2023-09-01 11:50:35 +02007257 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007258 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7259 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7260 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307261 auto hasStreamActive = [&](auto stream) {
7262 return hasStream(streams, stream) && isStreamActive(stream, 0);
7263 };
Eric Laurent484e9272018-06-07 17:29:23 -07007264
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307265 auto doGetOutputDevicesForVoice = [&]() {
7266 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007267 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307268 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007269 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7270 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307271 };
7272
7273 // With low-latency playing on speaker, music on WFD, when the first low-latency
7274 // output is stopped, getNewOutputDevices checks for a product strategy
7275 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007276 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307277 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7278 // stream is associated to the output descriptor.
7279 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7280 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7281 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7282 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007283 // Retrieval of devices for voice DL is done on primary output profile, cannot
7284 // check the route (would force modifying configuration file for this profile)
7285 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7286 break;
7287 }
Eric Laurente552edb2014-03-10 17:42:56 -07007288 }
François Gaffiec005e562018-11-06 15:04:49 +01007289 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007290 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007291}
7292
François Gaffie11d30102018-11-02 16:09:09 +01007293sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7294 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007295{
François Gaffie11d30102018-11-02 16:09:09 +01007296 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007297
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007298 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007299 if (index >= 0) {
7300 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007301 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007302 ALOGV("getNewInputDevice() device %s forced by patch %d",
7303 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7304 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007305 }
7306 }
7307
Eric Laurent97ac8712018-07-27 18:59:02 -07007308 // Honor explicit routing requests only if no client using default routing is active on this
7309 // input: a specific app can not force routing for other apps by setting a preferred device.
7310 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007311 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7312 if (device != nullptr) {
7313 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007314 }
7315
Eric Laurentdc95a252018-04-12 12:46:56 -07007316 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007317 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007318 audio_attributes_t attributes;
7319 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007320 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007321 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7322 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007323 attributes = topClient->attributes();
7324 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007325 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007326 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007327 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7328 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007329 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007330 }
7331
Francois Gaffie716e1432019-01-14 16:58:59 +01007332 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7333 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007334 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007335 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007336 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007337 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007338
Eric Laurente552edb2014-03-10 17:42:56 -07007339 return device;
7340}
7341
Eric Laurent794fde22016-03-11 09:50:45 -08007342bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7343 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007344 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007345}
7346
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007347status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007348 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007349 if (devices == nullptr) {
7350 return BAD_VALUE;
7351 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007352
Andy Hung6d23c0f2022-02-16 09:37:15 -08007353 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007354 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7355 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007356 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007357 for (const auto& device : curDevices) {
7358 devices->push_back(device->getDeviceTypeAddr());
7359 }
7360 return NO_ERROR;
7361}
7362
Eric Laurente0720872014-03-11 09:30:41 -07007363void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007364 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007365 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007366 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007367 updateDevicesAndOutputs();
7368 break;
7369 default:
7370 break;
7371 }
7372}
7373
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007374uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007375
7376 // skip beacon mute management if a dedicated TTS output is available
7377 if (mTtsOutputAvailable) {
7378 return 0;
7379 }
7380
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007381 switch(event) {
7382 case STARTING_OUTPUT:
7383 mBeaconMuteRefCount++;
7384 break;
7385 case STOPPING_OUTPUT:
7386 if (mBeaconMuteRefCount > 0) {
7387 mBeaconMuteRefCount--;
7388 }
7389 break;
7390 case STARTING_BEACON:
7391 mBeaconPlayingRefCount++;
7392 break;
7393 case STOPPING_BEACON:
7394 if (mBeaconPlayingRefCount > 0) {
7395 mBeaconPlayingRefCount--;
7396 }
7397 break;
7398 }
7399
7400 if (mBeaconMuteRefCount > 0) {
7401 // any playback causes beacon to be muted
7402 return setBeaconMute(true);
7403 } else {
7404 // no other playback: unmute when beacon starts playing, mute when it stops
7405 return setBeaconMute(mBeaconPlayingRefCount == 0);
7406 }
7407}
7408
7409uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7410 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7411 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7412 // keep track of muted state to avoid repeating mute/unmute operations
7413 if (mBeaconMuted != mute) {
7414 // mute/unmute AUDIO_STREAM_TTS on all outputs
7415 ALOGV("\t muting %d", mute);
7416 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007417 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7418 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7419 ALOGV("\t no tts volume source available");
7420 return 0;
7421 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007422 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007423 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007424 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007425 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007426 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007427 maxLatency = latency;
7428 }
7429 }
7430 mBeaconMuted = mute;
7431 return maxLatency;
7432 }
7433 return 0;
7434}
7435
Eric Laurente0720872014-03-11 09:30:41 -07007436void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007437{
François Gaffiec005e562018-11-06 15:04:49 +01007438 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007439 mPreviousOutputs = mOutputs;
7440}
7441
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007442uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007443 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007444 uint32_t delayMs)
7445{
7446 // mute/unmute strategies using an incompatible device combination
7447 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7448 // if unmuting, unmute only after the specified delay
7449 if (outputDesc->isDuplicated()) {
7450 return 0;
7451 }
7452
7453 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007454 DeviceVector devices = outputDesc->devices();
7455 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007456
François Gaffiec005e562018-11-06 15:04:49 +01007457 auto productStrategies = mEngine->getOrderedProductStrategies();
7458 for (const auto &productStrategy : productStrategies) {
7459 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7460 DeviceVector curDevices =
7461 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7462 curDevices = curDevices.filter(outputDesc->supportedDevices());
7463 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007464 bool doMute = false;
7465
François Gaffiec005e562018-11-06 15:04:49 +01007466 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007467 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007468 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7469 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007470 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007471 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007472 }
Eric Laurent99401132014-05-07 19:48:15 -07007473 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007474 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007475 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007476 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007477 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007478 continue;
7479 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307480 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007481 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7482 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7483 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007484 if (mute) {
7485 // FIXME: should not need to double latency if volume could be applied
7486 // immediately by the audioflinger mixer. We must account for the delay
7487 // between now and the next time the audioflinger thread for this output
7488 // will process a buffer (which corresponds to one buffer size,
7489 // usually 1/2 or 1/4 of the latency).
7490 if (muteWaitMs < desc->latency() * 2) {
7491 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007492 }
7493 }
7494 }
7495 }
7496 }
7497 }
7498
Eric Laurent99401132014-05-07 19:48:15 -07007499 // temporary mute output if device selection changes to avoid volume bursts due to
7500 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007501 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007502 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007503
Eric Laurentdc462862016-07-19 12:29:53 -07007504 if (muteWaitMs < tempMuteWaitMs) {
7505 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007506 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007507
7508 // If recommended duration is defined, replace temporary mute duration to avoid
7509 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7510 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7511 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7512 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7513 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7514
François Gaffieaaac0fd2018-11-22 17:56:39 +01007515 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7516 // make sure that we do not start the temporary mute period too early in case of
7517 // delayed device change
7518 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7519 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007520 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007521 }
7522 }
7523
Eric Laurente552edb2014-03-10 17:42:56 -07007524 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7525 if (muteWaitMs > delayMs) {
7526 muteWaitMs -= delayMs;
7527 usleep(muteWaitMs * 1000);
7528 return muteWaitMs;
7529 }
7530 return 0;
7531}
7532
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307533uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7534 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007535 const DeviceVector &devices,
7536 bool force,
7537 int delayMs,
7538 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007539 bool requiresMuteCheck, bool requiresVolumeCheck,
7540 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007541{
jiabin3ff8d7d2022-12-13 06:27:44 +00007542 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307543 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7544 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7545 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007546 uint32_t muteWaitMs;
7547
7548 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307549 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007550 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307551 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007552 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007553 return muteWaitMs;
7554 }
Eric Laurente552edb2014-03-10 17:42:56 -07007555
7556 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007557 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007558 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007559 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007560
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307561 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7562 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007563
7564 if (!filteredDevices.isEmpty()) {
7565 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007566 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007567
7568 // if the outputs are not materially active, there is no need to mute.
7569 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007570 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007571 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307572 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7573 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007574 muteWaitMs = 0;
7575 }
Eric Laurente552edb2014-03-10 17:42:56 -07007576
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007577 bool outputRouted = outputDesc->isRouted();
7578
Eric Laurent79ea9582020-06-11 18:49:24 -07007579 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7580 // output profile or if new device is not supported AND previous device(s) is(are) still
7581 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007582 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307583 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7584 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007585 // restore previous device after evaluating strategy mute state
7586 outputDesc->setDevices(prevDevices);
7587 return muteWaitMs;
7588 }
7589
Eric Laurente552edb2014-03-10 17:42:56 -07007590 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007591 // the requested device is AUDIO_DEVICE_NONE
7592 // OR the requested device is the same as current device
7593 // AND force is not specified
7594 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007595 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007596 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307597 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7598 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7599 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007600 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307601 ALOGV("%s %s setting same device on routed output, force apply volumes",
7602 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007603 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7604 }
Eric Laurente552edb2014-03-10 17:42:56 -07007605 return muteWaitMs;
7606 }
7607
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307608 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7609 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007610
Eric Laurente552edb2014-03-10 17:42:56 -07007611 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007612 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007613 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007614 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007615 PatchBuilder patchBuilder;
7616 patchBuilder.addSource(outputDesc);
7617 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7618 for (const auto &filteredDevice : filteredDevices) {
7619 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007620 }
7621
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007622 // Add half reported latency to delayMs when muteWaitMs is null in order
7623 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007624 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7625 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7626 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007627 }
Eric Laurente552edb2014-03-10 17:42:56 -07007628
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007629 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7630 if (!skipMuteDelay) {
7631 // update stream volumes according to new device
7632 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7633 }
Eric Laurente552edb2014-03-10 17:42:56 -07007634
7635 return muteWaitMs;
7636}
7637
Eric Laurentc75307b2015-03-17 15:29:32 -07007638status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007639 int delayMs,
7640 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007641{
Eric Laurent6a94d692014-05-20 11:18:06 -07007642 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007643 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7644 return INVALID_OPERATION;
7645 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007646 if (patchHandle) {
7647 index = mAudioPatches.indexOfKey(*patchHandle);
7648 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007649 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007650 }
7651 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007652 return INVALID_OPERATION;
7653 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007654 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007655 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007656 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007657 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007658 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007659 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007660 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007661 return status;
7662}
7663
7664status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007665 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007666 bool force,
7667 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007668{
7669 status_t status = NO_ERROR;
7670
Eric Laurent1f2f2232014-06-02 12:01:23 -07007671 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007672 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7673 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007674
François Gaffie11d30102018-11-02 16:09:09 +01007675 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007676 PatchBuilder patchBuilder;
7677 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007678 // AUDIO_SOURCE_HOTWORD is for internal use only:
7679 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007680 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7681 auto result = usecase;
7682 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7683 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7684 }
7685 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007686 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007687 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007688 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007689 }
7690 }
7691 return status;
7692}
7693
Eric Laurent6a94d692014-05-20 11:18:06 -07007694status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7695 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007696{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007697 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007698 ssize_t index;
7699 if (patchHandle) {
7700 index = mAudioPatches.indexOfKey(*patchHandle);
7701 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007702 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007703 }
7704 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007705 return INVALID_OPERATION;
7706 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007707 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007708 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007709 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007710 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007711 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007712 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007713 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007714 return status;
7715}
7716
François Gaffie11d30102018-11-02 16:09:09 +01007717sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007718 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007719 audio_format_t& format,
7720 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007721 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007722{
7723 // Choose an input profile based on the requested capture parameters: select the first available
7724 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007725 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007726
Atneya Nair0f0a8032022-12-12 16:20:12 -08007727 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7728 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7729 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7730
7731 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007732
jiabin2fd710d2022-05-02 23:20:22 +00007733 for (;;) {
7734 sp<IOProfile> firstInexact = nullptr;
7735 uint32_t updatedSamplingRate = 0;
7736 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7737 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7738 for (const auto& hwModule : mHwModules) {
7739 for (const auto& profile : hwModule->getInputProfiles()) {
7740 // profile->log();
7741 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007742 if (profile->getCompatibilityScore(
7743 DeviceVector(device),
7744 samplingRate,
7745 &updatedSamplingRate,
7746 format,
7747 &updatedFormat,
7748 channelMask,
7749 &updatedChannelMask,
7750 // FIXME ugly cast
7751 (audio_output_flags_t) flags,
7752 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7753 samplingRate = updatedSamplingRate;
7754 format = updatedFormat;
7755 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007756 return profile;
7757 }
jiabin66acc432024-02-06 00:57:36 +00007758 if (firstInexact == nullptr
7759 && profile->getCompatibilityScore(
7760 DeviceVector(device),
7761 samplingRate,
7762 &updatedSamplingRate,
7763 format,
7764 &updatedFormat,
7765 channelMask,
7766 &updatedChannelMask,
7767 // FIXME ugly cast
7768 (audio_output_flags_t) flags,
7769 false /*exactMatchRequiredForInputFlags*/)
7770 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007771 firstInexact = profile;
7772 }
7773 }
7774 }
7775
7776 if (firstInexact != nullptr) {
7777 samplingRate = updatedSamplingRate;
7778 format = updatedFormat;
7779 channelMask = updatedChannelMask;
7780 return firstInexact;
7781 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7782 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7783 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7784 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7785 flags = AUDIO_INPUT_FLAG_NONE;
7786 } else { // fail
7787 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7788 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7789 samplingRate, format, channelMask, oriFlags);
7790 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007791 }
7792 }
jiabin2fd710d2022-05-02 23:20:22 +00007793
7794 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007795}
7796
François Gaffieaaac0fd2018-11-22 17:56:39 +01007797float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7798 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007799 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007800 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007801{
jiabin9a3361e2019-10-01 09:38:30 -07007802 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007803
7804 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7805 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7806 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7807 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007808 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7809 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7810 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7811 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7812 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007813 // Verify that the current volume source is not the ringer volume to prevent recursively
7814 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7815 // to the same volume group.
7816 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007817 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7818 mOutputs.isActive(ringVolumeSrc, 0)) {
7819 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007820 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007821 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007822 }
7823
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007824 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007825 if ((volumeSource != callVolumeSrc && (isInCall() ||
7826 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007827 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007828 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7829 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007830 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7831 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7832 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007833 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007834 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007835 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007836 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007837 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007838 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007839 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7840 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7841 // programmatically muted.
7842 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7843 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7844 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007845 bool exemptFromCapping =
7846 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7847 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007848 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7849 volumeSource, volumeDb);
7850 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007851 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7852 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7853 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007854 }
7855 }
Eric Laurente552edb2014-03-10 17:42:56 -07007856 // if a headset is connected, apply the following rules to ring tones and notifications
7857 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007858 // - always attenuate notifications volume by 6dB
7859 // - attenuate ring tones volume by 6dB unless music is not playing and
7860 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007861 // - if music is playing, always limit the volume to current music volume,
7862 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007863 if (!Intersection(deviceTypes,
7864 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7865 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007866 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7867 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007868 ((volumeSource == alarmVolumeSrc ||
7869 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007870 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7871 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7872 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007873 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7874 curves.canBeMuted()) {
7875
Eric Laurente552edb2014-03-10 17:42:56 -07007876 // when the phone is ringing we must consider that music could have been paused just before
7877 // by the music application and behave as if music was active if the last music track was
7878 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007879 // Verify that the current volume source is not the music volume to prevent recursively
7880 // calling to compute volume. This could happen in cases where music and
7881 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7882 if (volumeSource != musicVolumeSrc &&
7883 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7884 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007885 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007886 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007887 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7888 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007889 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007890 float musicVolDb = computeVolume(musicCurves,
7891 musicVolumeSrc,
7892 musicCurves.getVolumeIndex(musicDevice),
7893 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007894 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7895 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7896 if (volumeDb > minVolDb) {
7897 volumeDb = minVolDb;
7898 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007899 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007900 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7901 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7902 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007903 // on A2DP, also ensure notification volume is not too low compared to media when
7904 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007905 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007906 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007907 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7908 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007909 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7910 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007911 }
7912 }
jiabin9a3361e2019-10-01 09:38:30 -07007913 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007914 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007915 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007916 }
7917 }
7918
François Gaffie43c73442018-11-08 08:21:55 +01007919 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007920}
7921
Eric Laurent3839bc02018-07-10 18:33:34 -07007922int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007923 VolumeSource fromVolumeSource,
7924 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007925{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007926 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007927 return srcIndex;
7928 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007929 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7930 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007931 float minSrc = (float)srcCurves.getVolumeIndexMin();
7932 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7933 float minDst = (float)dstCurves.getVolumeIndexMin();
7934 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007935
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007936 // preserve mute request or correct range
7937 if (srcIndex < minSrc) {
7938 if (srcIndex == 0) {
7939 return 0;
7940 }
7941 srcIndex = minSrc;
7942 } else if (srcIndex > maxSrc) {
7943 srcIndex = maxSrc;
7944 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007945 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7946}
7947
François Gaffieaaac0fd2018-11-22 17:56:39 +01007948status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7949 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007950 int index,
7951 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007952 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007953 int delayMs,
7954 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007955{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007956 // do not change actual attributes volume if the attributes is muted
7957 if (outputDesc->isMuted(volumeSource)) {
7958 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7959 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007960 return NO_ERROR;
7961 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007962
Eric Laurentae6e88c2024-01-10 14:42:57 +01007963 bool isVoiceVolSrc;
7964 bool isBtScoVolSrc;
7965 if (!isVolumeConsistentForCalls(
7966 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007967 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007968 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007969 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007970 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007971
jiabin9a3361e2019-10-01 09:38:30 -07007972 if (deviceTypes.empty()) {
7973 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007974 index = curves.getVolumeIndex(deviceTypes);
7975 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7976 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007977 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007978
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007979 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7980 ALOGE("invalid volume index range");
7981 return BAD_VALUE;
7982 }
7983
jiabin9a3361e2019-10-01 09:38:30 -07007984 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7985 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007986 // Force VoIP volume to max for bluetooth SCO device except if muted
7987 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007988 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007989 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007990 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007991 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007992 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7993 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007994
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007995 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007996 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007997 }
Eric Laurente552edb2014-03-10 17:42:56 -07007998 return NO_ERROR;
7999}
8000
Eric Laurentae6e88c2024-01-10 14:42:57 +01008001void AudioPolicyManager::setVoiceVolume(
8002 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8003 float voiceVolume;
8004 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8005 // by the headset
8006 if (isVoiceVolSrc) {
8007 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8008 } else {
8009 voiceVolume = index == 0 ? 0.0 : 1.0;
8010 }
8011 if (voiceVolume != mLastVoiceVolume) {
8012 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8013 mLastVoiceVolume = voiceVolume;
8014 }
8015}
8016
8017bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8018 const DeviceTypeSet& deviceTypes,
8019 bool& isVoiceVolSrc,
8020 bool& isBtScoVolSrc,
8021 const char* caller) {
8022 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8023 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8024 const bool isScoRequested = isScoRequestedForComm();
8025 const bool isHAUsed = isHearingAidUsedForComm();
8026
8027 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8028 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8029
8030 if ((callVolSrc != btScoVolSrc) &&
8031 ((isVoiceVolSrc && isScoRequested) ||
8032 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8033 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8034 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8035 volumeSource, isScoRequested ? " " : " not ");
8036 return false;
8037 }
8038 return true;
8039}
8040
Eric Laurentc75307b2015-03-17 15:29:32 -07008041void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008042 const DeviceTypeSet& deviceTypes,
8043 int delayMs,
8044 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008045{
jiabincd510522020-01-22 09:40:55 -08008046 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008047 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8048 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8049 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008050 curves.getVolumeIndex(deviceTypes),
8051 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008052 }
8053}
8054
François Gaffiec005e562018-11-06 15:04:49 +01008055void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8056 bool on,
8057 const sp<AudioOutputDescriptor>& outputDesc,
8058 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008059 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008060{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008061 std::vector<VolumeSource> sourcesToMute;
8062 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8063 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8064 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008065 VolumeSource source = toVolumeSource(attributes, false);
8066 if ((source != VOLUME_SOURCE_NONE) &&
8067 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8068 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008069 sourcesToMute.push_back(source);
8070 }
Eric Laurente552edb2014-03-10 17:42:56 -07008071 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008072 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008073 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008074 }
8075
Eric Laurente552edb2014-03-10 17:42:56 -07008076}
8077
François Gaffieaaac0fd2018-11-22 17:56:39 +01008078void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8079 bool on,
8080 const sp<AudioOutputDescriptor>& outputDesc,
8081 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008082 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008083{
jiabin9a3361e2019-10-01 09:38:30 -07008084 if (deviceTypes.empty()) {
8085 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008086 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008087 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008088 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008089 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008090 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008091 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008092 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8093 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008094 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008095 }
8096 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008097 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8098 // ignored
8099 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008100 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008101 if (!outputDesc->isMuted(volumeSource)) {
8102 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008103 return;
8104 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008105 if (outputDesc->decMuteCount(volumeSource) == 0) {
8106 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008107 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008108 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008109 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008110 delayMs);
8111 }
8112 }
8113}
8114
François Gaffie53615e22015-03-19 09:24:12 +01008115bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8116{
François Gaffiec005e562018-11-06 15:04:49 +01008117 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008118 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8119 return true;
8120 }
8121
8122 // has known usage?
8123 switch (paa->usage) {
8124 case AUDIO_USAGE_UNKNOWN:
8125 case AUDIO_USAGE_MEDIA:
8126 case AUDIO_USAGE_VOICE_COMMUNICATION:
8127 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8128 case AUDIO_USAGE_ALARM:
8129 case AUDIO_USAGE_NOTIFICATION:
8130 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8131 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8132 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8133 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8134 case AUDIO_USAGE_NOTIFICATION_EVENT:
8135 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8136 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8137 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8138 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008139 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008140 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008141 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008142 case AUDIO_USAGE_EMERGENCY:
8143 case AUDIO_USAGE_SAFETY:
8144 case AUDIO_USAGE_VEHICLE_STATUS:
8145 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008146 break;
8147 default:
8148 return false;
8149 }
8150 return true;
8151}
8152
François Gaffie2110e042015-03-24 08:41:51 +01008153audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8154{
8155 return mEngine->getForceUse(usage);
8156}
8157
Eric Laurent96d1dda2022-03-14 17:14:19 +01008158bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008159 return isStateInCall(mEngine->getPhoneState());
8160}
8161
Eric Laurent96d1dda2022-03-14 17:14:19 +01008162bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008163 return is_state_in_call(state);
8164}
8165
Eric Laurentf9cccec2022-11-16 19:12:00 +01008166bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008167 audio_mode_t mode = mEngine->getPhoneState();
8168 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008169 || (mode == AUDIO_MODE_CALL_SCREEN)
8170 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008171}
8172
Eric Laurentf9cccec2022-11-16 19:12:00 +01008173bool AudioPolicyManager::isInCallOrScreening() const {
8174 audio_mode_t mode = mEngine->getPhoneState();
8175 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8176}
8177
Eric Laurentd60560a2015-04-10 11:31:20 -07008178void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8179{
8180 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008181 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008182 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008183 sourceDesc->sinkDevice()->equals(deviceDesc))
8184 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008185 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008186 }
8187 }
8188
8189 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8190 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8191 bool release = false;
8192 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8193 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8194 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8195 source->ext.device.type == deviceDesc->type()) {
8196 release = true;
8197 }
8198 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008199 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008200 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8201 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8202 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008203 sink->ext.device.type == deviceDesc->type() &&
8204 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8205 || strncmp(sink->ext.device.address, address,
8206 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008207 release = true;
8208 }
8209 }
8210 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008211 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8212 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008213 }
8214 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008215
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008216 mInputs.clearSessionRoutesForDevice(deviceDesc);
8217
Francois Gaffie716e1432019-01-14 16:58:59 +01008218 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008219}
8220
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008221void AudioPolicyManager::modifySurroundFormats(
8222 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008223 std::unordered_set<audio_format_t> enforcedSurround(
8224 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008225 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008226 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008227 allSurround.insert(pair.first);
8228 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8229 }
Phil Burk09bc4612016-02-24 15:58:15 -08008230
8231 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8232 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008233 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008234 // This is the resulting set of formats depending on the surround mode:
8235 // 'all surround' = allSurround
8236 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8237 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8238 // 'manual surround' = mManualSurroundFormats
8239 // AUTO: formats v 'enforced surround'
8240 // ALWAYS: formats v 'all surround' v 'enforced surround'
8241 // NEVER: formats ^ 'non-surround'
8242 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008243
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008244 std::unordered_set<audio_format_t> formatSet;
8245 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8246 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008247 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008248 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008249 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008250 formatSet.insert(*formatIter);
8251 }
8252 }
8253 } else {
8254 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8255 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008256 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008257
jiabin81772902018-04-02 17:52:27 -07008258 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008259 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008260 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8261 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8262 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008263 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008264 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8265 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8266 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008267 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008268 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008269 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008270 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008271 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008272 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008273}
8274
jiabin06e4bab2019-07-29 10:13:34 -07008275void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8276 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008277 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8278 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8279
8280 // If NEVER, then remove support for channelMasks > stereo.
8281 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008282 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8283 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008284 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008285 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008286 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008287 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008288 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008289 }
8290 }
jiabin81772902018-04-02 17:52:27 -07008291 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8292 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8293 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008294 bool supports5dot1 = false;
8295 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008296 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008297 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8298 supports5dot1 = true;
8299 break;
8300 }
8301 }
8302 // If not then add 5.1 support.
8303 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008304 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008305 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008306 }
Phil Burk09bc4612016-02-24 15:58:15 -08008307 }
8308}
8309
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008310void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008311 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008312 const sp<IOProfile>& profile) {
8313 if (!profile->hasDynamicAudioProfile()) {
8314 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008315 }
François Gaffie112b0af2015-11-19 16:13:25 +01008316
jiabin12537fc2023-10-12 17:56:08 +00008317 audio_port_v7 devicePort;
8318 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008319
jiabin12537fc2023-10-12 17:56:08 +00008320 audio_port_v7 mixPort;
8321 profile->toAudioPort(&mixPort);
8322 mixPort.ext.mix.handle = ioHandle;
8323
8324 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8325 if (status != NO_ERROR) {
8326 ALOGE("%s failed to query the attributes of the mix port", __func__);
8327 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008328 }
jiabin12537fc2023-10-12 17:56:08 +00008329
8330 std::set<audio_format_t> supportedFormats;
8331 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8332 supportedFormats.insert(mixPort.audio_profiles[i].format);
8333 }
8334 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8335 mReportedFormatsMap[devDesc] = formats;
8336
8337 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8338 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8339 modifySurroundFormats(devDesc, &formats);
8340 size_t modifiedNumProfiles = 0;
8341 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8342 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8343 formats.end()) {
8344 // Skip the format that is not present after modifying surround formats.
8345 continue;
8346 }
8347 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8348 sizeof(struct audio_profile));
8349 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8350 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8351 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8352 modifySurroundChannelMasks(&channels);
8353 std::copy(channels.begin(), channels.end(),
8354 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8355 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8356 }
8357 mixPort.num_audio_profiles = modifiedNumProfiles;
8358 }
8359 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008360}
Eric Laurentd60560a2015-04-10 11:31:20 -07008361
Mikhail Naganovdc769682018-05-04 15:34:08 -07008362status_t AudioPolicyManager::installPatch(const char *caller,
8363 audio_patch_handle_t *patchHandle,
8364 AudioIODescriptorInterface *ioDescriptor,
8365 const struct audio_patch *patch,
8366 int delayMs)
8367{
8368 ssize_t index = mAudioPatches.indexOfKey(
8369 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8370 *patchHandle : ioDescriptor->getPatchHandle());
8371 sp<AudioPatch> patchDesc;
8372 status_t status = installPatch(
8373 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8374 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008375 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008376 }
8377 return status;
8378}
8379
8380status_t AudioPolicyManager::installPatch(const char *caller,
8381 ssize_t index,
8382 audio_patch_handle_t *patchHandle,
8383 const struct audio_patch *patch,
8384 int delayMs,
8385 uid_t uid,
8386 sp<AudioPatch> *patchDescPtr)
8387{
8388 sp<AudioPatch> patchDesc;
8389 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8390 if (index >= 0) {
8391 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008392 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008393 }
8394
8395 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8396 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8397 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8398 if (status == NO_ERROR) {
8399 if (index < 0) {
8400 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008401 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008402 } else {
8403 patchDesc->mPatch = *patch;
8404 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008405 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008406 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008407 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008408 }
8409 nextAudioPortGeneration();
8410 mpClientInterface->onAudioPatchListUpdate();
8411 }
8412 if (patchDescPtr) *patchDescPtr = patchDesc;
8413 return status;
8414}
8415
jiabinbce0c1d2020-10-05 11:20:18 -07008416bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8417{
8418 const TrackClientVector activeClients = output->getActiveClients();
8419 if (activeClients.empty()) {
8420 return true;
8421 }
8422 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8423 if (index < 0) {
8424 ALOGE("%s, no audio patch found while there are active clients on output %d",
8425 __func__, output->getId());
8426 return false;
8427 }
8428 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8429 DeviceVector routedDevices;
8430 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8431 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8432 patchDesc->mPatch.sinks[i].id);
8433 if (device == nullptr) {
8434 ALOGE("%s, no audio device found with id(%d)",
8435 __func__, patchDesc->mPatch.sinks[i].id);
8436 return false;
8437 }
8438 routedDevices.add(device);
8439 }
8440 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008441 if (client->isInvalid()) {
8442 // No need to take care about invalidated clients.
8443 continue;
8444 }
jiabinbce0c1d2020-10-05 11:20:18 -07008445 sp<DeviceDescriptor> preferredDevice =
8446 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8447 if (mEngine->getOutputDevicesForAttributes(
8448 client->attributes(), preferredDevice, false) == routedDevices) {
8449 return false;
8450 }
8451 }
8452 return true;
8453}
8454
8455sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008456 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008457 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8458 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008459{
8460 for (const auto& device : devices) {
8461 // TODO: This should be checking if the profile supports the device combo.
8462 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008463 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8464 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008465 return nullptr;
8466 }
8467 }
8468 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8469 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008470 status_t status = desc->open(halConfig, mixerConfig, devices,
8471 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008472 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008473 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008474 return nullptr;
8475 }
jiabin14b50cc2023-12-13 19:01:52 +00008476 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8477 auto portConfig = desc->getConfig();
8478 for (const auto& device : devices) {
8479 device->setPreferredConfig(&portConfig);
8480 }
8481 }
jiabinbce0c1d2020-10-05 11:20:18 -07008482
8483 // Here is where the out_set_parameters() for card & device gets called
8484 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8485 const audio_devices_t deviceType = device->type();
8486 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008487 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008488 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8489 mpClientInterface->setParameters(output, String8(param));
8490 free(param);
8491 }
jiabin12537fc2023-10-12 17:56:08 +00008492 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008493 if (!profile->hasValidAudioProfile()) {
8494 ALOGW("%s() missing param", __func__);
8495 desc->close();
8496 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008497 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8498 // Reopen the output with the best audio profile picked by APM when the profile supports
8499 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008500 desc->close();
8501 output = AUDIO_IO_HANDLE_NONE;
8502 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8503 profile->pickAudioProfile(
8504 config.sample_rate, config.channel_mask, config.format);
8505 config.offload_info.sample_rate = config.sample_rate;
8506 config.offload_info.channel_mask = config.channel_mask;
8507 config.offload_info.format = config.format;
8508
jiabina84c3d32022-12-02 18:59:55 +00008509 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008510 if (status != NO_ERROR) {
8511 return nullptr;
8512 }
8513 }
8514
8515 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008516
baek.kim -61c20122022-07-27 10:05:32 +00008517 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8518 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8519
jiabinbce0c1d2020-10-05 11:20:18 -07008520 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8521 sp<AudioPolicyMix> policyMix;
8522 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8523 policyMix->setOutput(desc);
8524 desc->mPolicyMix = policyMix;
8525 } else {
8526 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008527 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008528 }
8529
baek.kim -61c20122022-07-27 10:05:32 +00008530 } else if (hasPrimaryOutput() && speaker != nullptr
8531 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008532 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8533 // no duplicated output for:
8534 // - direct outputs
8535 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008536 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008537 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8538
8539 //TODO: configure audio effect output stage here
8540
8541 // open a duplicating output thread for the new output and the primary output
8542 sp<SwAudioOutputDescriptor> dupOutputDesc =
8543 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8544 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8545 if (status == NO_ERROR) {
8546 // add duplicated output descriptor
8547 addOutput(duplicatedOutput, dupOutputDesc);
8548 } else {
8549 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8550 mPrimaryOutput->mIoHandle, output);
8551 desc->close();
8552 removeOutput(output);
8553 nextAudioPortGeneration();
8554 return nullptr;
8555 }
8556 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008557 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8558 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8559 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008560 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008561 }
jiabinbce0c1d2020-10-05 11:20:18 -07008562 return desc;
8563}
8564
jiabinf1c73972022-04-14 16:28:52 -07008565status_t AudioPolicyManager::getDevicesForAttributes(
8566 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8567 // Devices are determined in the following precedence:
8568 //
8569 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8570 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8571 //
8572 // If no such dynamic policy then
8573 // 2) Devices containing an active client using setPreferredDevice
8574 // with same strategy as the attributes.
8575 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8576 //
8577 // If no corresponding active client with setPreferredDevice then
8578 // 3) Devices associated with the strategy determined by the attributes
8579 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8580 //
8581 // See related getOutputForAttrInt().
8582
8583 // check dynamic policies but only for primary descriptors (secondary not used for audible
8584 // audio routing, only used for duplication for playback capture)
8585 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008586 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008587 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008588 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8589 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8590 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008591 if (status != OK) {
8592 return status;
8593 }
8594
8595 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8596 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8597 // as they are unaffected by device/stream volume
8598 // (per SwAudioOutputDescriptor::isFixedVolume()).
8599 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8600 ) {
8601 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8602 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8603 devices.add(deviceDesc);
8604 } else {
8605 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8606 // which selects setPreferredDevice if active. This means forVolume call
8607 // will take an active setPreferredDevice, if such exists.
8608
8609 devices = mEngine->getOutputDevicesForAttributes(
8610 attr, nullptr /* preferredDevice */, false /* fromCache */);
8611 }
8612
8613 if (forVolume) {
8614 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8615 // for single volume control in AudioService (such relationship should exist if
8616 // SPEAKER_SAFE is present).
8617 //
8618 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8619 DeviceVector speakerSafeDevices =
8620 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8621 if (!speakerSafeDevices.isEmpty()) {
8622 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8623 devices.remove(speakerSafeDevices);
8624 }
8625 }
8626
8627 return NO_ERROR;
8628}
8629
8630status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8631 AudioProfileVector& audioProfiles,
8632 uint32_t flags,
8633 bool isInput) {
8634 for (const auto& hwModule : mHwModules) {
8635 // the MSD module checks for different conditions
8636 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8637 continue;
8638 }
8639 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8640 : hwModule->getOutputProfiles();
8641 for (const auto& profile : ioProfiles) {
8642 if (!profile->areAllDevicesSupported(devices) ||
8643 !profile->isCompatibleProfileForFlags(
8644 flags, false /*exactMatchRequiredForInputFlags*/)) {
8645 continue;
8646 }
8647 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8648 }
8649 }
8650
8651 if (!isInput) {
8652 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8653 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8654 if (msdModule != nullptr) {
8655 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8656 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8657 for (const auto &profile: msdModule->getOutputProfiles()) {
8658 if (!profile->asAudioPort()->isDirectOutput()) {
8659 continue;
8660 }
8661 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8662 }
8663 } else {
8664 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8665 }
8666 }
8667 }
8668
8669 return NO_ERROR;
8670}
8671
jiabin3ff8d7d2022-12-13 06:27:44 +00008672sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8673 const audio_config_t *config,
8674 audio_output_flags_t flags,
8675 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008676 closeOutput(outputDesc->mIoHandle);
8677 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8678 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8679 if (preferredOutput == nullptr) {
8680 ALOGE("%s failed to reopen output device=%d, caller=%s",
8681 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008682 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008683 return preferredOutput;
8684}
8685
8686void AudioPolicyManager::reopenOutputsWithDevices(
8687 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8688 for (const auto& [output, devices] : outputsToReopen) {
8689 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8690 closeOutput(output);
8691 openOutputWithProfileAndDevice(desc->mProfile, devices);
8692 }
jiabina84c3d32022-12-02 18:59:55 +00008693}
8694
jiabinc44b3462022-12-08 12:52:31 -08008695PortHandleVector AudioPolicyManager::getClientsForStream(
8696 audio_stream_type_t streamType) const {
8697 PortHandleVector clients;
8698 for (size_t i = 0; i < mOutputs.size(); ++i) {
8699 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8700 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8701 }
8702 return clients;
8703}
8704
8705void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8706 PortHandleVector clients;
8707 for (auto stream : streams) {
8708 PortHandleVector clientsForStream = getClientsForStream(stream);
8709 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8710 }
8711 mpClientInterface->invalidateTracks(clients);
8712}
8713
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008714} // namespace android