blob: f99f76e414596a73aadf0ac1ae533150211d6454 [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
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
jiabin06e4bab2019-07-29 10:13:34 -070071template <typename T>
72bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
73{
74 if (left.size() != right.size()) {
75 return false;
76 }
77 for (size_t index = 0; index < right.size(); index++) {
78 if (left[index] != right[index]) {
79 return false;
80 }
81 }
82 return true;
83}
84
85template <typename T>
86bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 return !(left == right);
89}
90
Eric Laurente552edb2014-03-10 17:42:56 -070091// ----------------------------------------------------------------------------
92// AudioPolicyInterface implementation
93// ----------------------------------------------------------------------------
94
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010095status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
96 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
97 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080098 nextAudioPortGeneration();
99 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800100}
101
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100102status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
103 audio_policy_dev_state_t state,
104 const char* device_address,
105 const char* device_name,
106 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800107 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100108 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
109 status == OK) {
110 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
111 } else {
112 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
113 return status;
114 }
115}
116
François Gaffie11d30102018-11-02 16:09:09 +0100117void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
118 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200119{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000120 audio_port_v7 devicePort;
121 device->toAudioPort(&devicePort);
122 if (status_t status = mpClientInterface->setDeviceConnectedState(
123 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
124 status != OK) {
125 ALOGE("Error %d while setting connected state for device %s", status,
126 device->getDeviceTypeAddr().toString(false).c_str());
127 }
François Gaffie44481e72016-04-20 07:49:57 +0200128}
129
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100130status_t AudioPolicyManager::setDeviceConnectionStateInt(
131 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
132 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133 if (port.ext.getTag() != AudioPortExt::device) {
134 return BAD_VALUE;
135 }
136 audio_devices_t device_type;
137 std::string device_address;
138 if (status_t status = aidl2legacy_AudioDevice_audio_device(
139 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
140 status != OK) {
141 return status;
142 };
143 const char* device_name = port.name.c_str();
144 // connect/disconnect only 1 device at a time
145 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
146 return BAD_VALUE;
147
148 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
149 device_type, device_address.c_str(), device_name, encodedFormat,
150 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000151 if (device == nullptr) {
152 return INVALID_OPERATION;
153 }
154 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
155 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
156 }
157 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100158}
159
François Gaffie11d30102018-11-02 16:09:09 +0100160status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100162 const char* device_address,
163 const char* device_name,
164 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800165 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
167 status == OK) {
168 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
169 } else {
170 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
171 return status;
172 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700173}
Paul McLeane743a472015-01-28 11:07:31 -0800174
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700175status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
176 audio_policy_dev_state_t state)
177{
Eric Laurente552edb2014-03-10 17:42:56 -0700178 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700180 SortedVector <audio_io_handle_t> outputs;
181
François Gaffie11d30102018-11-02 16:09:09 +0100182 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // save a copy of the opened output descriptors before any output is opened or closed
185 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
186 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100187
188 bool wasLeUnicastActive = isLeUnicastActive();
189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 switch (state)
191 {
192 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800193 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700199 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200202 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 }
205
François Gaffie44481e72016-04-20 07:49:57 +0200206 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
207 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100208 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200209
François Gaffie11d30102018-11-02 16:09:09 +0100210 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
211 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200212
Francois Gaffie716e1432019-01-14 16:58:59 +0100213 mHwModules.cleanUpForDevice(device);
214
François Gaffie11d30102018-11-02 16:09:09 +0100215 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700216 return INVALID_OPERATION;
217 }
François Gaffie2110e042015-03-24 08:41:51 +0100218
jiabin1c4794b2020-05-05 10:08:05 -0700219 // Populate encapsulation information when a output device is connected.
220 device->setEncapsulationInfoFromHal(mpClientInterface);
221
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 // outputs should never be empty here
223 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
224 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100225 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
234
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700236
Paul McLeane743a472015-01-28 11:07:31 -0800237 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100238 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Eric Laurente552edb2014-03-10 17:42:56 -0700240 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100241 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700242
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100243 mOutputs.clearSessionRoutesForDevice(device);
244
François Gaffie11d30102018-11-02 16:09:09 +0100245 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100246
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800247 // Reset active device codec
248 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
249
Kriti Dangef6be8f2020-11-05 11:58:19 +0100250 // remove device from mReportedFormatsMap cache
251 mReportedFormatsMap.erase(device);
252
jiabina84c3d32022-12-02 18:59:55 +0000253 // remove preferred mixer configurations
254 mPreferredMixerAttrInfos.erase(device->getId());
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200290 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200291 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
292 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200293 (desc->mDirectOpenCount == 0))
294 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
295 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200296 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 closeOutput(output);
298 }
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
301 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800304 };
305
306 if (doCheckForDeviceAndOutputChanges) {
307 checkForDeviceAndOutputChanges(checkCloseOutputs);
308 } else {
309 checkCloseOutputs();
310 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100311 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100312 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700313 const DeviceVector activeMediaDevices =
314 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000315 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700316 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530318 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
319 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700321 // do not force device change on duplicated output because if device is 0, it will
322 // also force a device 0 for the two outputs it is duplicated to which may override
323 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100324 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100325 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700326 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 // always force when disconnecting (a non-duplicated device)
328 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000329 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
330 // If the device is using preferred mixer attributes, the output need to reopen
331 // with default configuration when the new selected devices are different from
332 // current routing devices
333 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
334 continue;
335 }
François Gaffie11d30102018-11-02 16:09:09 +0100336 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337 }
jiabinbce0c1d2020-10-05 11:20:18 -0700338 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000339 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700340 desc->supportsDevicesForPlayback(activeMediaDevices)) {
341 // Reopen the output to query the dynamic profiles when there is not active
342 // clients or all active clients will be rerouted. Otherwise, set the flag
343 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
344 // can be reopened to query dynamic profiles when all clients are inactive.
345 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000346 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700347 } else {
348 desc->mPendingReopenToQueryProfiles = true;
349 }
350 }
351 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
352 // Clear the flag that previously set for re-querying profiles.
353 desc->mPendingReopenToQueryProfiles = false;
354 }
355 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000356 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700357
Eric Laurentd60560a2015-04-10 11:31:20 -0700358 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100359 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700360 }
361
Eric Laurent96d1dda2022-03-14 17:14:19 +0100362 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
363
Eric Laurent72aa32f2014-05-30 18:51:48 -0700364 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700365 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700366 } // end if is output device
367
Eric Laurente552edb2014-03-10 17:42:56 -0700368 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700369 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700371 switch (state)
372 {
373 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700374 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100376 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700377 return INVALID_OPERATION;
378 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700379
380 if (mAvailableInputDevices.add(device) < 0) {
381 return NO_MEMORY;
382 }
383
François Gaffie44481e72016-04-20 07:49:57 +0200384 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
385 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100386 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200387
Eric Laurent0dd51852019-04-19 18:18:58 -0700388 if (checkInputsForDevice(device, state) != NO_ERROR) {
389 mAvailableInputDevices.remove(device);
390
François Gaffie11d30102018-11-02 16:09:09 +0100391 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100392
393 mHwModules.cleanUpForDevice(device);
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 return INVALID_OPERATION;
396 }
397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700402 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700404 return INVALID_OPERATION;
405 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700406
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700408
409 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100410 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700413
414 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100415
416 // remove device from mReportedFormatsMap cache
417 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 default:
François Gaffie11d30102018-11-02 16:09:09 +0100421 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 return BAD_VALUE;
423 }
424
Eric Laurent736a1022019-03-27 18:28:46 -0700425 // Propagate device availability to Engine
426 setEngineDeviceConnectionState(device, state);
427
Eric Laurent0dd51852019-04-19 18:18:58 -0700428 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700429 // As the input device list can impact the output device selection, update
430 // getDeviceForStrategy() cache
431 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700432
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100433 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200434 // Reconnect Audio Source
435 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
436 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
437 checkAudioSourceForAttributes(attributes);
438 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700439 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100440 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700441 }
442
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700444 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700446
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449}
450
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100451status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
452 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800453 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100454 DeviceDescriptorBase devDescr(device, device_address);
455 devDescr.setName(device_name);
456 return devDescr.writeToParcelable(aidlPort);
457}
458
Eric Laurent736a1022019-03-27 18:28:46 -0700459void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
460 audio_policy_dev_state_t state) {
461
462 // the Engine does not have to know about remote submix devices used by dynamic audio policies
463 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
464 return;
465 }
466 mEngine->setDeviceConnectionState(device, state);
467}
468
469
Eric Laurente0720872014-03-11 09:30:41 -0700470audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100471 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700472{
Eric Laurent634b7142016-04-20 13:48:02 -0700473 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800474 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
475 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700476 (strlen(device_address) != 0)/*matchAddress*/);
477
478 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100479 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700480 device, device_address);
481 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
482 }
François Gaffie53615e22015-03-19 09:24:12 +0100483
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 DeviceVector *deviceVector;
485
Eric Laurente552edb2014-03-10 17:42:56 -0700486 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700487 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700488 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700489 deviceVector = &mAvailableInputDevices;
490 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100491 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700493 }
Eric Laurent634b7142016-04-20 13:48:02 -0700494
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 return (deviceVector->getDevice(
496 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700497 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800498}
499
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800500status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
501 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 const char *device_name,
503 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504{
505 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700506 String8 reply;
507 AudioParameter param;
508 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
511 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800513 // connect/disconnect only 1 device at a time
514 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700517 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 // Nothing to do: device is not connected
520 return NO_ERROR;
521 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700524 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 // configure codecs.
526 // Handle two specific cases by sending a set parameter to
527 // configure A2DP codecs. No need to toggle device state.
528 // Case 1: A2DP active device switches from primary to primary
529 // module
530 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200531 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700532 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
534 if (availablePrimaryOutputDevices().contains(devDesc) &&
535 (module != 0 && module->getHandle() == primaryHandle)) {
536 reply = mpClientInterface->getParameters(
537 AUDIO_IO_HANDLE_NONE,
538 String8(AudioParameter::keyReconfigA2dpSupported));
539 AudioParameter repliedParameters(reply);
540 repliedParameters.getInt(
541 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
542 if (isReconfigA2dpSupported) {
543 const String8 key(AudioParameter::keyReconfigA2dp);
544 param.add(key, String8("true"));
545 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
546 devDesc->setEncodedFormat(encodedFormat);
547 return NO_ERROR;
548 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700549 }
550 }
cnx421bd2dcc42020-07-11 14:58:44 +0800551 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
552 for (size_t i = 0; i < mOutputs.size(); i++) {
553 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
554 // mute media strategies and delay device switch by the largest
555 // This avoid sending the music tail into the earpiece or headset.
556 setStrategyMute(musicStrategy, true, desc);
557 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
558 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
559 nullptr, true /*fromCache*/).types());
560 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561 // Toggle the device state: UNAVAILABLE -> AVAILABLE
562 // This will force reading again the device configuration
563 status = setDeviceConnectionState(device,
564 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 device_address, device_name,
566 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800567 if (status != NO_ERROR) {
568 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
569 status);
570 return status;
571 }
572
573 status = setDeviceConnectionState(device,
574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
578 status);
579 return status;
580 }
581
582 return NO_ERROR;
583}
584
Pattydd807582021-11-04 21:01:03 +0800585status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
586 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800587{
Pattydd807582021-11-04 21:01:03 +0800588 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800589 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800590 std::unordered_set<audio_format_t> formatSet;
591 sp<HwModule> primaryModule =
592 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700593 if (primaryModule == nullptr) {
594 ALOGE("%s() unable to get primary module", __func__);
595 return NO_INIT;
596 }
Pattydd807582021-11-04 21:01:03 +0800597
598 DeviceTypeSet audioDeviceSet;
599
600 switch(device) {
601 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
602 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
603 break;
604 case AUDIO_DEVICE_OUT_BLE_HEADSET:
605 audioDeviceSet = getAudioDeviceOutAllBleSet();
606 break;
607 default:
608 ALOGE("%s() device type 0x%08x not supported", __func__, device);
609 return BAD_VALUE;
610 }
611
jiabin9a3361e2019-10-01 09:38:30 -0700612 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800613 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 for (const auto& device : declaredDevices) {
615 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800616 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800617 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800618 return status;
619}
620
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100621DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
622{
623 DeviceVector rxSinkdevices{};
624 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
625 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
626 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
627 auto rxSinkDevice = rxSinkdevices.itemAt(0);
628 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
630 // retrieve Rx Source device descriptor
631 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
632 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
633
634 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
635 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
636 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
637 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
638 return DeviceVector(rxSinkDevice);
639 }
640 }
641 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
642 // the device returned is not necessarily reachable via this output
643 // (filter later by setOutputDevices())
644 return getNewOutputDevices(mPrimaryOutput, fromCache);
645}
646
647status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
648{
649 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
650 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
651 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
652 }
653 return INVALID_OPERATION;
654}
655
656status_t AudioPolicyManager::updateCallRoutingInternal(
657 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658{
659 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100660 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700661 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700662 if(!hasPrimaryOutput() ||
663 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700665 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100666 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100667
Francois Gaffie716e1432019-01-14 16:58:59 +0100668 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100669 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100671
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100672 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100673 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
Francois Gaffie601801d2021-06-22 13:27:39 +0200675 disconnectTelephonyAudioSource(mCallRxSourceClient);
676 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677
François Gaffie9eb18552018-11-05 10:33:26 +0100678 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700679 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100680 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700681 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100682 // retrieve Rx Source and Tx Sink device descriptors
683 sp<DeviceDescriptor> rxSourceDevice =
684 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
685 String8(),
686 AUDIO_FORMAT_DEFAULT);
687 sp<DeviceDescriptor> txSinkDevice =
688 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691
692 // RX and TX Telephony device are declared by Primary Audio HAL
693 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
694 (telephonyRxModule->getHalVersionMajor() >= 3)) {
695 if (rxSourceDevice == 0 || txSinkDevice == 0) {
696 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 ALOGE("%s() no telephony Tx and/or RX device", __func__);
698 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100699 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100700 // createAudioPatchInternal now supports both HW / SW bridging
701 createRxPatch = true;
702 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 } else {
704 // If the RX device is on the primary HW module, then use legacy routing method for
705 // voice calls via setOutputDevice() on primary output.
706 // Otherwise, create two audio patches for TX and RX path.
707 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
708 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709 // If the TX device is also on the primary HW module, setOutputDevice() will take care
710 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100711 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
712 (txSinkDevice != 0);
713 }
714 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
715 // Otherwise, create two audio patches for TX and RX path.
716 if (!createRxPatch) {
717 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700718 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200719 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800720 // If the TX device is on the primary HW module but RX device is
721 // on other HW module, SinkMetaData of telephony input should handle it
722 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700724 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100725 // terminate active capture if on the same HW module as the call TX source device
726 // FIXME: would be better to refine to only inputs whose profile connects to the
727 // call TX device but this information is not in the audio patch and logic here must be
728 // symmetric to the one in startInput()
729 for (const auto& activeDesc : mInputs.getActiveInputs()) {
730 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
731 closeActiveClients(activeDesc);
732 }
733 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200734 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800735 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100736 if (waitMs != nullptr) {
737 *waitMs = muteWaitMs;
738 }
739 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800740}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
Mikhail Naganov100f0122018-11-29 11:22:16 -0800742bool AudioPolicyManager::isDeviceOfModule(
743 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
744 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
745 if (module != 0) {
746 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
747 .indexOf(devDesc) != NAME_NOT_FOUND
748 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
749 .indexOf(devDesc) != NAME_NOT_FOUND;
750 }
751 return false;
752}
753
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754void AudioPolicyManager::connectTelephonyRxAudioSource()
755{
Francois Gaffie601801d2021-06-22 13:27:39 +0200756 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200757 const struct audio_port_config source = {
758 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
759 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
760 };
761 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200762 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
763 ALOGE_IF(mCallRxSourceClient == nullptr,
764 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765}
766
Francois Gaffie601801d2021-06-22 13:27:39 +0200767void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768{
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 if (clientDesc == nullptr) {
770 return;
771 }
772 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
773 "%s error stopping audio source", __func__);
774 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200775}
776
777void AudioPolicyManager::connectTelephonyTxAudioSource(
778 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
779 uint32_t delayMs)
780{
Francois Gaffie601801d2021-06-22 13:27:39 +0200781 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 if (srcDevice == nullptr || sinkDevice == nullptr) {
783 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
784 return;
785 }
786 PatchBuilder patchBuilder;
787 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
788 ALOGV("%s between source %s and sink %s", __func__,
789 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200791 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
792
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200793 struct audio_port_config source = {};
794 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 mCallTxSourceClient = new InternalSourceClientDescriptor(
796 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 mCommunnicationStrategy, toVolumeSource(aa));
798 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
799 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
801 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200802 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
803 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200806}
807
Eric Laurente0720872014-03-11 09:30:41 -0700808void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700809{
810 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100811 // store previous phone state for management of sonification strategy below
812 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100813 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100814
815 if (mEngine->setPhoneState(state) != NO_ERROR) {
816 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 return;
818 }
François Gaffie2110e042015-03-24 08:41:51 +0100819 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700820 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700821 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700822 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800823 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700824 }
825
François Gaffie2110e042015-03-24 08:41:51 +0100826 /**
827 * Switching to or from incall state or switching between telephony and VoIP lead to force
828 * routing command.
829 */
Eric Laurent74b71512019-11-06 17:21:57 -0800830 bool force = ((isStateInCall(oldState) != isStateInCall(state))
831 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700832
833 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700834 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700835
Eric Laurente552edb2014-03-10 17:42:56 -0700836 int delayMs = 0;
837 if (isStateInCall(state)) {
838 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100839 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
840 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700841 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700842 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700843 // mute media and sonification strategies and delay device switch by the largest
844 // latency of any output where either strategy is active.
845 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100846 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
847 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
848 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700849 (delayMs < (int)desc->latency()*2)) {
850 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700851 }
François Gaffiec005e562018-11-06 15:04:49 +0100852 setStrategyMute(musicStrategy, true, desc);
853 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
854 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
855 nullptr, true /*fromCache*/).types());
856 setStrategyMute(sonificationStrategy, true, desc);
857 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
858 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
859 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700860 }
861 }
862
Eric Laurent87ffa392015-05-22 10:32:38 -0700863 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700864 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100865 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700866 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100867 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
868 // force routing command to audio hardware when ending call
869 // even if no device change is needed
870 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
871 rxDevices = mPrimaryOutput->devices();
872 }
873 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200874 disconnectTelephonyAudioSource(mCallRxSourceClient);
875 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100876 }
François Gaffie11d30102018-11-02 16:09:09 +0100877 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700878 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700879 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700880
jiabin3ff8d7d2022-12-13 06:27:44 +0000881 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700882 // reevaluate routing on all outputs in case tracks have been started during the call
883 for (size_t i = 0; i < mOutputs.size(); i++) {
884 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100885 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200886 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
887 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000888 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
889 // If the device is using preferred mixer attributes, the output need to reopen
890 // with default configuration when the new selected devices are different from
891 // current routing devices.
892 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
893 continue;
894 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200895 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
896 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700897 }
898 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000899 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700900
Eric Laurent96d1dda2022-03-14 17:14:19 +0100901 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
902
Eric Laurente552edb2014-03-10 17:42:56 -0700903 if (isStateInCall(state)) {
904 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700905 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800906 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700907 }
908
909 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100910 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
911 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700912}
913
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700914audio_mode_t AudioPolicyManager::getPhoneState() {
915 return mEngine->getPhoneState();
916}
917
Eric Laurente0720872014-03-11 09:30:41 -0700918void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100919 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700920{
François Gaffie2110e042015-03-24 08:41:51 +0100921 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700922 if (config == mEngine->getForceUse(usage)) {
923 return;
924 }
Eric Laurente552edb2014-03-10 17:42:56 -0700925
François Gaffie2110e042015-03-24 08:41:51 +0100926 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
927 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
928 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700929 }
François Gaffie2110e042015-03-24 08:41:51 +0100930 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
931 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
932 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700933
934 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700935 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800936
Eric Laurent22fcda22019-05-17 16:28:47 -0700937 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
938 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800939 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700940 }
941
Eric Laurentdc462862016-07-19 12:29:53 -0700942 //FIXME: workaround for truncated touch sounds
943 // to be removed when the problem is handled by system UI
944 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700945 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
946 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
947 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700948
949 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100950 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700951}
952
Eric Laurente0720872014-03-11 09:30:41 -0700953void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700954{
955 ALOGV("setSystemProperty() property %s, value %s", property, value);
956}
957
Dorin Drimusecc9f422022-03-09 17:57:40 +0100958// Find an MSD output profile compatible with the parameters passed.
959// When "directOnly" is set, restrict search to profiles for direct outputs.
960sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
961 const DeviceVector& devices,
962 uint32_t samplingRate,
963 audio_format_t format,
964 audio_channel_mask_t channelMask,
965 audio_output_flags_t flags,
966 bool directOnly)
967{
968 flags = getRelevantFlags(flags, directOnly);
969
970 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
971 if (msdModule != nullptr) {
972 // for the msd module check if there are patches to the output devices
973 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
974 HwModuleCollection modules;
975 modules.add(msdModule);
976 return searchCompatibleProfileHwModules(
977 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
978 flags, directOnly);
979 }
980 }
981 return nullptr;
982}
983
Michael Chana94fbb22018-04-24 14:31:19 +1000984// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
985// search to profiles for direct outputs.
986sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100987 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000988 uint32_t samplingRate,
989 audio_format_t format,
990 audio_channel_mask_t channelMask,
991 audio_output_flags_t flags,
992 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700993{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100994 flags = getRelevantFlags(flags, directOnly);
995
996 return searchCompatibleProfileHwModules(
997 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
998}
999
1000audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1001 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001002 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001003 // only retain flags that will drive the direct output profile selection
1004 // if explicitly requested
1005 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001006 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001007 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1008 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001009 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001010 return flags;
1011}
Eric Laurent861a6282015-05-18 15:40:16 -07001012
Dorin Drimusecc9f422022-03-09 17:57:40 +01001013sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1014 const HwModuleCollection& hwModules,
1015 const DeviceVector& devices,
1016 uint32_t samplingRate,
1017 audio_format_t format,
1018 audio_channel_mask_t channelMask,
1019 audio_output_flags_t flags,
1020 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001021 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001022 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001023 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024 if (!curProfile->isCompatibleProfile(devices,
1025 samplingRate, NULL /*updatedSamplingRate*/,
1026 format, NULL /*updatedFormat*/,
1027 channelMask, NULL /*updatedChannelMask*/,
1028 flags)) {
1029 continue;
1030 }
1031 // reject profiles not corresponding to a device currently available
1032 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1033 continue;
1034 }
1035 // reject profiles if connected device does not support codec
1036 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1037 continue;
1038 }
1039 if (!directOnly) {
1040 return curProfile;
1041 }
1042
1043 // when searching for direct outputs, if several profiles are compatible, give priority
1044 // to one with offload capability
1045 if (profile != 0 &&
1046 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001047 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001048 }
1049 profile = curProfile;
1050 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1051 break;
1052 }
Eric Laurente552edb2014-03-10 17:42:56 -07001053 }
1054 }
Eric Laurent861a6282015-05-18 15:40:16 -07001055 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001056}
1057
Eric Laurentfa0f6742021-08-17 18:39:44 +02001058sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001059 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001060{
1061 for (const auto& hwModule : mHwModules) {
1062 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001063 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001064 continue;
1065 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001066 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001067 // reject profiles not corresponding to a device currently available
1068 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1069 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1070 continue;
1071 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001072 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1073 != devices.size()) {
1074 continue;
1075 }
1076 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001077 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1078 return curProfile;
1079 }
1080 }
1081 return nullptr;
1082}
1083
Eric Laurentf4e63452017-11-06 19:31:46 +00001084audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001085{
François Gaffiec005e562018-11-06 15:04:49 +01001086 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001087
1088 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1089 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1090 // format, flags, etc. This may result in some discrepancy for functions that utilize
1091 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1092 // and AudioSystem::getOutputSamplingRate().
1093
François Gaffie11d30102018-11-02 16:09:09 +01001094 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001095 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001096
François Gaffie11d30102018-11-02 16:09:09 +01001097 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1098 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001099 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001100}
1101
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001102status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1103 const audio_attributes_t *srcAttr,
1104 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001105{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001106 if (srcAttr != NULL) {
1107 if (!isValidAttributes(srcAttr)) {
1108 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1109 __func__,
1110 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1111 srcAttr->tags);
1112 return BAD_VALUE;
1113 }
1114 *dstAttr = *srcAttr;
1115 } else {
1116 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1117 ALOGE("%s: invalid stream type", __func__);
1118 return BAD_VALUE;
1119 }
François Gaffiec005e562018-11-06 15:04:49 +01001120 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001122
1123 // Only honor audibility enforced when required. The client will be
1124 // forced to reconnect if the forced usage changes.
1125 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001126 dstAttr->flags = static_cast<audio_flags_mask_t>(
1127 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001128 }
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130 return NO_ERROR;
1131}
1132
Kevin Rocard153f92d2018-12-18 18:33:28 -08001133status_t AudioPolicyManager::getOutputForAttrInt(
1134 audio_attributes_t *resultAttr,
1135 audio_io_handle_t *output,
1136 audio_session_t session,
1137 const audio_attributes_t *attr,
1138 audio_stream_type_t *stream,
1139 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001140 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001141 audio_output_flags_t *flags,
1142 audio_port_handle_t *selectedDeviceId,
1143 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001144 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001145 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001146 bool *isSpatialized,
1147 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001148{
François Gaffiec005e562018-11-06 15:04:49 +01001149 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001150 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001151 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001152 const sp<DeviceDescriptor> requestedDevice =
1153 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1154
Eric Laurent8a1095a2019-11-08 14:44:16 -08001155 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001156 *isSpatialized = false;
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1159 if (status != NO_ERROR) {
1160 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001161 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001162 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001163 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001164 }
François Gaffiec005e562018-11-06 15:04:49 +01001165 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001166
François Gaffiec005e562018-11-06 15:04:49 +01001167 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1168 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001169
Kevin Rocard153f92d2018-12-18 18:33:28 -08001170 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1171 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1172 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001174 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1175 .channel_mask = config->channel_mask,
1176 .format = config->format,
1177 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001178 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1179 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001180 if (status != OK) {
1181 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001182 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001183
Kevin Rocard153f92d2018-12-18 18:33:28 -08001184 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001185 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186
1187 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001188 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1189 && !audio_is_linear_pcm(config->format)) {
1190 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001191 return BAD_VALUE;
1192 }
1193 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001194 sp<DeviceDescriptor> deviceDesc =
1195 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1196 primaryMix->mDeviceAddress,
1197 AUDIO_FORMAT_DEFAULT);
1198 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001199 bool tryDirectForFlags = policyDesc == nullptr ||
1200 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1201 // if a direct output can be opened to deliver the track's multi-channel content to the
1202 // output rather than being downmixed by the primary output, then use this direct
1203 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1204 // mix.
1205 bool tryDirectForChannelMask = policyDesc != nullptr
1206 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1207 audio_channel_count_from_out_mask(config->channel_mask));
1208 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 audio_io_handle_t newOutput;
1210 status = openDirectOutput(
1211 *stream, session, config,
1212 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1213 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001214 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001215 policyDesc = mOutputs.valueFor(newOutput);
1216 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001217 } else if (tryDirectForFlags) {
1218 policyDesc = nullptr;
1219 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001220 }
1221 if (policyDesc != nullptr) {
1222 policyDesc->mPolicyMix = primaryMix;
1223 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001224 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001225
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001226 ALOGV("getOutputForAttr() returns output %d", *output);
1227 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1228 *outputType = API_OUT_MIX_PLAYBACK;
1229 } else {
1230 *outputType = API_OUTPUT_LEGACY;
1231 }
1232 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001233 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001234 }
François Gaffiec005e562018-11-06 15:04:49 +01001235 // Virtual sources must always be dynamicaly or explicitly routed
1236 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1237 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1238 return BAD_VALUE;
1239 }
1240 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1241 // in order to let the choice of the order to future vendor engine
1242 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001243
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001245 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001246 }
1247
Nadav Barb2f18162018-07-18 13:01:53 +03001248 // Set incall music only if device was explicitly set, and fallback to the device which is
1249 // chosen by the engine if not.
1250 // FIXME: provide a more generic approach which is not device specific and move this back
1251 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001252 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001253 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001254 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001255 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001256 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001257 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001258 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001259 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001260 }
1261 }
1262
François Gaffiec005e562018-11-06 15:04:49 +01001263 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1264 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1265 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001266
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001268 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001269 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001270 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001271 ALOGV("%s() Using MSD devices %s instead of devices %s",
1272 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001273 } else {
1274 *output = AUDIO_IO_HANDLE_NONE;
1275 }
1276 }
1277 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001278 sp<PreferredMixerAttributesInfo> info = nullptr;
1279 if (outputDevices.size() == 1) {
1280 info = getPreferredMixerAttributesInfo(
1281 outputDevices.itemAt(0)->getId(),
1282 mEngine->getProductStrategyForAttributes(*resultAttr));
jiabin5eaf0962022-12-20 20:11:38 +00001283 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1284 // and it is currently active.
1285 if (info != nullptr && info->getUid() != uid &&
1286 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1287 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001288 info = nullptr;
1289 }
1290 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001291 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001292 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001293 // The client will be active if the client is currently preferred mixer owner and the
1294 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001295 *isBitPerfect = (info != nullptr
1296 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001297 && info->getUid() == uid
1298 && *output != AUDIO_IO_HANDLE_NONE
1299 // When bit-perfect output is selected for the preferred mixer attributes owner,
1300 // only need to consider the config matches.
1301 && mOutputs.valueFor(*output)->isConfigurationMatched(
1302 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001303 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001304 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001305 AudioProfileVector profiles;
1306 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1307 if (ret == NO_ERROR && !profiles.empty()) {
1308 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1309 : *profiles[0]->getChannels().begin();
1310 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1311 : *profiles[0]->getSampleRates().begin();
1312 config->format = profiles[0]->getFormat();
1313 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001314 return INVALID_OPERATION;
1315 }
Paul McLeanaa981192015-03-21 09:55:15 -07001316
François Gaffiec005e562018-11-06 15:04:49 +01001317 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001318 for (auto &outputDevice : outputDevices) {
1319 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1320 *selectedDeviceId = outputDevice->getId();
1321 break;
1322 }
1323 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001324
Eric Laurent8a1095a2019-11-08 14:44:16 -08001325 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1326 *outputType = API_OUTPUT_TELEPHONY_TX;
1327 } else {
1328 *outputType = API_OUTPUT_LEGACY;
1329 }
1330
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001331 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1332
1333 return NO_ERROR;
1334}
1335
1336status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1337 audio_io_handle_t *output,
1338 audio_session_t session,
1339 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001340 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001341 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001342 audio_output_flags_t *flags,
1343 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001344 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001345 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001346 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001347 bool *isSpatialized,
1348 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001349{
1350 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1351 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1352 return INVALID_OPERATION;
1353 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001354 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001355 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001356 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001357 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001358 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001359 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001360 const sp<DeviceDescriptor> requestedDevice =
1361 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1362
1363 // Prevent from storing invalid requested device id in clients
1364 const audio_port_handle_t sanitizedRequestedPortId =
1365 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1366 *selectedDeviceId = sanitizedRequestedPortId;
1367
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001368 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001369 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001370 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1371 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001372 if (status != NO_ERROR) {
1373 return status;
1374 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001375 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001376 if (secondaryOutputs != nullptr) {
1377 for (auto &secondaryMix : secondaryMixes) {
1378 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1379 if (outputDesc != nullptr &&
1380 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1381 secondaryOutputs->push_back(outputDesc->mIoHandle);
1382 weakSecondaryOutputDescs.push_back(outputDesc);
1383 }
1384 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001385 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001386
Eric Laurent8fc147b2018-07-22 19:13:55 -07001387 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001388 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001389 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001390 };
jiabin4ef93452019-09-10 14:29:54 -07001391 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001392
Eric Laurentc209fe42020-06-05 18:11:23 -07001393 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001394 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001395 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001396 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001397 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001398 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001399 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001400 std::move(weakSecondaryOutputDescs),
1401 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001402 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001403
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001404 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1405 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001406
Eric Laurente83b55d2014-11-14 10:06:21 -08001407 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001408}
1409
Eric Laurentc529cf62020-04-17 18:19:10 -07001410status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1411 audio_session_t session,
1412 const audio_config_t *config,
1413 audio_output_flags_t flags,
1414 const DeviceVector &devices,
1415 audio_io_handle_t *output) {
1416
1417 *output = AUDIO_IO_HANDLE_NONE;
1418
1419 // skip direct output selection if the request can obviously be attached to a mixed output
1420 // and not explicitly requested
1421 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1422 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1423 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1424 return NAME_NOT_FOUND;
1425 }
1426
1427 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1428 // This prevents creating an offloaded track and tearing it down immediately after start
1429 // when audioflinger detects there is an active non offloadable effect.
1430 // FIXME: We should check the audio session here but we do not have it in this context.
1431 // This may prevent offloading in rare situations where effects are left active by apps
1432 // in the background.
1433 sp<IOProfile> profile;
1434 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1435 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1436 profile = getProfileForOutput(
1437 devices, config->sample_rate, config->format, config->channel_mask,
1438 flags, true /* directOnly */);
1439 }
1440
1441 if (profile == nullptr) {
1442 return NAME_NOT_FOUND;
1443 }
1444
1445 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1446 for (size_t i = 0; i < mOutputs.size(); i++) {
1447 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1448 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1449 // reuse direct output if currently open by the same client
1450 // and configured with same parameters
1451 if ((config->sample_rate == desc->getSamplingRate()) &&
1452 (config->format == desc->getFormat()) &&
1453 (config->channel_mask == desc->getChannelMask()) &&
1454 (session == desc->mDirectClientSession)) {
1455 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001456 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001457 mOutputs.keyAt(i), session);
1458 *output = mOutputs.keyAt(i);
1459 return NO_ERROR;
1460 }
1461 }
1462 }
1463
1464 if (!profile->canOpenNewIo()) {
1465 return NAME_NOT_FOUND;
1466 }
1467
1468 sp<SwAudioOutputDescriptor> outputDesc =
1469 new SwAudioOutputDescriptor(profile, mpClientInterface);
1470
Michael Chan6fb34492020-12-08 15:44:49 +11001471 // An MSD patch may be using the only output stream that can service this request. Release
1472 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001473 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001474
Eric Laurentf1f22e72021-07-13 14:04:14 +02001475 status_t status =
1476 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001477
1478 // only accept an output with the requested parameters
1479 if (status != NO_ERROR ||
1480 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1481 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1482 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1483 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1484 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1485 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1486 config->channel_mask, outputDesc->getChannelMask());
1487 if (*output != AUDIO_IO_HANDLE_NONE) {
1488 outputDesc->close();
1489 }
1490 // fall back to mixer output if possible when the direct output could not be open
1491 if (audio_is_linear_pcm(config->format) &&
1492 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1493 return NAME_NOT_FOUND;
1494 }
1495 *output = AUDIO_IO_HANDLE_NONE;
1496 return BAD_VALUE;
1497 }
1498 outputDesc->mDirectOpenCount = 1;
1499 outputDesc->mDirectClientSession = session;
1500
1501 addOutput(*output, outputDesc);
1502 mPreviousOutputs = mOutputs;
1503 ALOGV("%s returns new direct output %d", __func__, *output);
1504 mpClientInterface->onAudioPortListUpdate();
1505 return NO_ERROR;
1506}
1507
François Gaffie11d30102018-11-02 16:09:09 +01001508audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1509 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001510 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001511 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001512 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001513 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001514 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001515 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001516 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001517{
Andy Hungc88b0642018-04-27 15:42:35 -07001518 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001519
jiabine375d412019-02-26 12:54:53 -08001520 // Discard haptic channel mask when forcing muting haptic channels.
1521 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001522 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1523 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001524
Eric Laurente552edb2014-03-10 17:42:56 -07001525 // open a direct output if required by specified parameters
1526 //force direct flag if offload flag is set: offloading implies a direct output stream
1527 // and all common behaviors are driven by checking only the direct flag
1528 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001529 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1530 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001531 }
Nadav Bar766fb022018-01-07 12:18:03 +02001532 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1533 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001534 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001535
1536 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1537
Eric Laurente83b55d2014-11-14 10:06:21 -08001538 // only allow deep buffering for music stream type
1539 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001540 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001541 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001542 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001543 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1544 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001545 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001546 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001547 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001548 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001549 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001550 audio_is_linear_pcm(config->format) &&
1551 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001552 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001553 AUDIO_OUTPUT_FLAG_DIRECT);
1554 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001555 }
Eric Laurente552edb2014-03-10 17:42:56 -07001556
Carter Hsua3abb402021-10-26 11:11:20 +08001557 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1558 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1559 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1560 }
1561
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001562 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001563 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001564 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001565 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001566 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001567 }
1568
Eric Laurentc529cf62020-04-17 18:19:10 -07001569 audio_config_t directConfig = *config;
1570 directConfig.channel_mask = channelMask;
1571 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1572 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001573 return output;
1574 }
1575
Eric Laurent14cbfca2016-03-17 09:42:16 -07001576 // A request for HW A/V sync cannot fallback to a mixed output because time
1577 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001578 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001579 return AUDIO_IO_HANDLE_NONE;
1580 }
1581
Eric Laurente552edb2014-03-10 17:42:56 -07001582 // ignoring channel mask due to downmix capability in mixer
1583
1584 // open a non direct output
1585
1586 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001587 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001588 // get which output is suitable for the specified stream. The actual
1589 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001590 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001591 if (prefMixerConfigInfo != nullptr) {
1592 for (audio_io_handle_t outputHandle : outputs) {
1593 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1594 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1595 output = outputHandle;
1596 break;
1597 }
1598 }
1599 if (output == AUDIO_IO_HANDLE_NONE) {
1600 // No output open with the preferred profile. Open a new one.
1601 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1602 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1603 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1604 config.format = prefMixerConfigInfo->getConfigBase().format;
1605 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1606 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1607 &config, prefMixerConfigInfo->getFlags());
1608 if (preferredOutput == nullptr) {
1609 ALOGE("%s failed to open output with preferred mixer config", __func__);
1610 } else {
1611 output = preferredOutput->mIoHandle;
1612 }
1613 }
1614 } else {
1615 // at this stage we should ignore the DIRECT flag as no direct output could be
1616 // found earlier
1617 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1618 output = selectOutput(
1619 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1620 }
Eric Laurente552edb2014-03-10 17:42:56 -07001621 }
François Gaffie11d30102018-11-02 16:09:09 +01001622 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001623 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001624 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001625
Eric Laurente552edb2014-03-10 17:42:56 -07001626 return output;
1627}
1628
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001629sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001630 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1631 mAvailableInputDevices);
1632 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1633}
1634
1635DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1636 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1637 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638}
1639
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001640const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001641 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001642 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1643 if (msdModule != 0) {
1644 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1645 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1646 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1647 const struct audio_port_config *source = &patch->mPatch.sources[j];
1648 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1649 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001650 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001651 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001652 }
1653 }
1654 }
1655 return msdPatches;
1656}
1657
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001658bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1659 ssize_t index = mAudioPatches.indexOfKey(handle);
1660 if (index < 0) {
1661 return false;
1662 }
1663 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1664 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1665 if (msdModule == nullptr) {
1666 return false;
1667 }
1668 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1669 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1670 return true;
1671 }
1672 index = getMsdOutputPatches().indexOfKey(handle);
1673 if (index < 0) {
1674 return false;
1675 }
1676 return true;
1677}
1678
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001679status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1680 const InputProfileCollection &inputProfiles,
1681 const OutputProfileCollection &outputProfiles,
1682 const sp<DeviceDescriptor> &sourceDevice,
1683 const sp<DeviceDescriptor> &sinkDevice,
1684 AudioProfileVector& sourceProfiles,
1685 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001686 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001687 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 return NO_INIT;
1689 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001691 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 return NO_INIT;
1693 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001695 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1696 inProfile->supportsDevice(sourceDevice)) {
1697 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001698 }
1699 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001700 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001701 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001702 outProfile->supportsDevice(sinkDevice)) {
1703 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 }
1705 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001706 return NO_ERROR;
1707}
1708
1709status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1710 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1711 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1712{
Dean Wheatley16809da2022-12-09 14:55:46 +11001713 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1714 static const std::vector<audio_format_t> formatsOrder = {{
1715 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1716 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1717 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1718 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1719 // preferred).
1720 std::vector<audio_channel_mask_t> masks = {{
1721 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1722 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1723 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1724 // insert index masks (higher counts most preferred) as preferred over position masks
1725 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1726 masks.insert(
1727 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1728 }
1729 return masks;
1730 }();
1731
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001732 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001733 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1734 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001735 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001736 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1737 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001738 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001739 }
1740 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1741 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1742 sinkConfig->format = bestSinkConfig.format;
1743 // For encoded streams force direct flag to prevent downstream mixing.
1744 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1745 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001746 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1747 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001748 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001749 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1750 // raw and IEC61937 framed streams.
1751 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1752 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1753 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001754 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1755 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001756 sourceConfig->channel_mask =
1757 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1758 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1759 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001760 sourceConfig->format = bestSinkConfig.format;
1761 // Copy input stream directly without any processing (e.g. resampling).
1762 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1763 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1764 if (hwAvSync) {
1765 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1766 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1767 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1768 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1769 }
1770 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1771 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1772 sinkConfig->config_mask |= config_mask;
1773 sourceConfig->config_mask |= config_mask;
1774 return NO_ERROR;
1775}
1776
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001777PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1778 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779{
1780 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001781 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1782 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1783 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1784 if (deviceModule == nullptr) {
1785 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1786 return patchBuilder;
1787 }
1788 const InputProfileCollection inputProfiles = msdIsSource ?
1789 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1790 const OutputProfileCollection outputProfiles = msdIsSource ?
1791 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1792
1793 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1794 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1795 device : getMsdAudioOutDevices().itemAt(0);
1796 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1797
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001798 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1799 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001800 AudioProfileVector sourceProfiles;
1801 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001802 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1803 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 for (auto hwAvSync : { true, false }) {
1805 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1806 sourceProfiles, sinkProfiles) != NO_ERROR) {
1807 continue;
1808 }
1809 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1810 &sinkConfig) == NO_ERROR) {
1811 // Found a matching config. Re-create PatchBuilder with this config.
1812 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1813 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001814 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001815 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001816 " supporting PCM format conversion.", __func__);
1817 return patchBuilder;
1818}
1819
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001820status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001821 DeviceVector devices;
1822 if (outputDevices != nullptr && outputDevices->size() > 0) {
1823 devices.add(*outputDevices);
1824 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001825 // Use media strategy for unspecified output device. This should only
1826 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1827 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001828 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001829 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001830 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001831 }
Michael Chan6fb34492020-12-08 15:44:49 +11001832 std::vector<PatchBuilder> patchesToCreate;
1833 for (auto i = 0u; i < devices.size(); ++i) {
1834 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001836 }
1837 // Retain only the MSD patches associated with outputDevices request.
1838 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001840 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1841 auto retainedPatch = false;
1842 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1843 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1844 patchesToRemove.removeItemsAt(i);
1845 retainedPatch = true;
1846 break;
1847 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001848 }
Michael Chan6fb34492020-12-08 15:44:49 +11001849 if (retainedPatch) {
1850 it = patchesToCreate.erase(it);
1851 continue;
1852 }
1853 ++it;
1854 }
1855 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1856 return NO_ERROR;
1857 }
1858 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1859 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001860 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861 }
Michael Chan6fb34492020-12-08 15:44:49 +11001862 status_t status = NO_ERROR;
1863 for (const auto &p : patchesToCreate) {
1864 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1865 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1866 char message[256];
1867 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1868 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1869 currStatus == NO_ERROR ? "Success" : "Error",
1870 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1871 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1872 if (currStatus == NO_ERROR) {
1873 ALOGD("%s", message);
1874 } else {
1875 ALOGE("%s", message);
1876 if (status == NO_ERROR) {
1877 status = currStatus;
1878 }
1879 }
1880 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 return status;
1882}
1883
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001884void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1885 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001886 for (size_t i = 0; i < msdPatches.size(); i++) {
1887 const auto& patch = msdPatches[i];
1888 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1889 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1890 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1891 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1892 releaseAudioPatch(patch->getHandle(), mUidCached);
1893 break;
1894 }
1895 }
1896 }
1897}
1898
Dorin Drimus94d94412022-02-02 09:05:02 +01001899bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1900 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1901 AudioPatchCollection msdPatches = getMsdOutputPatches();
1902 for (size_t i = 0; i < msdPatches.size(); i++) {
1903 const auto& patch = msdPatches[i];
1904 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1905 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1906 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1907 const auto& foundDevice = devicesToCheck.getDevice(
1908 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1909 if (foundDevice != nullptr) {
1910 devicesToCheck.remove(foundDevice);
1911 if (devicesToCheck.isEmpty()) {
1912 return true;
1913 }
1914 }
1915 }
1916 }
1917 }
1918 return false;
1919}
1920
Eric Laurente0720872014-03-11 09:30:41 -07001921audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001922 audio_output_flags_t flags,
1923 audio_format_t format,
1924 audio_channel_mask_t channelMask,
1925 uint32_t samplingRate,
1926 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001927{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001928 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1929 "%s called with format %#x", __func__, format);
1930
jiabinebb6af42020-06-09 17:31:17 -07001931 // Return the output that haptic-generating attached to when 1) session id is specified,
1932 // 2) haptic-generating effect exists for given session id and 3) the output that
1933 // haptic-generating effect attached to is in given outputs.
1934 if (sessionId != AUDIO_SESSION_NONE) {
1935 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1936 sessionId, FX_IID_HAPTICGENERATOR);
1937 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1938 return hapticGeneratingOutput;
1939 }
1940 }
1941
Eric Laurent16c66dd2019-05-01 17:54:10 -07001942 // Flags disqualifying an output: the match must happen before calling selectOutput()
1943 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1944 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1945
1946 // Flags expressing a functional request: must be honored in priority over
1947 // other criteria
1948 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1949 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001950 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1951 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001952 // Flags expressing a performance request: have lower priority than serving
1953 // requested sampling rate or channel mask
1954 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1955 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1956 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1957
1958 const audio_output_flags_t functionalFlags =
1959 (audio_output_flags_t)(flags & kFunctionalFlags);
1960 const audio_output_flags_t performanceFlags =
1961 (audio_output_flags_t)(flags & kPerformanceFlags);
1962
1963 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1964
Eric Laurente552edb2014-03-10 17:42:56 -07001965 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001966 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001967 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001968 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001970 // with tiebreak preferring the minimum number of extra functional flags
1971 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001972 // 3: the output supporting the exact channel mask
1973 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001974 // 5: the output with the highest sampling rate if the requested sample rate is
1975 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 // 6: the output with the highest number of requested performance flags
1977 // 7: the output with the bit depth the closest to the requested one
1978 // 8: the primary output
1979 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001980
Eric Laurent16c66dd2019-05-01 17:54:10 -07001981 // matching criteria values in priority order for best matching output so far
1982 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001983
Eric Laurent16c66dd2019-05-01 17:54:10 -07001984 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1985 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1986 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001987
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001988 for (audio_io_handle_t output : outputs) {
1989 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001990 // matching criteria values in priority order for current output
1991 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001992
Eric Laurent16c66dd2019-05-01 17:54:10 -07001993 if (outputDesc->isDuplicated()) {
1994 continue;
1995 }
1996 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1997 continue;
1998 }
Eric Laurent8838a382014-09-08 16:44:28 -07001999
Eric Laurent16c66dd2019-05-01 17:54:10 -07002000 // If haptic channel is specified, use the haptic output if present.
2001 // When using haptic output, same audio format and sample rate are required.
2002 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002003 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002004 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2005 continue;
2006 }
2007 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002008 && format == outputDesc->getFormat()
2009 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002010 currentMatchCriteria[0] = outputHapticChannelCount;
2011 }
2012
2013 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002014 const int matchingFunctionalFlags =
2015 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2016 const int totalFunctionalFlags =
2017 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2018 // Prefer matching functional flags, but subtract unnecessary functional flags.
2019 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002020
2021 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002022 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2023 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2025 channelCount <= outputChannelCount) {
2026 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002027 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2028 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002030 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002031 currentMatchCriteria[3] = outputChannelCount;
2032 }
2033
2034 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002035 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002036 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002037 }
2038
2039 // performance flags match
2040 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2041
2042 // format match
2043 if (format != AUDIO_FORMAT_INVALID) {
2044 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002045 PolicyAudioPort::kFormatDistanceMax -
2046 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 }
2048
2049 // primary output match
2050 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2051
2052 // compare match criteria by priority then value
2053 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2054 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2055 bestMatchCriteria = currentMatchCriteria;
2056 bestOutput = output;
2057
2058 std::stringstream result;
2059 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2060 std::ostream_iterator<int>(result, " "));
2061 ALOGV("%s new bestOutput %d criteria %s",
2062 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002063 }
2064 }
2065
Eric Laurent16c66dd2019-05-01 17:54:10 -07002066 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002067}
2068
Eric Laurent8fc147b2018-07-22 19:13:55 -07002069status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002070{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002071 ALOGV("%s portId %d", __FUNCTION__, portId);
2072
2073 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2074 if (outputDesc == 0) {
2075 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002076 return BAD_VALUE;
2077 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002078 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002079
Eric Laurent8fc147b2018-07-22 19:13:55 -07002080 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002081 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002082
Eric Laurent733ce942017-12-07 12:18:25 -08002083 status_t status = outputDesc->start();
2084 if (status != NO_ERROR) {
2085 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002086 }
2087
Eric Laurent97ac8712018-07-27 18:59:02 -07002088 uint32_t delayMs;
2089 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002090
2091 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002092 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002093 if (status == DEAD_OBJECT) {
2094 sp<SwAudioOutputDescriptor> desc =
2095 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2096 if (desc == nullptr) {
2097 // This is not common, it may indicate something wrong with the HAL.
2098 ALOGE("%s unable to open output with default config", __func__);
2099 return status;
2100 }
2101 desc->mUsePreferredMixerAttributes = true;
2102 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002103 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002104 }
jiabina84c3d32022-12-02 18:59:55 +00002105
2106 // If the client is the first one active on preferred mixer parameters, reopen the output
2107 // if the current mixer parameters doesn't match the preferred one.
2108 if (outputDesc->devices().size() == 1) {
2109 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2110 outputDesc->devices()[0]->getId(), client->strategy());
2111 if (info != nullptr && info->getUid() == client->uid()) {
2112 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2113 info->getConfigBase(), info->getFlags())) {
2114 stopSource(outputDesc, client);
2115 outputDesc->stop();
2116 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2117 config.channel_mask = info->getConfigBase().channel_mask;
2118 config.sample_rate = info->getConfigBase().sample_rate;
2119 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002120 sp<SwAudioOutputDescriptor> desc =
2121 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2122 if (desc == nullptr) {
2123 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002124 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002125 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002126 // Intentionally return error to let the client side resending request for
2127 // creating and starting.
2128 return DEAD_OBJECT;
2129 }
2130 info->increaseActiveClient();
2131 }
2132 }
2133
Eric Laurentc75307b2015-03-17 15:29:32 -07002134 if (delayMs != 0) {
2135 usleep(delayMs * 1000);
2136 }
2137
2138 return status;
2139}
2140
Eric Laurent96d1dda2022-03-14 17:14:19 +01002141bool AudioPolicyManager::isLeUnicastActive() const {
2142 if (isInCall()) {
2143 return true;
2144 }
2145 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2146}
2147
2148bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2149 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2150 return false;
2151 }
2152 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2153 ALOGV("%s active %d", __func__, active);
2154 return active;
2155}
2156
Eric Laurent97ac8712018-07-27 18:59:02 -07002157status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2158 const sp<TrackClientDescriptor>& client,
2159 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002160{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002161 // cannot start playback of STREAM_TTS if any other output is being used
2162 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002163
2164 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002165 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002166 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002167 auto clientStrategy = client->strategy();
2168 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002169 if (stream == AUDIO_STREAM_TTS) {
2170 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002171 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002172 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002173 return INVALID_OPERATION;
2174 } else {
2175 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2176 }
2177 } else {
2178 // some playback other than beacon starts
2179 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2180 }
2181
Eric Laurent77305a62016-07-25 16:39:22 -07002182 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002183 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002184 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002185
François Gaffie11d30102018-11-02 16:09:09 +01002186 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002187 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002188 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002189 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002190 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002191 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002192 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002193 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002194 } else {
2195 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002196 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002197 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2198 AUDIO_FORMAT_DEFAULT);
2199 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2200 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002201 }
2202
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002203 // requiresMuteCheck is false when we can bypass mute strategy.
2204 // It covers a common case when there is no materially active audio
2205 // and muting would result in unnecessary delay and dropped audio.
2206 const uint32_t outputLatencyMs = outputDesc->latency();
2207 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002208 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002209
Eric Laurente552edb2014-03-10 17:42:56 -07002210 // increment usage count for this stream on the requested output:
2211 // NOTE that the usage count is the same for duplicated output and hardware output which is
2212 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002213 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002214
2215 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002216 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2217 client->isPreferredDeviceForExclusiveUse()) {
2218 // Preferred device may be exclusive, use only if no other active clients on this output
2219 devices = DeviceVector(
2220 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2221 } else {
2222 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2223 }
François Gaffie11d30102018-11-02 16:09:09 +01002224 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002225 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002226 }
2227 }
Eric Laurente552edb2014-03-10 17:42:56 -07002228
François Gaffiec005e562018-11-06 15:04:49 +01002229 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002230 selectOutputForMusicEffects();
2231 }
2232
François Gaffie1c878552018-11-22 16:53:21 +01002233 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002234 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002235 if (devices.isEmpty()) {
2236 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002237 }
François Gaffiec005e562018-11-06 15:04:49 +01002238 bool shouldWait =
2239 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2240 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2241 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002242 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002243 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002244 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002245 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002246 // An output has a shared device if
2247 // - managed by the same hw module
2248 // - supports the currently selected device
2249 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002250 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002251
Eric Laurent77305a62016-07-25 16:39:22 -07002252 // force a device change if any other output is:
2253 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002254 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002255 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002256 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002257 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002258 // change the device currently selected by the other output.
2259 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002260 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002261 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002262 force = true;
2263 }
2264 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002265 // a notification so that audio focus effect can propagate, or that a mute/unmute
2266 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002267 const uint32_t latencyMs = desc->latency();
2268 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2269
2270 if (shouldWait && isActive && (waitMs < latencyMs)) {
2271 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002272 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002273
2274 // Require mute check if another output is on a shared device
2275 // and currently active to have proper drain and avoid pops.
2276 // Note restoring AudioTracks onto this output needs to invoke
2277 // a volume ramp if there is no mute.
2278 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002279 }
2280 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002281
jiabin3ff8d7d2022-12-13 06:27:44 +00002282 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2283 // If the output is open with preferred mixer attributes, but the routed device is
2284 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2285 // changed.
2286 return DEAD_OBJECT;
2287 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002288 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002289 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002290
Eric Laurente552edb2014-03-10 17:42:56 -07002291 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002292 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002293 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002294 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002295 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002296 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002297 outputDesc->useHwGain() /*force*/)) {
2298 // request AudioService to reinitialize the volume curves asynchronously
2299 ALOGE("checkAndSetVolume failed, requesting volume range init");
2300 mpClientInterface->onVolumeRangeInitRequest();
2301 };
Eric Laurente552edb2014-03-10 17:42:56 -07002302
2303 // update the outputs if starting an output with a stream that can affect notification
2304 // routing
2305 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002306
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002307 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002308 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002309 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002310 }
Eric Laurentdc462862016-07-19 12:29:53 -07002311
2312 if (waitMs > muteWaitMs) {
2313 *delayMs = waitMs - muteWaitMs;
2314 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002315
2316 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2317 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2318 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2319 // change occurs after the MixerThread starts and causes a stream volume
2320 // glitch.
2321 //
2322 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002323 }
Eric Laurentdc462862016-07-19 12:29:53 -07002324
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002325 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002326 mEngine->getForceUse(
2327 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002328 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002329 }
2330
Eric Laurent97ac8712018-07-27 18:59:02 -07002331 // Automatically enable the remote submix input when output is started on a re routing mix
2332 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002333 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2334 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002335 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2336 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2337 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002338 "remote-submix",
2339 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002340 }
2341
Eric Laurent96d1dda2022-03-14 17:14:19 +01002342 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2343
Eric Laurente552edb2014-03-10 17:42:56 -07002344 return NO_ERROR;
2345}
2346
Eric Laurent96d1dda2022-03-14 17:14:19 +01002347void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2348 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2349 bool isUnicastActive = isLeUnicastActive();
2350
2351 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002352 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002353 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2354 for (size_t i = 0; i < mOutputs.size(); i++) {
2355 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2356 if (desc != ignoredOutput && desc->isActive()
2357 && ((isUnicastActive &&
2358 !desc->devices().
2359 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2360 || (wasUnicastActive &&
2361 !desc->devices().getDevicesFromTypes(
2362 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2363 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2364 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002365 if (desc->mUsePreferredMixerAttributes && force) {
2366 // If the device is using preferred mixer attributes, the output need to reopen
2367 // with default configuration when the new selected devices are different from
2368 // current routing devices.
2369 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2370 continue;
2371 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002372 setOutputDevices(desc, newDevices, force, delayMs);
2373 // re-apply device specific volume if not done by setOutputDevice()
2374 if (!force) {
2375 applyStreamVolumes(desc, newDevices.types(), delayMs);
2376 }
2377 }
2378 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002379 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002380 }
2381}
2382
Eric Laurent8fc147b2018-07-22 19:13:55 -07002383status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002384{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002385 ALOGV("%s portId %d", __FUNCTION__, portId);
2386
2387 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2388 if (outputDesc == 0) {
2389 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002390 return BAD_VALUE;
2391 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002392 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002393
Eric Laurent97ac8712018-07-27 18:59:02 -07002394 ALOGV("stopOutput() output %d, stream %d, session %d",
2395 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002396
Eric Laurent97ac8712018-07-27 18:59:02 -07002397 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002398
Eric Laurent733ce942017-12-07 12:18:25 -08002399 if (status == NO_ERROR ) {
2400 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002401 } else {
2402 return status;
2403 }
2404
2405 if (outputDesc->devices().size() == 1) {
2406 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2407 outputDesc->devices()[0]->getId(), client->strategy());
2408 if (info != nullptr && info->getUid() == client->uid()) {
2409 info->decreaseActiveClient();
2410 if (info->getActiveClientCount() == 0) {
2411 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2412 }
2413 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002414 }
2415 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002416}
2417
Eric Laurent97ac8712018-07-27 18:59:02 -07002418status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2419 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002420{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002421 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002422 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002423 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002424 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002425
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002426 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2427
François Gaffie1c878552018-11-22 16:53:21 +01002428 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2429 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002430 // Automatically disable the remote submix input when output is stopped on a
2431 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002432 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002433 if (isSingleDeviceType(
2434 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002435 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002436 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002437 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2438 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002439 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002440 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002441 }
2442 }
2443 bool forceDeviceUpdate = false;
2444 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002445 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002446 forceDeviceUpdate = true;
2447 }
2448
Eric Laurente552edb2014-03-10 17:42:56 -07002449 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002450 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002451
Eric Laurente552edb2014-03-10 17:42:56 -07002452 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002453 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002454 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002455 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002456
2457 // If the routing does not change, if an output is routed on a device using HwGain
2458 // (aka setAudioPortConfig) and there are still active clients following different
2459 // volume group(s), force reapply volume
2460 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2461 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2462
Eric Laurente552edb2014-03-10 17:42:56 -07002463 // delay the device switch by twice the latency because stopOutput() is executed when
2464 // the track stop() command is received and at that time the audio track buffer can
2465 // still contain data that needs to be drained. The latency only covers the audio HAL
2466 // and kernel buffers. Also the latency does not always include additional delay in the
2467 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002468 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2469 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002470
2471 // force restoring the device selection on other active outputs if it differs from the
2472 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002473 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002474 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002475 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002476 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002477 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002478 desc->isActive() &&
2479 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002480 (newDevices != desc->devices())) {
2481 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2482 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002483
jiabin3ff8d7d2022-12-13 06:27:44 +00002484 if (desc->mUsePreferredMixerAttributes && force) {
2485 // If the device is using preferred mixer attributes, the output need to
2486 // reopen with default configuration when the new selected devices are
2487 // different from current routing devices.
2488 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2489 continue;
2490 }
François Gaffie11d30102018-11-02 16:09:09 +01002491 setOutputDevices(desc, newDevices2, force, delayMs);
2492
Eric Laurent57de36c2016-09-28 16:59:11 -07002493 // re-apply device specific volume if not done by setOutputDevice()
2494 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002495 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002496 }
Eric Laurente552edb2014-03-10 17:42:56 -07002497 }
2498 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002499 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002500 // update the outputs if stopping one with a stream that can affect notification routing
2501 handleNotificationRoutingForStream(stream);
2502 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002503
2504 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2505 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002506 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002507 }
2508
François Gaffiec005e562018-11-06 15:04:49 +01002509 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002510 selectOutputForMusicEffects();
2511 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002512
2513 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2514
Eric Laurente552edb2014-03-10 17:42:56 -07002515 return NO_ERROR;
2516 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002517 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002518 return INVALID_OPERATION;
2519 }
2520}
2521
jiabinbce0c1d2020-10-05 11:20:18 -07002522bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002523{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002524 ALOGV("%s portId %d", __FUNCTION__, portId);
2525
2526 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2527 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002528 // If an output descriptor is closed due to a device routing change,
2529 // then there are race conditions with releaseOutput from tracks
2530 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2531 // destroyed shortly thereafter.
2532 //
2533 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002534 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002535 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002536 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002537
2538 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002539
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302540 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2541 if (outputDesc->isClientActive(client)) {
2542 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2543 stopOutput(portId);
2544 }
2545
Eric Laurent8fc147b2018-07-22 19:13:55 -07002546 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2547 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002548 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002549 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002550 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002551 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002552 if (--outputDesc->mDirectOpenCount == 0) {
2553 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002554 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002555 }
2556 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302557
Andy Hung39efb7a2018-09-26 15:39:28 -07002558 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002559 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2560 // The output is pending reopened to query dynamic profiles and
2561 // there is no active clients
2562 closeOutput(outputDesc->mIoHandle);
2563 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2564 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2565 if (newOutputDesc == nullptr) {
2566 ALOGE("%s failed to open output", __func__);
2567 }
2568 return true;
2569 }
2570 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002571}
2572
Eric Laurentcaf7f482014-11-25 17:50:47 -08002573status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2574 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002575 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002576 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002577 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002578 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002579 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002580 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002581 input_type_t *inputType,
2582 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002583{
François Gaffiec005e562018-11-06 15:04:49 +01002584 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002585 "flags %#x attributes=%s requested device ID %d",
2586 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2587 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002588
Eric Laurentad2e7b92017-09-14 20:06:42 -07002589 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002590 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002591 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002592 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593 sp<AudioInputDescriptor> inputDesc;
2594 sp<RecordClientDescriptor> clientDesc;
2595 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002596 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002597 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002598
2599 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2600 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2601 return INVALID_OPERATION;
2602 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002603
Francois Gaffie716e1432019-01-14 16:58:59 +01002604 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2605 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002606 }
2607
Paul McLean466dc8e2015-04-17 13:15:36 -06002608 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002609 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002610 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002611
Eric Laurentad2e7b92017-09-14 20:06:42 -07002612 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2613 // possible
2614 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2615 *input != AUDIO_IO_HANDLE_NONE) {
2616 ssize_t index = mInputs.indexOfKey(*input);
2617 if (index < 0) {
2618 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2619 status = BAD_VALUE;
2620 goto error;
2621 }
2622 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002623 RecordClientVector clients = inputDesc->getClientsForSession(session);
2624 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002625 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2626 status = BAD_VALUE;
2627 goto error;
2628 }
2629 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2630 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002631 // corresponds to a new client and is only permitted from the same UID.
2632 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 if (clients.size() > 1) {
2634 for (const auto& client : clients) {
2635 // The client map is ordered by key values (portId) and portIds are allocated
2636 // incrementaly. So the first client in this list is the one opened by audio flinger
2637 // when the mmap stream is created and should be ignored as it does not correspond
2638 // to an actual client
2639 if (client == *clients.cbegin()) {
2640 continue;
2641 }
2642 if (uid != client->uid() && !client->isSilenced()) {
2643 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2644 uid, client->portId(), client->uid());
2645 status = INVALID_OPERATION;
2646 goto error;
2647 }
Eric Laurent331679c2018-04-16 17:03:16 -07002648 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002649 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002650 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002651 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002652
Eric Laurentfecbceb2021-02-09 14:46:43 +01002653 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002654 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002655 }
2656
2657 *input = AUDIO_IO_HANDLE_NONE;
2658 *inputType = API_INPUT_INVALID;
2659
Francois Gaffie716e1432019-01-14 16:58:59 +01002660 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002661 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002662 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002663 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002664 ALOGW("%s could not find input mix for attr %s",
2665 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002666 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002667 }
jiabinc1de2df2019-05-07 14:26:40 -07002668 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2669 String8(attr->tags + strlen("addr=")),
2670 AUDIO_FORMAT_DEFAULT);
2671 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002672 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002673 __func__, attributes.source, attributes.tags);
2674 status = BAD_VALUE;
2675 goto error;
2676 }
2677
Kevin Rocard25f9b052019-02-27 15:08:54 -08002678 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2679 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2680 } else {
2681 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2682 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002683 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002684 if (explicitRoutingDevice != nullptr) {
2685 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002686 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002687 // Prevent from storing invalid requested device id in clients
2688 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002689 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002690 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2691 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002692 }
François Gaffie11d30102018-11-02 16:09:09 +01002693 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002694 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002695 status = BAD_VALUE;
2696 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002697 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002698 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2699 *inputType = API_INPUT_MIX_CAPTURE;
2700 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002701 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2702 // there is an external policy, but this input is attached to a mix of recorders,
2703 // meaning it receives audio injected into the framework, so the recorder doesn't
2704 // know about it and is therefore considered "legacy"
2705 *inputType = API_INPUT_LEGACY;
2706 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002707 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002708 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002709 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002710 } else {
2711 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002712 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002713
Eric Laurent599c7582015-12-07 18:05:55 -08002714 }
2715
François Gaffiec005e562018-11-06 15:04:49 +01002716 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002717 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002718 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002719 AudioProfileVector profiles;
2720 status_t ret = getProfilesForDevices(
2721 DeviceVector(device), profiles, flags, true /*isInput*/);
2722 if (ret == NO_ERROR && !profiles.empty()) {
2723 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2724 : *profiles[0]->getChannels().begin();
2725 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2726 : *profiles[0]->getSampleRates().begin();
2727 config->format = profiles[0]->getFormat();
2728 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002729 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002730 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002731
Eric Laurent8f42ea12018-08-08 09:08:25 -07002732exit:
2733
François Gaffiec005e562018-11-06 15:04:49 +01002734 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2735 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002736
Francois Gaffie716e1432019-01-14 16:58:59 +01002737 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002738 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002739 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002740
Mikhail Naganov2996f672019-04-18 12:29:59 -07002741 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002742 requestedDeviceId, attributes.source, flags,
2743 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002744 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002745 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002746
2747 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2748 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002749
Eric Laurent599c7582015-12-07 18:05:55 -08002750 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002751
2752error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002753 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002754}
2755
2756
François Gaffie11d30102018-11-02 16:09:09 +01002757audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002758 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002759 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002760 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002761 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002762 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002763{
2764 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002765 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002766 bool isSoundTrigger = false;
2767
François Gaffiec005e562018-11-06 15:04:49 +01002768 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002769 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2770 if (index >= 0) {
2771 input = mSoundTriggerSessions.valueFor(session);
2772 isSoundTrigger = true;
2773 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2774 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2775 } else {
2776 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002777 }
François Gaffiec005e562018-11-06 15:04:49 +01002778 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002779 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002780 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002781 }
2782
Carter Hsua3abb402021-10-26 11:11:20 +08002783 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2784 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2785 }
2786
Eric Laurentfe231122017-11-17 17:48:06 -08002787 // sampling rate and flags may be updated by getInputProfile
2788 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2789 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002790 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002791 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002792 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002793 // find a compatible input profile (not necessarily identical in parameters)
2794 sp<IOProfile> profile = getInputProfile(
2795 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2796 if (profile == nullptr) {
2797 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002798 }
jiabin2fd710d2022-05-02 23:20:22 +00002799
Glenn Kasten05ddca52016-02-11 08:17:12 -08002800 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002801 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002802 if (samplingRate == 0) {
2803 samplingRate = profileSamplingRate;
2804 }
Eric Laurente552edb2014-03-10 17:42:56 -07002805
Eric Laurent322b4d22015-04-03 15:57:54 -07002806 if (profile->getModuleHandle() == 0) {
2807 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002808 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002809 }
2810
Eric Laurentec376dc2021-04-08 20:41:22 +02002811 // Reuse an already opened input if a client with the same session ID already exists
2812 // on that input
2813 for (size_t i = 0; i < mInputs.size(); i++) {
2814 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2815 if (desc->mProfile != profile) {
2816 continue;
2817 }
2818 RecordClientVector clients = desc->clientsList();
2819 for (const auto &client : clients) {
2820 if (session == client->session()) {
2821 return desc->mIoHandle;
2822 }
2823 }
2824 }
2825
Eric Laurent3974e3b2017-12-07 17:58:43 -08002826 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002827 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002828 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002829 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002830 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002831 continue;
2832 }
2833 // if sound trigger, reuse input if used by other sound trigger on same session
2834 // else
2835 // reuse input if active client app is not in IDLE state
2836 //
2837 RecordClientVector clients = desc->clientsList();
2838 bool doClose = false;
2839 for (const auto& client : clients) {
2840 if (isSoundTrigger != client->isSoundTrigger()) {
2841 continue;
2842 }
2843 if (client->isSoundTrigger()) {
2844 if (session == client->session()) {
2845 return desc->mIoHandle;
2846 }
2847 continue;
2848 }
2849 if (client->active() && client->appState() != APP_STATE_IDLE) {
2850 return desc->mIoHandle;
2851 }
2852 doClose = true;
2853 }
2854 if (doClose) {
2855 closeInput(desc->mIoHandle);
2856 } else {
2857 i++;
2858 }
2859 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002860 }
2861
Eric Laurentfe231122017-11-17 17:48:06 -08002862 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002863
Eric Laurentfe231122017-11-17 17:48:06 -08002864 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2865 lConfig.sample_rate = profileSamplingRate;
2866 lConfig.channel_mask = profileChannelMask;
2867 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002868
François Gaffie11d30102018-11-02 16:09:09 +01002869 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002870
2871 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002872 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002873 (profileSamplingRate != lConfig.sample_rate) ||
2874 !audio_formats_match(profileFormat, lConfig.format) ||
2875 (profileChannelMask != lConfig.channel_mask)) {
2876 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002877 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002878 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002879 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002880 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002881 }
Eric Laurent599c7582015-12-07 18:05:55 -08002882 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002883 }
2884
Eric Laurentc722f302014-12-10 11:21:49 -08002885 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002886
Eric Laurent599c7582015-12-07 18:05:55 -08002887 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002888 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002889
Eric Laurent599c7582015-12-07 18:05:55 -08002890 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002891}
2892
Eric Laurent4eb58f12018-12-07 16:41:02 -08002893status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002894{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895 ALOGV("%s portId %d", __FUNCTION__, portId);
2896
2897 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2898 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002899 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002900 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002902 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002903 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 if (client->active()) {
2905 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2906 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002907 }
2908
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909 audio_session_t session = client->session();
2910
Eric Laurent4eb58f12018-12-07 16:41:02 -08002911 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002912
Eric Laurent4eb58f12018-12-07 16:41:02 -08002913 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002914
Eric Laurent4eb58f12018-12-07 16:41:02 -08002915 status_t status = inputDesc->start();
2916 if (status != NO_ERROR) {
2917 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002918 }
Eric Laurente552edb2014-03-10 17:42:56 -07002919
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002920 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002921 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002923
Eric Laurent8f42ea12018-08-08 09:08:25 -07002924 // indicate active capture to sound trigger service if starting capture from a mic on
2925 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002926 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002927 if (device != nullptr) {
2928 status = setInputDevice(input, device, true /* force */);
2929 } else {
2930 ALOGW("%s no new input device can be found for descriptor %d",
2931 __FUNCTION__, inputDesc->getId());
2932 status = BAD_VALUE;
2933 }
Eric Laurente552edb2014-03-10 17:42:56 -07002934
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002935 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002936 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002937 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002938 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002939 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2940 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002941 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002942 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002943
François Gaffie11d30102018-11-02 16:09:09 +01002944 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2945 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002946 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002947 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002948 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002949
Eric Laurent8f42ea12018-08-08 09:08:25 -07002950 // automatically enable the remote submix output when input is started if not
2951 // used by a policy mix of type MIX_TYPE_RECORDERS
2952 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002953 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002955 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002956 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002957 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2958 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002959 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002960 if (address != "") {
2961 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2962 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002963 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002964 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002965 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002966 } else if (status != NO_ERROR) {
2967 // Restore client activity state.
2968 inputDesc->setClientActive(client, false);
2969 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002970 }
2971
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002972 ALOGV("%s input %d source = %d status = %d exit",
2973 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002974
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002975 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002976}
2977
Eric Laurent8fc147b2018-07-22 19:13:55 -07002978status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002979{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002980 ALOGV("%s portId %d", __FUNCTION__, portId);
2981
2982 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2983 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002984 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002985 return BAD_VALUE;
2986 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002987 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002988 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989 if (!client->active()) {
2990 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002991 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002992 }
Carter Hsue6139d52021-07-08 10:30:20 +08002993 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002994 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002995
Eric Laurent8f42ea12018-08-08 09:08:25 -07002996 inputDesc->stop();
2997 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002998 auto current_source = inputDesc->source();
2999 setInputDevice(input, getNewInputDevice(inputDesc),
3000 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003002 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003003 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003004 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003005 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3006 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003008 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003009
3010 // automatically disable the remote submix output when input is stopped if not
3011 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003012 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003013 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003014 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003016 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3017 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003018 }
3019 if (address != "") {
3020 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3021 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003022 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 }
3024 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 resetInputDevice(input);
3026
3027 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3028 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003029 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3030 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003031 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003032 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 }
3034 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003035 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003036 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003037}
3038
Eric Laurent8fc147b2018-07-22 19:13:55 -07003039void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003040{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003041 ALOGV("%s portId %d", __FUNCTION__, portId);
3042
3043 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3044 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003046 return;
3047 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003048 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003049 audio_io_handle_t input = inputDesc->mIoHandle;
3050
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003052
Andy Hung39efb7a2018-09-26 15:39:28 -07003053 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003054
Andy Hung39efb7a2018-09-26 15:39:28 -07003055 if (inputDesc->getClientCount() > 0) {
3056 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003057 return;
3058 }
3059
Eric Laurent05b90f82014-08-27 15:32:29 -07003060 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003061 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003063}
3064
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003066{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003068
3069 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003071 }
3072}
3073
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3075{
3076 stopInput(portId);
3077 releaseInput(portId);
3078}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003079
Eric Laurent0dd51852019-04-19 18:18:58 -07003080void AudioPolicyManager::checkCloseInputs() {
3081 // After connecting or disconnecting an input device, close input if:
3082 // - it has no client (was just opened to check profile) OR
3083 // - none of its supported devices are connected anymore OR
3084 // - one of its clients cannot be routed to one of its supported
3085 // devices anymore. Otherwise update device selection
3086 std::vector<audio_io_handle_t> inputsToClose;
3087 for (size_t i = 0; i < mInputs.size(); i++) {
3088 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3089 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003090 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003091 inputsToClose.push_back(mInputs.keyAt(i));
3092 } else {
3093 bool close = false;
3094 for (const auto& client : input->clientsList()) {
3095 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003096 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3097 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003098 if (!input->supportedDevices().contains(device)) {
3099 close = true;
3100 break;
3101 }
3102 }
3103 if (close) {
3104 inputsToClose.push_back(mInputs.keyAt(i));
3105 } else {
3106 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3107 }
3108 }
3109 }
3110
3111 for (const audio_io_handle_t handle : inputsToClose) {
3112 ALOGV("%s closing input %d", __func__, handle);
3113 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003114 }
Eric Laurentd4692962014-05-05 18:13:44 -07003115}
3116
François Gaffie251c7f02018-11-07 10:41:08 +01003117void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003118{
3119 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003120 if (indexMin < 0 || indexMax < 0) {
3121 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3122 return;
3123 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003124 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003125
3126 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003127 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3128 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003129 continue;
3130 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003131 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003132 }
Eric Laurente552edb2014-03-10 17:42:56 -07003133}
3134
Eric Laurente0720872014-03-11 09:30:41 -07003135status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003136 int index,
3137 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003138{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003139 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003140 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3141 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3142 return NO_ERROR;
3143 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003144 ALOGV("%s: stream %s attributes=%s", __func__,
3145 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003146 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003147}
3148
Eric Laurente0720872014-03-11 09:30:41 -07003149status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003150 int *index,
3151 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003152{
François Gaffiec005e562018-11-06 15:04:49 +01003153 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3154 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003155 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003156 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003157 deviceTypes = mEngine->getOutputDevicesForStream(
3158 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003159 }
jiabin9a3361e2019-10-01 09:38:30 -07003160 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003161}
3162
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003163status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003164 int index,
3165 audio_devices_t device)
3166{
3167 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003168 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3169 if (group == VOLUME_GROUP_NONE) {
3170 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003171 return BAD_VALUE;
3172 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003173 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003174 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003175 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003176 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003177 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3178 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3179 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3180 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003181 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3182
3183 status = setVolumeCurveIndex(index, device, curves);
3184 if (status != NO_ERROR) {
3185 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3186 return status;
3187 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003188
jiabin9a3361e2019-10-01 09:38:30 -07003189 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003190 auto curCurvAttrs = curves.getAttributes();
3191 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3192 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003193 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003194 } else if (!curves.getStreamTypes().empty()) {
3195 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003196 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003197 } else {
3198 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3199 return BAD_VALUE;
3200 }
jiabin9a3361e2019-10-01 09:38:30 -07003201 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3202 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003203
François Gaffiecfe17322018-11-07 13:41:29 +01003204 // update volume on all outputs and streams matching the following:
3205 // - The requested stream (or a stream matching for volume control) is active on the output
3206 // - The device (or devices) selected by the engine for this stream includes
3207 // the requested device
3208 // - For non default requested device, currently selected device on the output is either the
3209 // requested device or one of the devices selected by the engine for this stream
3210 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3211 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003212 for (size_t i = 0; i < mOutputs.size(); i++) {
3213 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003214 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003215
jiabin9a3361e2019-10-01 09:38:30 -07003216 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3217 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003218 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003219
3220 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003221 continue;
3222 }
3223 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3224 curDevices.find(device) == curDevices.end()) {
3225 continue;
3226 }
3227 bool applyVolume = false;
3228 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3229 curSrcDevices.insert(device);
3230 applyVolume = (curSrcDevices.find(
3231 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3232 } else {
3233 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3234 }
3235 if (!applyVolume) {
3236 continue; // next output
3237 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003238 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3239 // If a higher priority strategy is active, and the output is routed to a device with a
3240 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003241 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003242 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003243 // If the volume source is active with higher priority source, ensure at least Sw Muted
3244 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003245 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3246 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3247 false /*preferredDevice*/);
3248 if (activeClients.empty()) {
3249 continue;
3250 }
3251 bool isPreempted = false;
3252 bool isHigherPriority = productStrategy < strategy;
3253 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003254 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003255 ALOGV("%s: Strategy=%d (\nrequester:\n"
3256 " group %d, volumeGroup=%d attributes=%s)\n"
3257 " higher priority source active:\n"
3258 " volumeGroup=%d attributes=%s) \n"
3259 " on output %zu, bailing out", __func__, productStrategy,
3260 group, group, toString(attributes).c_str(),
3261 client->volumeSource(), toString(client->attributes()).c_str(), i);
3262 applyVolume = false;
3263 isPreempted = true;
3264 break;
3265 }
3266 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003267 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003268 applyVolume = true;
3269 }
3270 }
3271 if (isPreempted || applyVolume) {
3272 break;
3273 }
3274 }
3275 if (!applyVolume) {
3276 continue; // next output
3277 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003278 }
François Gaffieed91f582020-01-31 10:35:37 +01003279 //FIXME: workaround for truncated touch sounds
3280 // delayed volume change for system stream to be removed when the problem is
3281 // handled by system UI
3282 status_t volStatus = checkAndSetVolume(
3283 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003284 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003285 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3286 if (volStatus != NO_ERROR) {
3287 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003288 }
3289 }
François Gaffiecfe17322018-11-07 13:41:29 +01003290 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3291 return status;
3292}
3293
François Gaffieaaac0fd2018-11-22 17:56:39 +01003294status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003295 audio_devices_t device,
3296 IVolumeCurves &volumeCurves)
3297{
3298 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3299 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003300 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3301 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003302 (index > volumeCurves.getVolumeIndexMax())) {
3303 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3304 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3305 return BAD_VALUE;
3306 }
3307 if (!audio_is_output_device(device)) {
3308 return BAD_VALUE;
3309 }
3310
3311 // Force max volume if stream cannot be muted
3312 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3313
François Gaffieaaac0fd2018-11-22 17:56:39 +01003314 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003315 volumeCurves.addCurrentVolumeIndex(device, index);
3316 return NO_ERROR;
3317}
3318
3319status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3320 int &index,
3321 audio_devices_t device)
3322{
3323 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3324 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003325 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003326 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003327 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003328 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003329 }
jiabin9a3361e2019-10-01 09:38:30 -07003330 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003331}
3332
3333status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3334 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003335 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003336{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003337 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003338 return BAD_VALUE;
3339 }
jiabin9a3361e2019-10-01 09:38:30 -07003340 index = curves.getVolumeIndex(deviceTypes);
3341 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003342 return NO_ERROR;
3343}
3344
3345status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3346 int &index)
3347{
3348 index = getVolumeCurves(attr).getVolumeIndexMin();
3349 return NO_ERROR;
3350}
3351
3352status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3353 int &index)
3354{
3355 index = getVolumeCurves(attr).getVolumeIndexMax();
3356 return NO_ERROR;
3357}
3358
Eric Laurent36829f92017-04-07 19:04:42 -07003359audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003360{
3361 // select one output among several suitable for global effects.
3362 // The priority is as follows:
3363 // 1: An offloaded output. If the effect ends up not being offloadable,
3364 // AudioFlinger will invalidate the track and the offloaded output
3365 // will be closed causing the effect to be moved to a PCM output.
3366 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003367 // 3: The primary output
3368 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003369
François Gaffiec005e562018-11-06 15:04:49 +01003370 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3371 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003372 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003373
Eric Laurent36829f92017-04-07 19:04:42 -07003374 if (outputs.size() == 0) {
3375 return AUDIO_IO_HANDLE_NONE;
3376 }
Eric Laurente552edb2014-03-10 17:42:56 -07003377
Eric Laurent36829f92017-04-07 19:04:42 -07003378 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3379 bool activeOnly = true;
3380
3381 while (output == AUDIO_IO_HANDLE_NONE) {
3382 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3383 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3384 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3385
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003386 for (audio_io_handle_t output : outputs) {
3387 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003388 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003389 continue;
3390 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003391 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3392 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003393 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003394 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003395 }
3396 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003397 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003398 }
3399 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003400 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003401 }
3402 }
3403 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3404 output = outputOffloaded;
3405 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3406 output = outputDeepBuffer;
3407 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3408 output = outputPrimary;
3409 } else {
3410 output = outputs[0];
3411 }
3412 activeOnly = false;
3413 }
3414
3415 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003416 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003417 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3418 mMusicEffectOutput = output;
3419 }
3420
3421 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003422 return output;
3423}
3424
Eric Laurent36829f92017-04-07 19:04:42 -07003425audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3426{
3427 return selectOutputForMusicEffects();
3428}
3429
Eric Laurente0720872014-03-11 09:30:41 -07003430status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003431 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003432 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003433 int session,
3434 int id)
3435{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003436 if (session != AUDIO_SESSION_DEVICE) {
3437 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003438 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003439 index = mInputs.indexOfKey(io);
3440 if (index < 0) {
3441 ALOGW("registerEffect() unknown io %d", io);
3442 return INVALID_OPERATION;
3443 }
Eric Laurente552edb2014-03-10 17:42:56 -07003444 }
3445 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003446 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3447 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3448 || strategy == PRODUCT_STRATEGY_NONE));
3449 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003450}
3451
Eric Laurentc241b0d2018-11-28 09:08:49 -08003452status_t AudioPolicyManager::unregisterEffect(int id)
3453{
3454 if (mEffects.getEffect(id) == nullptr) {
3455 return INVALID_OPERATION;
3456 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003457 if (mEffects.isEffectEnabled(id)) {
3458 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3459 setEffectEnabled(id, false);
3460 }
3461 return mEffects.unregisterEffect(id);
3462}
3463
3464status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3465{
3466 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3467 if (effect == nullptr) {
3468 return INVALID_OPERATION;
3469 }
3470
3471 status_t status = mEffects.setEffectEnabled(id, enabled);
3472 if (status == NO_ERROR) {
3473 mInputs.trackEffectEnabled(effect, enabled);
3474 }
3475 return status;
3476}
3477
Eric Laurent6c796322019-04-09 14:13:17 -07003478
3479status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3480{
3481 mEffects.moveEffects(ids, io);
3482 return NO_ERROR;
3483}
3484
Eric Laurentc75307b2015-03-17 15:29:32 -07003485bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3486{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003487 auto vs = toVolumeSource(stream, false);
3488 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003489}
3490
3491bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3492{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003493 auto vs = toVolumeSource(stream, false);
3494 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003495}
3496
Eric Laurente0720872014-03-11 09:30:41 -07003497bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003498{
3499 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003500 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003501 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003502 return true;
3503 }
3504 }
3505 return false;
3506}
3507
Eric Laurent275e8e92014-11-30 15:14:47 -08003508// Register a list of custom mixes with their attributes and format.
3509// When a mix is registered, corresponding input and output profiles are
3510// added to the remote submix hw module. The profile contains only the
3511// parameters (sampling rate, format...) specified by the mix.
3512// The corresponding input remote submix device is also connected.
3513//
3514// When a remote submix device is connected, the address is checked to select the
3515// appropriate profile and the corresponding input or output stream is opened.
3516//
3517// When capture starts, getInputForAttr() will:
3518// - 1 look for a mix matching the address passed in attribtutes tags if any
3519// - 2 if none found, getDeviceForInputSource() will:
3520// - 2.1 look for a mix matching the attributes source
3521// - 2.2 if none found, default to device selection by policy rules
3522// At this time, the corresponding output remote submix device is also connected
3523// and active playback use cases can be transferred to this mix if needed when reconnecting
3524// after AudioTracks are invalidated
3525//
3526// When playback starts, getOutputForAttr() will:
3527// - 1 look for a mix matching the address passed in attribtutes tags if any
3528// - 2 if none found, look for a mix matching the attributes usage
3529// - 3 if none found, default to device and output selection by policy rules.
3530
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003531status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003532{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003533 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3534 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003535 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003536 sp<HwModule> rSubmixModule;
3537 // examine each mix's route type
3538 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003539 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003540 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3541 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3542 ALOGE("Unsupported Policy Mix %zu of %zu: "
3543 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3544 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003545 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003546 break;
3547 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003548 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3549 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003550 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003551 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3552 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003553 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003554 rSubmixModule = mHwModules.getModuleFromName(
3555 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3556 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003557 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003558 i);
3559 res = INVALID_OPERATION;
3560 break;
3561 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003562 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003563
Eric Laurent97ac8712018-07-27 18:59:02 -07003564 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003565 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003566 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003567 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003568 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3569 } else {
3570 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3571 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003572 }
François Gaffie036e1e92015-03-19 10:16:24 +01003573
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003574 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003575 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003576 res = INVALID_OPERATION;
3577 break;
3578 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003579 audio_config_t outputConfig = mix.mFormat;
3580 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003581 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3582 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003583 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3584 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003585 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003586 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003587 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003588 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003589
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003590 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003591 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3592 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3593 ALOGE("Failed to set remote submix device available, type %u, address %s",
3594 mix.mDeviceType, address.string());
3595 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003596 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003597 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3598 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003599 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003600 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003601 i, mixes.size(), type, address.string());
3602
3603 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3604 mix.mDeviceType, mix.mDeviceAddress,
3605 String8(), AUDIO_FORMAT_DEFAULT);
3606 if (device == nullptr) {
3607 res = INVALID_OPERATION;
3608 break;
3609 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003610
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003611 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003612 // First try to find an already opened output supporting the device
3613 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003614 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003615
Eric Laurentc529cf62020-04-17 18:19:10 -07003616 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003617 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003618 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3619 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003620 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003621 } else {
3622 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003623 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003624 }
3625 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003626 // If no output found, try to find a direct output profile supporting the device
3627 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3628 sp<HwModule> module = mHwModules[i];
3629 for (size_t j = 0;
3630 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3631 j++) {
3632 sp<IOProfile> profile = module->getOutputProfiles()[j];
3633 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3634 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3635 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3636 address.string());
3637 res = INVALID_OPERATION;
3638 } else {
3639 foundOutput = true;
3640 }
3641 }
3642 }
3643 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003644 if (res != NO_ERROR) {
3645 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003646 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003647 res = INVALID_OPERATION;
3648 break;
3649 } else if (!foundOutput) {
3650 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003651 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 res = INVALID_OPERATION;
3653 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003654 } else {
3655 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003656 }
Eric Laurentc722f302014-12-10 11:21:49 -08003657 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003658 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003659 if (res != NO_ERROR) {
3660 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003661 } else if (checkOutputs) {
3662 checkForDeviceAndOutputChanges();
3663 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664 }
3665 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003666}
3667
3668status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3669{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003670 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003671 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003672 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 sp<HwModule> rSubmixModule;
3674 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003675 for (const auto& mix : mixes) {
3676 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003677
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003678 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003679 rSubmixModule = mHwModules.getModuleFromName(
3680 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3681 if (rSubmixModule == 0) {
3682 res = INVALID_OPERATION;
3683 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003684 }
3685 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003686
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003687 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003688
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003689 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 res = INVALID_OPERATION;
3691 continue;
3692 }
3693
Kevin Rocard04ed0462019-05-02 17:53:24 -07003694 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3695 if (getDeviceConnectionState(device, address.string()) ==
3696 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3697 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3698 address.string(), "remote-submix",
3699 AUDIO_FORMAT_DEFAULT);
3700 if (res != OK) {
3701 ALOGE("Error making RemoteSubmix device unavailable for mix "
3702 "with type %d, address %s", device, address.string());
3703 }
3704 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003705 }
jiabin5740f082019-08-19 15:08:30 -07003706 rSubmixModule->removeOutputProfile(address.c_str());
3707 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003708
Kevin Rocard153f92d2018-12-18 18:33:28 -08003709 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003710 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 res = INVALID_OPERATION;
3712 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003713 } else {
3714 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003715 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003716 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003717 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003718 if (res == NO_ERROR && checkOutputs) {
3719 checkForDeviceAndOutputChanges();
3720 updateCallAndOutputRouting();
3721 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003723}
3724
Mikhail Naganov100f0122018-11-29 11:22:16 -08003725void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3726{
3727 size_t i = 0;
3728 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3729 for (const auto& fmt : mManualSurroundFormats) {
3730 if (i++ != 0) dst->append(", ");
3731 std::string sfmt;
3732 FormatConverter::toString(fmt, sfmt);
3733 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3734 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3735 }
3736}
3737
Eric Laurentc529cf62020-04-17 18:19:10 -07003738// Returns true if all devices types match the predicate and are supported by one HW module
3739bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003740 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003741 std::function<bool(audio_devices_t)> predicate,
3742 const char *context) {
3743 for (size_t i = 0; i < devices.size(); i++) {
3744 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003745 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003746 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003747 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003748 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003749 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003750 return false;
3751 }
3752 }
3753 return true;
3754}
3755
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003756status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003757 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003758 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003759 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3760 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003761 }
3762 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003763 if (res != NO_ERROR) {
3764 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3765 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003766 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003767
3768 checkForDeviceAndOutputChanges();
3769 updateCallAndOutputRouting();
3770
3771 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003772}
3773
3774status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3775 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003776 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3777 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003778 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003779 __FUNCTION__, uid);
3780 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003781 }
3782
Eric Laurentc529cf62020-04-17 18:19:10 -07003783 checkForDeviceAndOutputChanges();
3784 updateCallAndOutputRouting();
3785
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003786 return res;
3787}
3788
Eric Laurent2517af32020-11-25 15:31:27 +01003789
jiabin0a488932020-08-07 17:32:40 -07003790status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3791 device_role_t role,
3792 const AudioDeviceTypeAddrVector &devices) {
3793 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3794 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003795
Eric Laurentc529cf62020-04-17 18:19:10 -07003796 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003797 return BAD_VALUE;
3798 }
jiabin0a488932020-08-07 17:32:40 -07003799 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003800 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003801 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3802 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003803 return status;
3804 }
3805
3806 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003807
3808 bool forceVolumeReeval = false;
3809 // FIXME: workaround for truncated touch sounds
3810 // to be removed when the problem is handled by system UI
3811 uint32_t delayMs = 0;
3812 if (strategy == mCommunnicationStrategy) {
3813 forceVolumeReeval = true;
3814 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3815 updateInputRouting();
3816 }
3817 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003818
3819 return NO_ERROR;
3820}
3821
3822void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3823{
3824 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003825 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003826 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003827 // Only apply special touch sound delay once
3828 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003829 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003830 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003831 for (size_t i = 0; i < mOutputs.size(); i++) {
3832 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3833 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003834 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3835 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003836 // As done in setDeviceConnectionState, we could also fix default device issue by
3837 // preventing the force re-routing in case of default dev that distinguishes on address.
3838 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003839 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003840 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3841 // If the device is using preferred mixer attributes, the output need to reopen
3842 // with default configuration when the new selected devices are different from
3843 // current routing devices.
3844 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3845 continue;
3846 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003847 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3848 true /*requiresMuteCheck*/,
3849 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003850 // Only apply special touch sound delay once
3851 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003852 }
3853 if (forceVolumeReeval && !newDevices.isEmpty()) {
3854 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3855 }
3856 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003857 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003858 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003859}
3860
Eric Laurent2517af32020-11-25 15:31:27 +01003861void AudioPolicyManager::updateInputRouting() {
3862 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303863 // Skip for hotword recording as the input device switch
3864 // is handled within sound trigger HAL
3865 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3866 continue;
3867 }
Eric Laurent2517af32020-11-25 15:31:27 +01003868 auto newDevice = getNewInputDevice(activeDesc);
3869 // Force new input selection if the new device can not be reached via current input
3870 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3871 setInputDevice(activeDesc->mIoHandle, newDevice);
3872 } else {
3873 closeInput(activeDesc->mIoHandle);
3874 }
3875 }
3876}
3877
jiabin0a488932020-08-07 17:32:40 -07003878status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3879 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003880{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003881 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003882
jiabin0a488932020-08-07 17:32:40 -07003883 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003884 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003885 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3886 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003887 return status;
3888 }
3889
3890 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003891
3892 bool forceVolumeReeval = false;
3893 // FIXME: workaround for truncated touch sounds
3894 // to be removed when the problem is handled by system UI
3895 uint32_t delayMs = 0;
3896 if (strategy == mCommunnicationStrategy) {
3897 forceVolumeReeval = true;
3898 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3899 updateInputRouting();
3900 }
3901 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003902
3903 return NO_ERROR;
3904}
3905
jiabin0a488932020-08-07 17:32:40 -07003906status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3907 device_role_t role,
3908 AudioDeviceTypeAddrVector &devices) {
3909 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003910}
3911
Jiabin Huang3b98d322020-09-03 17:54:16 +00003912status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3913 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3914 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3915 dumpAudioDeviceTypeAddrVector(devices).c_str());
3916
Mikhail Naganov55773032020-10-01 15:08:13 -07003917 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003918 return BAD_VALUE;
3919 }
3920 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3921 ALOGW_IF(status != NO_ERROR,
3922 "Engine could not set preferred devices %s for audio source %d role %d",
3923 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3924
3925 return status;
3926}
3927
3928status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3929 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3930 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3931 dumpAudioDeviceTypeAddrVector(devices).c_str());
3932
Mikhail Naganov55773032020-10-01 15:08:13 -07003933 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003934 return BAD_VALUE;
3935 }
3936 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3937 ALOGW_IF(status != NO_ERROR,
3938 "Engine could not add preferred devices %s for audio source %d role %d",
3939 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3940
Eric Laurent2517af32020-11-25 15:31:27 +01003941 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003942 return status;
3943}
3944
3945status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3946 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3947{
3948 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3949 dumpAudioDeviceTypeAddrVector(devices).c_str());
3950
Mikhail Naganov55773032020-10-01 15:08:13 -07003951 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003952 return BAD_VALUE;
3953 }
3954
3955 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3956 audioSource, role, devices);
3957 ALOGW_IF(status != NO_ERROR,
3958 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3959
Eric Laurent2517af32020-11-25 15:31:27 +01003960 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003961 return status;
3962}
3963
3964status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3965 device_role_t role) {
3966 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3967
3968 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3969 ALOGW_IF(status != NO_ERROR,
3970 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3971
Eric Laurent2517af32020-11-25 15:31:27 +01003972 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003973 return status;
3974}
3975
3976status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3977 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3978 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3979}
3980
Oscar Azucena90e77632019-11-27 17:12:28 -08003981status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003982 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003983 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003984 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3985 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003986 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003987 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3988 if (status != NO_ERROR) {
3989 ALOGE("%s() could not set device affinity for userId %d",
3990 __FUNCTION__, userId);
3991 return status;
3992 }
3993
3994 // reevaluate outputs for all devices
3995 checkForDeviceAndOutputChanges();
3996 updateCallAndOutputRouting();
3997
3998 return NO_ERROR;
3999}
4000
4001status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004002 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08004003 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4004 if (status != NO_ERROR) {
4005 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4006 __FUNCTION__, userId);
4007 return status;
4008 }
4009
4010 // reevaluate outputs for all devices
4011 checkForDeviceAndOutputChanges();
4012 updateCallAndOutputRouting();
4013
4014 return NO_ERROR;
4015}
4016
Andy Hungc29d82b2018-10-05 12:23:17 -07004017void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004018{
Andy Hungc29d82b2018-10-05 12:23:17 -07004019 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004020 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004021 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004022 std::string stateLiteral;
4023 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004024 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004025 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4026 "communications", "media", "record", "dock", "system",
4027 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4028 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4029 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004030 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4031 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4032 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4033 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4034 dst->append(" (MANUAL: ");
4035 dumpManualSurroundFormats(dst);
4036 dst->append(")");
4037 }
4038 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004039 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004040 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4041 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004042 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004043 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004044
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004045 dst->append("\n");
4046 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4047 dst->append("\n");
4048 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004049 mHwModulesAll.dump(dst);
4050 mOutputs.dump(dst);
4051 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004052 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004053 mAudioPatches.dump(dst);
4054 mPolicyMixes.dump(dst);
4055 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004056
Kevin Rocardb99cc752019-03-21 20:52:24 -07004057 dst->appendFormat(" AllowedCapturePolicies:\n");
4058 for (auto& policy : mAllowedCapturePolicies) {
4059 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4060 }
4061
jiabina84c3d32022-12-02 18:59:55 +00004062 dst->appendFormat(" Preferred mixer audio configuration:\n");
4063 for (const auto it : mPreferredMixerAttrInfos) {
4064 dst->appendFormat(" - device port id: %d\n", it.first);
4065 for (const auto preferredMixerInfoIt : it.second) {
4066 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4067 preferredMixerInfoIt.second->dump(dst);
4068 }
4069 }
4070
François Gaffiec005e562018-11-06 15:04:49 +01004071 dst->appendFormat("\nPolicy Engine dump:\n");
4072 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004073}
4074
4075status_t AudioPolicyManager::dump(int fd)
4076{
4077 String8 result;
4078 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004079 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004080 return NO_ERROR;
4081}
4082
Kevin Rocardb99cc752019-03-21 20:52:24 -07004083status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4084{
4085 mAllowedCapturePolicies[uid] = capturePolicy;
4086 return NO_ERROR;
4087}
4088
Eric Laurente552edb2014-03-10 17:42:56 -07004089// This function checks for the parameters which can be offloaded.
4090// This can be enhanced depending on the capability of the DSP and policy
4091// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004092audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004093{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004094 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004095 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004096 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004097 offloadInfo.format,
4098 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4099 offloadInfo.has_video);
4100
jiabin2b9d5a12021-12-10 01:06:29 +00004101 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004102 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004103 }
4104
4105 // See if there is a profile to support this.
4106 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004107 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004108 offloadInfo.sample_rate,
4109 offloadInfo.format,
4110 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004111 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4112 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004113 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4114 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4115 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004116 if (profile == nullptr) {
4117 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4118 }
4119 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4120 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4121 }
4122 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004123}
4124
Michael Chana94fbb22018-04-24 14:31:19 +10004125bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4126 const audio_attributes_t& attributes) {
4127 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004128 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004129 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4130 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004131 config.sample_rate,
4132 config.format,
4133 config.channel_mask,
4134 output_flags,
4135 true /* directOnly */);
4136 ALOGV("%s() profile %sfound with name: %s, "
4137 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4138 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004139 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004140 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004141
4142 // also try the MSD module if compatible profile not found
4143 if (profile == nullptr) {
4144 profile = getMsdProfileForOutput(outputDevices,
4145 config.sample_rate,
4146 config.format,
4147 config.channel_mask,
4148 output_flags,
4149 true /* directOnly */);
4150 ALOGV("%s() MSD profile %sfound with name: %s, "
4151 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4152 __FUNCTION__, profile != 0 ? "" : "NOT ",
4153 (profile != 0 ? profile->getTagName().c_str() : "null"),
4154 config.sample_rate, config.format, config.channel_mask, output_flags);
4155 }
4156 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004157}
4158
jiabin2b9d5a12021-12-10 01:06:29 +00004159bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4160 bool durationIgnored) {
4161 if (mMasterMono) {
4162 return false; // no offloading if mono is set.
4163 }
4164
4165 // Check if offload has been disabled
4166 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4167 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4168 return false;
4169 }
4170
4171 // Check if stream type is music, then only allow offload as of now.
4172 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4173 {
4174 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4175 return false;
4176 }
4177
4178 //TODO: enable audio offloading with video when ready
4179 const bool allowOffloadWithVideo =
4180 property_get_bool("audio.offload.video", false /* default_value */);
4181 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4182 ALOGV("%s: has_video == true, returning false", __func__);
4183 return false;
4184 }
4185
4186 //If duration is less than minimum value defined in property, return false
4187 const int min_duration_secs = property_get_int32(
4188 "audio.offload.min.duration.secs", -1 /* default_value */);
4189 if (!durationIgnored) {
4190 if (min_duration_secs >= 0) {
4191 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4192 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4193 __func__, min_duration_secs);
4194 return false;
4195 }
4196 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4197 ALOGV("%s: Offload denied by duration < default min(=%u)",
4198 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4199 return false;
4200 }
4201 }
4202
4203 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4204 // creating an offloaded track and tearing it down immediately after start when audioflinger
4205 // detects there is an active non offloadable effect.
4206 // FIXME: We should check the audio session here but we do not have it in this context.
4207 // This may prevent offloading in rare situations where effects are left active by apps
4208 // in the background.
4209 if (mEffects.isNonOffloadableEffectEnabled()) {
4210 return false;
4211 }
4212
4213 return true;
4214}
4215
4216audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4217 const audio_config_t *config) {
4218 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4219 offloadInfo.format = config->format;
4220 offloadInfo.sample_rate = config->sample_rate;
4221 offloadInfo.channel_mask = config->channel_mask;
4222 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4223 offloadInfo.has_video = false;
4224 offloadInfo.is_streaming = false;
4225 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4226
4227 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4228 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4229 audio_flags_to_audio_output_flags(attr->flags, &flags);
4230 // only retain flags that will drive compressed offload or passthrough
4231 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4232 if (offloadPossible) {
4233 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4234 }
4235 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4236
Dorin Drimusfae3c642022-03-17 18:36:30 +01004237 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004238 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004239 DeviceVector outputDevices = engineOutputDevices;
4240 // the MSD module checks for different conditions and output devices
4241 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4242 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4243 continue;
4244 }
4245 outputDevices = getMsdAudioOutDevices();
4246 }
jiabin2b9d5a12021-12-10 01:06:29 +00004247 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004248 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004249 config->sample_rate, nullptr /*updatedSamplingRate*/,
4250 config->format, nullptr /*updatedFormat*/,
4251 config->channel_mask, nullptr /*updatedChannelMask*/,
4252 flags)) {
4253 continue;
4254 }
4255 // reject profiles not corresponding to a device currently available
4256 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4257 continue;
4258 }
4259 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4260 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004261 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004262 != AUDIO_DIRECT_NOT_SUPPORTED) {
4263 // Already reports offload gapless supported. No need to report offload support.
4264 continue;
4265 }
4266 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4267 != AUDIO_OUTPUT_FLAG_NONE) {
4268 // If offload gapless is reported, no need to report offload support.
4269 directMode = (audio_direct_mode_t) ((directMode &
4270 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4271 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4272 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004273 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004274 }
4275 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004276 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004277 }
4278 }
4279 }
4280 return directMode;
4281}
4282
Dorin Drimusf2196d82022-01-03 12:11:18 +01004283status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4284 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004285 if (mEffects.isNonOffloadableEffectEnabled()) {
4286 return OK;
4287 }
jiabinf1c73972022-04-14 16:28:52 -07004288 DeviceVector devices;
4289 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004290 if (status != OK) {
4291 return status;
4292 }
4293 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4294 if (devices.empty()) {
4295 return OK; // no output devices for the attributes
4296 }
jiabinf1c73972022-04-14 16:28:52 -07004297 return getProfilesForDevices(devices, audioProfilesVector,
4298 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004299}
4300
jiabina84c3d32022-12-02 18:59:55 +00004301status_t AudioPolicyManager::getSupportedMixerAttributes(
4302 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4303 ALOGV("%s, portId=%d", __func__, portId);
4304 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4305 if (deviceDescriptor == nullptr) {
4306 ALOGE("%s the requested device is currently unavailable", __func__);
4307 return BAD_VALUE;
4308 }
4309 for (const auto& hwModule : mHwModules) {
4310 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4311 if (curProfile->supportsDevice(deviceDescriptor)) {
4312 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4313 }
4314 }
4315 }
4316 return NO_ERROR;
4317}
4318
4319status_t AudioPolicyManager::setPreferredMixerAttributes(
4320 const audio_attributes_t *attr,
4321 audio_port_handle_t portId,
4322 uid_t uid,
4323 const audio_mixer_attributes_t *mixerAttributes) {
4324 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4325 "mixerBehavior=%d}, uid=%d, portId=%u",
4326 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4327 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4328 mixerAttributes->mixer_behavior, uid, portId);
4329 if (attr->usage != AUDIO_USAGE_MEDIA) {
4330 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4331 return BAD_VALUE;
4332 }
4333 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4334 if (deviceDescriptor == nullptr) {
4335 ALOGE("%s the requested device is currently unavailable", __func__);
4336 return BAD_VALUE;
4337 }
4338 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4339 ALOGE("%s(%d), type=%d, is not a usb output device",
4340 __func__, portId, deviceDescriptor->type());
4341 return BAD_VALUE;
4342 }
4343
4344 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4345 audio_flags_to_audio_output_flags(attr->flags, &flags);
4346 flags = (audio_output_flags_t) (flags |
4347 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4348 sp<IOProfile> profile = nullptr;
4349 DeviceVector devices(deviceDescriptor);
4350 for (const auto& hwModule : mHwModules) {
4351 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4352 if (curProfile->hasDynamicAudioProfile()
4353 && curProfile->isCompatibleProfile(devices,
4354 mixerAttributes->config.sample_rate,
4355 nullptr /*updatedSamplingRate*/,
4356 mixerAttributes->config.format,
4357 nullptr /*updatedFormat*/,
4358 mixerAttributes->config.channel_mask,
4359 nullptr /*updatedChannelMask*/,
4360 flags,
4361 false /*exactMatchRequiredForInputFlags*/)) {
4362 profile = curProfile;
4363 break;
4364 }
4365 }
4366 }
4367 if (profile == nullptr) {
4368 ALOGE("%s, there is no compatible profile found", __func__);
4369 return BAD_VALUE;
4370 }
4371
4372 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4373 sp<PreferredMixerAttributesInfo>::make(
4374 uid, portId, profile, flags, *mixerAttributes);
4375 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4376 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4377
4378 // If 1) there is any client from the preferred mixer configuration owner that is currently
4379 // active and matches the strategy and 2) current output is on the preferred device and the
4380 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4381 // configuration.
4382 std::vector<audio_io_handle_t> outputsToReopen;
4383 for (size_t i = 0; i < mOutputs.size(); i++) {
4384 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004385 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4386 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4387 output->mUsePreferredMixerAttributes = true;
4388 } else {
4389 for (const auto &client: output->getActiveClients()) {
4390 if (client->uid() == uid && client->strategy() == strategy) {
4391 client->setIsInvalid();
4392 outputsToReopen.push_back(output->mIoHandle);
4393 }
jiabina84c3d32022-12-02 18:59:55 +00004394 }
4395 }
4396 }
4397 }
4398 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4399 config.sample_rate = mixerAttributes->config.sample_rate;
4400 config.channel_mask = mixerAttributes->config.channel_mask;
4401 config.format = mixerAttributes->config.format;
4402 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004403 sp<SwAudioOutputDescriptor> desc =
4404 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4405 if (desc == nullptr) {
4406 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4407 continue;
4408 }
4409 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004410 }
4411
4412 return NO_ERROR;
4413}
4414
4415sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4416 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4417 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4418 if (it == mPreferredMixerAttrInfos.end()) {
4419 return nullptr;
4420 }
4421 auto mixerAttrInfoIt = it->second.find(strategy);
4422 if (mixerAttrInfoIt == it->second.end()) {
4423 return nullptr;
4424 }
4425 return mixerAttrInfoIt->second;
4426}
4427
4428status_t AudioPolicyManager::getPreferredMixerAttributes(
4429 const audio_attributes_t *attr,
4430 audio_port_handle_t portId,
4431 audio_mixer_attributes_t* mixerAttributes) {
4432 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4433 portId, mEngine->getProductStrategyForAttributes(*attr));
4434 if (info == nullptr) {
4435 return NAME_NOT_FOUND;
4436 }
4437 *mixerAttributes = info->getMixerAttributes();
4438 return NO_ERROR;
4439}
4440
4441status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4442 audio_port_handle_t portId,
4443 uid_t uid) {
4444 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4445 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4446 if (preferredMixerAttrInfo == nullptr) {
4447 return NAME_NOT_FOUND;
4448 }
4449 if (preferredMixerAttrInfo->getUid() != uid) {
4450 ALOGE("%s, requested uid=%d, owned uid=%d",
4451 __func__, uid, preferredMixerAttrInfo->getUid());
4452 return PERMISSION_DENIED;
4453 }
4454 mPreferredMixerAttrInfos[portId].erase(strategy);
4455 if (mPreferredMixerAttrInfos[portId].empty()) {
4456 mPreferredMixerAttrInfos.erase(portId);
4457 }
4458
4459 // Reconfig existing output
4460 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4461 for (size_t i = 0; i < mOutputs.size(); i++) {
4462 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4463 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4464 }
4465 }
4466 for (const auto output : potentialOutputsToReopen) {
4467 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4468 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4469 preferredMixerAttrInfo->getFlags())) {
4470 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4471 }
4472 }
4473 return NO_ERROR;
4474}
4475
Eric Laurent6a94d692014-05-20 11:18:06 -07004476status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4477 audio_port_type_t type,
4478 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004479 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004480 unsigned int *generation)
4481{
jiabin19cdba52020-11-24 11:28:58 -08004482 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4483 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004484 return BAD_VALUE;
4485 }
4486 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004487 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004488 *num_ports = 0;
4489 }
4490
4491 size_t portsWritten = 0;
4492 size_t portsMax = *num_ports;
4493 *num_ports = 0;
4494 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004495 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4496 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004497 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004498 for (const auto& dev : mAvailableOutputDevices) {
4499 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004500 continue;
4501 }
4502 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004503 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004504 }
4505 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004507 }
4508 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004509 for (const auto& dev : mAvailableInputDevices) {
4510 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004511 continue;
4512 }
4513 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004514 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004515 }
4516 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004518 }
4519 }
4520 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4521 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4522 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4523 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4524 }
4525 *num_ports += mInputs.size();
4526 }
4527 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004528 size_t numOutputs = 0;
4529 for (size_t i = 0; i < mOutputs.size(); i++) {
4530 if (!mOutputs[i]->isDuplicated()) {
4531 numOutputs++;
4532 if (portsWritten < portsMax) {
4533 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4534 }
4535 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004536 }
Eric Laurent84c70242014-06-23 08:46:27 -07004537 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004538 }
4539 }
jiabina84c3d32022-12-02 18:59:55 +00004540
Eric Laurent6a94d692014-05-20 11:18:06 -07004541 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004542 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 return NO_ERROR;
4544}
4545
jiabin19cdba52020-11-24 11:28:58 -08004546status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004547{
Eric Laurent99fcae42018-05-17 16:59:18 -07004548 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4549 return BAD_VALUE;
4550 }
4551 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4552 if (dev != 0) {
4553 dev->toAudioPort(port);
4554 return NO_ERROR;
4555 }
4556 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4557 if (dev != 0) {
4558 dev->toAudioPort(port);
4559 return NO_ERROR;
4560 }
4561 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4562 if (out != 0) {
4563 out->toAudioPort(port);
4564 return NO_ERROR;
4565 }
4566 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4567 if (in != 0) {
4568 in->toAudioPort(port);
4569 return NO_ERROR;
4570 }
4571 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004572}
4573
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004574status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4575 audio_patch_handle_t *handle,
4576 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004577{
François Gaffieafd4cea2019-11-18 15:50:22 +01004578 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004579 if (handle == NULL || patch == NULL) {
4580 return BAD_VALUE;
4581 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004582 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004583 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004584 return BAD_VALUE;
4585 }
4586 // only one source per audio patch supported for now
4587 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004588 return INVALID_OPERATION;
4589 }
Eric Laurent874c42872014-08-08 15:13:39 -07004590 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004591 return INVALID_OPERATION;
4592 }
Eric Laurent874c42872014-08-08 15:13:39 -07004593 for (size_t i = 0; i < patch->num_sinks; i++) {
4594 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4595 return INVALID_OPERATION;
4596 }
4597 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004598
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004599 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4600 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4601 if (srcDevice == nullptr || sinkDevice == nullptr) {
4602 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4603 return BAD_VALUE;
4604 }
4605 ALOGV("%s between source %s and sink %s", __func__,
4606 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4607 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4608 // Default attributes, default volume priority, not to infer with non raw audio patches.
4609 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4610 const struct audio_port_config *source = &patch->sources[0];
4611 sp<SourceClientDescriptor> sourceDesc =
4612 new InternalSourceClientDescriptor(
4613 portId, uid, attributes, *source, srcDevice, sinkDevice,
4614 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4615
4616 status_t status =
4617 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4618
4619 if (status != NO_ERROR) {
4620 return INVALID_OPERATION;
4621 }
4622 mAudioSources.add(portId, sourceDesc);
4623 return NO_ERROR;
4624}
4625
4626status_t AudioPolicyManager::connectAudioSourceToSink(
4627 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4628 const struct audio_patch *patch,
4629 audio_patch_handle_t &handle,
4630 uid_t uid, uint32_t delayMs)
4631{
4632 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4633 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4634 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4635 return INVALID_OPERATION;
4636 }
4637 sourceDesc->connect(handle, sinkDevice);
4638 if (isMsdPatch(handle)) {
4639 return NO_ERROR;
4640 }
4641 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4642 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4643 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4644 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4645 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4646 goto FailurePatchAdded;
4647 }
4648 status = swOutput->start();
4649 if (status != NO_ERROR) {
4650 goto FailureSourceAdded;
4651 }
4652 swOutput->addClient(sourceDesc);
4653 status = startSource(swOutput, sourceDesc, &delayMs);
4654 if (status != NO_ERROR) {
4655 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4656 goto FailureSourceActive;
4657 }
4658 if (delayMs != 0) {
4659 usleep(delayMs * 1000);
4660 }
4661 return NO_ERROR;
4662
4663FailureSourceActive:
4664 swOutput->stop();
4665 releaseOutput(sourceDesc->portId());
4666FailureSourceAdded:
4667 sourceDesc->setSwOutput(nullptr);
4668FailurePatchAdded:
4669 releaseAudioPatchInternal(handle);
4670 return INVALID_OPERATION;
4671}
4672
4673status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4674 audio_patch_handle_t *handle,
4675 uid_t uid, uint32_t delayMs,
4676 const sp<SourceClientDescriptor>& sourceDesc)
4677{
4678 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 sp<AudioPatch> patchDesc;
4680 ssize_t index = mAudioPatches.indexOfKey(*handle);
4681
François Gaffieafd4cea2019-11-18 15:50:22 +01004682 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4683 patch->sources[0].role,
4684 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004685#if LOG_NDEBUG == 0
4686 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004687 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4688 patch->sinks[i].role,
4689 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004690 }
4691#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004692
4693 if (index >= 0) {
4694 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004695 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4696 __func__, mUidCached, patchDesc->getUid(), uid);
4697 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 return INVALID_OPERATION;
4699 }
4700 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004701 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004702 }
4703
4704 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004705 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004707 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004708 return BAD_VALUE;
4709 }
Eric Laurent84c70242014-06-23 08:46:27 -07004710 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4711 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004712 if (patchDesc != 0) {
4713 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004714 ALOGV("%s source id differs for patch current id %d new id %d",
4715 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004716 return BAD_VALUE;
4717 }
4718 }
Eric Laurent874c42872014-08-08 15:13:39 -07004719 DeviceVector devices;
4720 for (size_t i = 0; i < patch->num_sinks; i++) {
4721 // Only support mix to devices connection
4722 // TODO add support for mix to mix connection
4723 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004724 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004725 return INVALID_OPERATION;
4726 }
4727 sp<DeviceDescriptor> devDesc =
4728 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4729 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004730 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004731 return BAD_VALUE;
4732 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004733
François Gaffie11d30102018-11-02 16:09:09 +01004734 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004735 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004736 NULL, // updatedSamplingRate
4737 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004738 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004739 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004740 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004741 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004742 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004743 return INVALID_OPERATION;
4744 }
4745 devices.add(devDesc);
4746 }
4747 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004748 return INVALID_OPERATION;
4749 }
Eric Laurent874c42872014-08-08 15:13:39 -07004750
Eric Laurent6a94d692014-05-20 11:18:06 -07004751 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004752 ALOGV("%s setting device %s on output %d",
4753 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004754 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004755 index = mAudioPatches.indexOfKey(*handle);
4756 if (index >= 0) {
4757 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004758 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 }
4760 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004761 patchDesc->setUid(uid);
4762 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004764 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004765 return INVALID_OPERATION;
4766 }
4767 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4768 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4769 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004770 // only one sink supported when connecting an input device to a mix
4771 if (patch->num_sinks > 1) {
4772 return INVALID_OPERATION;
4773 }
François Gaffie53615e22015-03-19 09:24:12 +01004774 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004775 if (inputDesc == NULL) {
4776 return BAD_VALUE;
4777 }
4778 if (patchDesc != 0) {
4779 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4780 return BAD_VALUE;
4781 }
4782 }
François Gaffie11d30102018-11-02 16:09:09 +01004783 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004784 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004785 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004786 return BAD_VALUE;
4787 }
4788
François Gaffie11d30102018-11-02 16:09:09 +01004789 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004790 patch->sinks[0].sample_rate,
4791 NULL, /*updatedSampleRate*/
4792 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004793 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004794 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004795 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004796 // FIXME for the parameter type,
4797 // and the NONE
4798 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004799 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004800 return INVALID_OPERATION;
4801 }
4802 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004803 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004804 device->toString().c_str(), inputDesc->mIoHandle);
4805 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004806 index = mAudioPatches.indexOfKey(*handle);
4807 if (index >= 0) {
4808 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004809 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004810 }
4811 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004812 patchDesc->setUid(uid);
4813 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004815 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004816 return INVALID_OPERATION;
4817 }
4818 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4819 // device to device connection
4820 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004821 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004822 return BAD_VALUE;
4823 }
4824 }
François Gaffie11d30102018-11-02 16:09:09 +01004825 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004826 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004827 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004828 return BAD_VALUE;
4829 }
Eric Laurent874c42872014-08-08 15:13:39 -07004830
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 //update source and sink with our own data as the data passed in the patch may
4832 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004833 PatchBuilder patchBuilder;
4834 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004835
4836 // if first sink is to MSD, establish single MSD patch
4837 if (getMsdAudioOutDevices().contains(
4838 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4839 ALOGV("%s patching to MSD", __FUNCTION__);
4840 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4841 goto installPatch;
4842 }
4843
François Gaffieafd4cea2019-11-18 15:50:22 +01004844 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4845 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004846
Eric Laurent874c42872014-08-08 15:13:39 -07004847 for (size_t i = 0; i < patch->num_sinks; i++) {
4848 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004850 return INVALID_OPERATION;
4851 }
François Gaffie11d30102018-11-02 16:09:09 +01004852 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004853 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004854 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004855 return BAD_VALUE;
4856 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004857 audio_port_config sinkPortConfig = {};
4858 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4859 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004860
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004861 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4862 // volume management purpose (tracking activity)
4863 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4864 // in config XML to reach the sink so that is can be declared as available.
4865 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004866 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004867 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004868 // take care of dynamic routing for SwOutput selection,
4869 audio_attributes_t attributes = sourceDesc->attributes();
4870 audio_stream_type_t stream = sourceDesc->stream();
4871 audio_attributes_t resultAttr;
4872 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4873 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004874 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4875 config.channel_mask =
4876 (audio_channel_mask_get_representation(sourceMask)
4877 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4878 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004879 config.format = sourceDesc->config().format;
4880 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4881 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4882 bool isRequestedDeviceForExclusiveUse = false;
4883 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004884 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004885 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004886 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4887 &stream, sourceDesc->uid(), &config, &flags,
4888 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004889 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004890 if (output == AUDIO_IO_HANDLE_NONE) {
4891 ALOGV("%s no output for device %s",
4892 __FUNCTION__, sinkDevice->toString().c_str());
4893 return INVALID_OPERATION;
4894 }
4895 outputDesc = mOutputs.valueFor(output);
4896 if (outputDesc->isDuplicated()) {
4897 ALOGE("%s output is duplicated", __func__);
4898 return INVALID_OPERATION;
4899 }
François Gaffie7e39df22022-04-26 12:48:49 +02004900 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4901 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004902 } else {
4903 // Same for "raw patches" aka created from createAudioPatch API
4904 SortedVector<audio_io_handle_t> outputs =
4905 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4906 // if the sink device is reachable via an opened output stream, request to
4907 // go via this output stream by adding a second source to the patch
4908 // description
4909 output = selectOutput(outputs);
4910 if (output == AUDIO_IO_HANDLE_NONE) {
4911 ALOGE("%s no output available for internal patch sink", __func__);
4912 return INVALID_OPERATION;
4913 }
4914 outputDesc = mOutputs.valueFor(output);
4915 if (outputDesc->isDuplicated()) {
4916 ALOGV("%s output for device %s is duplicated",
4917 __func__, sinkDevice->toString().c_str());
4918 return INVALID_OPERATION;
4919 }
François Gaffie7e39df22022-04-26 12:48:49 +02004920 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004921 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004922 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004923 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004924 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004925 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004926 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4927 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004928 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4929 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004930 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004931 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004932 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004933 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004934 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004935 return INVALID_OPERATION;
4936 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004937 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004938 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004940 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004941 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004942 srcMixPortConfig.ext.mix.usecase.stream =
4943 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004944 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4945 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004946 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004947 }
Eric Laurent83b88082014-06-20 18:31:16 -07004948 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 }
4950 // TODO: check from routing capabilities in config file and other conflicting patches
4951
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004952installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004953 status_t status = installPatch(
4954 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004955 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004956 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 return INVALID_OPERATION;
4958 }
4959 } else {
4960 return BAD_VALUE;
4961 }
4962 } else {
4963 return BAD_VALUE;
4964 }
4965 return NO_ERROR;
4966}
4967
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004968status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004969{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004970 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 ssize_t index = mAudioPatches.indexOfKey(handle);
4972
4973 if (index < 0) {
4974 return BAD_VALUE;
4975 }
4976 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004977 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4978 __func__, mUidCached, patchDesc->getUid(), uid);
4979 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 return INVALID_OPERATION;
4981 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004982 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4983 for (size_t i = 0; i < mAudioSources.size(); i++) {
4984 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4985 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4986 portId = sourceDesc->portId();
4987 break;
4988 }
4989 }
4990 return portId != AUDIO_PORT_HANDLE_NONE ?
4991 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004992}
Eric Laurent6a94d692014-05-20 11:18:06 -07004993
François Gaffieafd4cea2019-11-18 15:50:22 +01004994status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004995 uint32_t delayMs,
4996 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004997{
4998 ALOGV("%s patch %d", __func__, handle);
4999 if (mAudioPatches.indexOfKey(handle) < 0) {
5000 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5001 return BAD_VALUE;
5002 }
5003 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005005 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005007 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005009 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005010 return BAD_VALUE;
5011 }
5012
François Gaffie11d30102018-11-02 16:09:09 +01005013 setOutputDevices(outputDesc,
5014 getNewOutputDevices(outputDesc, true /*fromCache*/),
5015 true,
5016 0,
5017 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005018 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5019 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005020 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 return BAD_VALUE;
5024 }
5025 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005026 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 true,
5028 NULL);
5029 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005030 status_t status =
5031 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5032 ALOGV("%s patch panel returned %d patchHandle %d",
5033 __func__, status, patchDesc->getAfHandle());
5034 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005036 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005037 // SW or HW Bridge
5038 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5039 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005040 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005041 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5042 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5043 outputDesc = sourceDesc->swOutput().promote();
5044 }
5045 if (outputDesc == nullptr) {
5046 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5047 // releaseOutput has already called closeOutput in case of direct output
5048 return NO_ERROR;
5049 }
François Gaffie7e39df22022-04-26 12:48:49 +02005050 patchHandle = outputDesc->getPatchHandle();
5051 // When a Sw bridge is released, the mixer used by this bridge will release its
5052 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5053 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5054 // updating hal patch handle (prevent leaks).
5055 // While using a HwBridge, force reconsidering device only if not reusing an existing
5056 // output and no more activity on output (will force to close).
5057 bool force = sourceDesc->useSwBridge() ||
5058 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5059 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5060 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5061 // Reconsider device only for cases:
5062 // 1 / Active Output
5063 // 2 / Inactive Output previously hosting HwBridge
5064 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5065 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5066 sourceDesc->canCloseOutput();
5067 setOutputDevices(outputDesc,
5068 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5069 outputDesc->devices(),
5070 force,
5071 0,
5072 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 } else {
5074 return BAD_VALUE;
5075 }
5076 } else {
5077 return BAD_VALUE;
5078 }
5079 return NO_ERROR;
5080}
5081
5082status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5083 struct audio_patch *patches,
5084 unsigned int *generation)
5085{
François Gaffie53615e22015-03-19 09:24:12 +01005086 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 return BAD_VALUE;
5088 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005090 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005091}
5092
Eric Laurente1715a42014-05-20 11:30:42 -07005093status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005094{
Eric Laurente1715a42014-05-20 11:30:42 -07005095 ALOGV("setAudioPortConfig()");
5096
5097 if (config == NULL) {
5098 return BAD_VALUE;
5099 }
5100 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5101 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005102 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5103 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005104 }
5105
Eric Laurenta121f902014-06-03 13:32:54 -07005106 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005107 if (config->type == AUDIO_PORT_TYPE_MIX) {
5108 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005110 if (outputDesc == NULL) {
5111 return BAD_VALUE;
5112 }
Eric Laurent84c70242014-06-23 08:46:27 -07005113 ALOG_ASSERT(!outputDesc->isDuplicated(),
5114 "setAudioPortConfig() called on duplicated output %d",
5115 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005116 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005117 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005118 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005119 if (inputDesc == NULL) {
5120 return BAD_VALUE;
5121 }
Eric Laurenta121f902014-06-03 13:32:54 -07005122 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005123 } else {
5124 return BAD_VALUE;
5125 }
5126 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5127 sp<DeviceDescriptor> deviceDesc;
5128 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5129 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5130 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5131 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5132 } else {
5133 return BAD_VALUE;
5134 }
5135 if (deviceDesc == NULL) {
5136 return BAD_VALUE;
5137 }
Eric Laurenta121f902014-06-03 13:32:54 -07005138 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005139 } else {
5140 return BAD_VALUE;
5141 }
5142
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005143 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005144 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5145 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005146 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005147 audioPortConfig->toAudioPortConfig(&newConfig, config);
5148 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005149 }
Eric Laurenta121f902014-06-03 13:32:54 -07005150 if (status != NO_ERROR) {
5151 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005152 }
Eric Laurente1715a42014-05-20 11:30:42 -07005153
5154 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005155}
5156
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005157void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5158{
Eric Laurentd60560a2015-04-10 11:31:20 -07005159 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005160 clearAudioPatches(uid);
5161 clearSessionRoutes(uid);
5162}
5163
Eric Laurent6a94d692014-05-20 11:18:06 -07005164void AudioPolicyManager::clearAudioPatches(uid_t uid)
5165{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005166 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005167 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005168 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005169 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 }
5171 }
5172}
5173
François Gaffiec005e562018-11-06 15:04:49 +01005174void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005175{
François Gaffiec005e562018-11-06 15:04:49 +01005176 // Take the first attributes following the product strategy as it is used to retrieve the routed
5177 // device. All attributes wihin a strategy follows the same "routing strategy"
5178 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5179 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005180 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005181 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005182 for (size_t j = 0; j < mOutputs.size(); j++) {
5183 if (mOutputs.keyAt(j) == ouptutToSkip) {
5184 continue;
5185 }
5186 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005187 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005188 continue;
5189 }
5190 // If the default device for this strategy is on another output mix,
5191 // invalidate all tracks in this strategy to force re connection.
5192 // Otherwise select new device on the output mix.
5193 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005194 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005195 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005196 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5197 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5198 // If the device is using preferred mixer attributes, the output need to reopen
5199 // with default configuration when the new selected devices are different from
5200 // current routing devices.
5201 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5202 continue;
5203 }
5204 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005205 }
5206 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005207 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005208}
5209
5210void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5211{
5212 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005213 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005214 for (size_t i = 0; i < mOutputs.size(); i++) {
5215 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005216 for (const auto& client : outputDesc->getClientIterable()) {
5217 if (client->hasPreferredDevice() && client->uid() == uid) {
5218 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005219 auto clientStrategy = client->strategy();
5220 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5221 end(affectedStrategies)) {
5222 continue;
5223 }
5224 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005225 }
5226 }
5227 }
5228 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005229 for (const auto& strategy : affectedStrategies) {
5230 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005231 }
5232
5233 // remove input routes associated with this uid
5234 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005235 for (size_t i = 0; i < mInputs.size(); i++) {
5236 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005237 for (const auto& client : inputDesc->getClientIterable()) {
5238 if (client->hasPreferredDevice() && client->uid() == uid) {
5239 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5240 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005241 }
5242 }
5243 }
5244 // reroute inputs if necessary
5245 SortedVector<audio_io_handle_t> inputsToClose;
5246 for (size_t i = 0; i < mInputs.size(); i++) {
5247 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005248 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005249 inputsToClose.add(inputDesc->mIoHandle);
5250 }
5251 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005252 for (const auto& input : inputsToClose) {
5253 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005254 }
5255}
5256
Eric Laurentd60560a2015-04-10 11:31:20 -07005257void AudioPolicyManager::clearAudioSources(uid_t uid)
5258{
5259 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005260 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5261 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005262 stopAudioSource(mAudioSources.keyAt(i));
5263 }
5264 }
5265}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005266
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005267status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5268 audio_io_handle_t *ioHandle,
5269 audio_devices_t *device)
5270{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005271 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5272 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005273 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005274 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005275
François Gaffiedf372692015-03-19 10:43:27 +01005276 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005277}
5278
Eric Laurentd60560a2015-04-10 11:31:20 -07005279status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005280 const audio_attributes_t *attributes,
5281 audio_port_handle_t *portId,
5282 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005283{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005284 ALOGV("%s", __FUNCTION__);
5285 *portId = AUDIO_PORT_HANDLE_NONE;
5286
5287 if (source == NULL || attributes == NULL || portId == NULL) {
5288 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5289 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005290 return BAD_VALUE;
5291 }
5292
Eric Laurentd60560a2015-04-10 11:31:20 -07005293 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5294 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005295 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5296 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005297 return INVALID_OPERATION;
5298 }
5299
François Gaffie11d30102018-11-02 16:09:09 +01005300 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005301 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005302 String8(source->ext.device.address),
5303 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005304 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005305 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005306 return BAD_VALUE;
5307 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005308
jiabin4ef93452019-09-10 14:29:54 -07005309 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005310
François Gaffieaaac0fd2018-11-22 17:56:39 +01005311 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005312 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005313 mEngine->getStreamTypeForAttributes(*attributes),
5314 mEngine->getProductStrategyForAttributes(*attributes),
5315 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005316
5317 status_t status = connectAudioSource(sourceDesc);
5318 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005319 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005320 }
5321 return status;
5322}
5323
Francois Gaffie601801d2021-06-22 13:27:39 +02005324sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5325 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5326{
5327 ALOGV("%s", __FUNCTION__);
5328 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5329
5330 status_t status = startAudioSource(source, attributes, &portId, uid);
5331 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5332 return mAudioSources.valueFor(portId);
5333}
5334
5335
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005336status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005337{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005338 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005339
5340 // make sure we only have one patch per source.
5341 disconnectAudioSource(sourceDesc);
5342
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005343 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005344 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5345 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5346 sourceDesc->srcDevice()->type(),
5347 String8(sourceDesc->srcDevice()->address().c_str()),
5348 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005349 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005350 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005351 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005352 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005353 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5354 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5355 return INVALID_OPERATION;
5356 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005357 PatchBuilder patchBuilder;
5358 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5359 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005360
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005361 return connectAudioSourceToSink(
5362 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005363}
5364
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005365status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005366{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005367 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5368 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005369 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005370 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005371 return BAD_VALUE;
5372 }
5373 status_t status = disconnectAudioSource(sourceDesc);
5374
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005375 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005376 return status;
5377}
5378
Andy Hung2ddee192015-12-18 17:34:44 -08005379status_t AudioPolicyManager::setMasterMono(bool mono)
5380{
5381 if (mMasterMono == mono) {
5382 return NO_ERROR;
5383 }
5384 mMasterMono = mono;
5385 // if enabling mono we close all offloaded devices, which will invalidate the
5386 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5387 // for recreating the new AudioTrack as non-offloaded PCM.
5388 //
5389 // If disabling mono, we leave all tracks as is: we don't know which clients
5390 // and tracks are able to be recreated as offloaded. The next "song" should
5391 // play back offloaded.
5392 if (mMasterMono) {
5393 Vector<audio_io_handle_t> offloaded;
5394 for (size_t i = 0; i < mOutputs.size(); ++i) {
5395 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5396 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5397 offloaded.push(desc->mIoHandle);
5398 }
5399 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005400 for (const auto& handle : offloaded) {
5401 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005402 }
5403 }
5404 // update master mono for all remaining outputs
5405 for (size_t i = 0; i < mOutputs.size(); ++i) {
5406 updateMono(mOutputs.keyAt(i));
5407 }
5408 return NO_ERROR;
5409}
5410
5411status_t AudioPolicyManager::getMasterMono(bool *mono)
5412{
5413 *mono = mMasterMono;
5414 return NO_ERROR;
5415}
5416
Eric Laurentac9cef52017-06-09 15:46:26 -07005417float AudioPolicyManager::getStreamVolumeDB(
5418 audio_stream_type_t stream, int index, audio_devices_t device)
5419{
jiabin9a3361e2019-10-01 09:38:30 -07005420 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005421}
5422
jiabin81772902018-04-02 17:52:27 -07005423status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5424 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005425 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005426{
Kriti Dang6537def2021-03-02 13:46:59 +01005427 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5428 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005429 return BAD_VALUE;
5430 }
Kriti Dang6537def2021-03-02 13:46:59 +01005431 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5432 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005433
5434 size_t formatsWritten = 0;
5435 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005436
Kriti Dang6537def2021-03-02 13:46:59 +01005437 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005438 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5439 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005440 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005441 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005442 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005443 bool formatEnabled = true;
5444 switch (forceUse) {
5445 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005446 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005447 break;
5448 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5449 formatEnabled = false;
5450 break;
5451 default: // AUTO or ALWAYS => true
5452 break;
jiabin81772902018-04-02 17:52:27 -07005453 }
5454 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5455 }
jiabin81772902018-04-02 17:52:27 -07005456 }
5457 return NO_ERROR;
5458}
5459
Kriti Dang6537def2021-03-02 13:46:59 +01005460status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5461 audio_format_t *surroundFormats) {
5462 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5463 return BAD_VALUE;
5464 }
5465 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5466 __func__, *numSurroundFormats, surroundFormats);
5467
5468 size_t formatsWritten = 0;
5469 size_t formatsMax = *numSurroundFormats;
5470 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5471
5472 // Return formats from all device profiles that have already been resolved by
5473 // checkOutputsForDevice().
5474 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5475 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5476 audio_devices_t deviceType = device->type();
5477 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5478 // returns formats reported by HDMI devices.
5479 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5480 continue;
5481 }
5482 // Formats reported by sink devices
5483 std::unordered_set<audio_format_t> formatset;
5484 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5485 formatset.insert(it->second.begin(), it->second.end());
5486 }
5487
5488 // Formats hard-coded in the in policy configuration file (if any).
5489 FormatVector encodedFormats = device->encodedFormats();
5490 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5491 // Filter the formats which are supported by the vendor hardware.
5492 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5493 if (mConfig.getSurroundFormats().count(*it) != 0) {
5494 formats.insert(*it);
5495 } else {
5496 for (const auto& pair : mConfig.getSurroundFormats()) {
5497 if (pair.second.count(*it) != 0) {
5498 formats.insert(pair.first);
5499 break;
5500 }
5501 }
5502 }
5503 }
5504 }
5505 *numSurroundFormats = formats.size();
5506 for (const auto& format: formats) {
5507 if (formatsWritten < formatsMax) {
5508 surroundFormats[formatsWritten++] = format;
5509 }
5510 }
5511 return NO_ERROR;
5512}
5513
jiabin81772902018-04-02 17:52:27 -07005514status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5515{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005516 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005517 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5518 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005519 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005520 return BAD_VALUE;
5521 }
5522
Mikhail Naganov100f0122018-11-29 11:22:16 -08005523 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5524 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005525 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005526 return INVALID_OPERATION;
5527 }
5528
Mikhail Naganov100f0122018-11-29 11:22:16 -08005529 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005530 return NO_ERROR;
5531 }
5532
Mikhail Naganov100f0122018-11-29 11:22:16 -08005533 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005534 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005535 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005536 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005537 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005538 }
5539 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005540 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005541 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005542 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005543 }
5544 }
5545
5546 sp<SwAudioOutputDescriptor> outputDesc;
5547 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005548 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5549 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005550 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5551 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005552 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005553 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005554 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5555 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5556 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005557 name.c_str(),
5558 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005559 if (status != NO_ERROR) {
5560 continue;
5561 }
5562 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5563 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5564 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005565 name.c_str(),
5566 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005567 profileUpdated |= (status == NO_ERROR);
5568 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005569 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005570 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005571 AUDIO_DEVICE_IN_HDMI);
5572 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5573 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005574 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005575 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005576 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5577 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5578 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005579 name.c_str(),
5580 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005581 if (status != NO_ERROR) {
5582 continue;
5583 }
5584 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5585 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5586 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005587 name.c_str(),
5588 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005589 profileUpdated |= (status == NO_ERROR);
5590 }
5591
jiabin81772902018-04-02 17:52:27 -07005592 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005593 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005594 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005595 }
5596
5597 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5598}
5599
Eric Laurent5ada82e2019-08-29 17:53:54 -07005600void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005601{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005602 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005603 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005604 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005605 }
5606}
5607
jiabin6012f912018-11-02 17:06:30 -07005608bool AudioPolicyManager::isHapticPlaybackSupported()
5609{
5610 for (const auto& hwModule : mHwModules) {
5611 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5612 for (const auto &outProfile : outputProfiles) {
5613 struct audio_port audioPort;
5614 outProfile->toAudioPort(&audioPort);
5615 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5616 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5617 return true;
5618 }
5619 }
5620 }
5621 }
5622 return false;
5623}
5624
Carter Hsu325a8eb2022-01-19 19:56:51 +08005625bool AudioPolicyManager::isUltrasoundSupported()
5626{
5627 bool hasUltrasoundOutput = false;
5628 bool hasUltrasoundInput = false;
5629 for (const auto& hwModule : mHwModules) {
5630 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5631 if (!hasUltrasoundOutput) {
5632 for (const auto &outProfile : outputProfiles) {
5633 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5634 hasUltrasoundOutput = true;
5635 break;
5636 }
5637 }
5638 }
5639
5640 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5641 if (!hasUltrasoundInput) {
5642 for (const auto &inputProfile : inputProfiles) {
5643 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5644 hasUltrasoundInput = true;
5645 break;
5646 }
5647 }
5648 }
5649
5650 if (hasUltrasoundOutput && hasUltrasoundInput)
5651 return true;
5652 }
5653 return false;
5654}
5655
Eric Laurent8340e672019-11-06 11:01:08 -08005656bool AudioPolicyManager::isCallScreenModeSupported()
5657{
5658 return getConfig().isCallScreenModeSupported();
5659}
5660
5661
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005662status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005663{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005664 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005665 if (!sourceDesc->isConnected()) {
5666 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5667 return NO_ERROR;
5668 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005669 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5670 if (swOutput != 0) {
5671 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005672 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005673 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005674 }
jiabinbce0c1d2020-10-05 11:20:18 -07005675 if (releaseOutput(sourceDesc->portId())) {
5676 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5677 // no need to release audio patch here but just return NO_ERROR.
5678 return NO_ERROR;
5679 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005680 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005681 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005682 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005683 // close Hwoutput and remove from mHwOutputs
5684 } else {
5685 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5686 }
5687 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005688 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005689 sourceDesc->disconnect();
5690 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005691}
5692
François Gaffiec005e562018-11-06 15:04:49 +01005693sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5694 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005695{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005696 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005697 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005698 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005699 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005700 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5701 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005702 source = sourceDesc;
5703 break;
5704 }
5705 }
5706 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005707}
5708
Eric Laurentb4f42a92022-01-17 17:37:31 +01005709bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005710 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005711 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005712{
5713 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5714 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005715 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005716 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005717 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5718 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5719 return false;
5720 }
5721 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5722 return false;
5723 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005724 }
5725
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005726 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005727 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005728 if (profile == nullptr) {
5729 return false;
5730 }
5731
5732 // The caller can have the audio config criteria ignored by either passing a null ptr or
5733 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005734 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005735 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005736
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005737 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005738 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005739 return false;
5740 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005741 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005742 return true;
5743}
5744
5745void AudioPolicyManager::checkVirtualizerClientRoutes() {
5746 std::set<audio_stream_type_t> streamsToInvalidate;
5747 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005748 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5749 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005750 audio_attributes_t attr = client->attributes();
5751 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5752 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5753 audio_config_base_t clientConfig = client->config();
5754 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005755 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005756 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005757 streamsToInvalidate.insert(client->stream());
5758 }
5759 }
5760 }
5761
jiabinc44b3462022-12-08 12:52:31 -08005762 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005763}
5764
Eric Laurente191d1b2022-04-15 11:59:25 +02005765
5766bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5767 const sp<SwAudioOutputDescriptor>& outputDesc) {
5768 if (outputDesc->isDuplicated()) {
5769 return false;
5770 }
5771 DeviceVector devices = outputDesc->supportedDevices();
5772 for (size_t i = 0; i < mOutputs.size(); i++) {
5773 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5774 if (desc == outputDesc || desc->isDuplicated()) {
5775 continue;
5776 }
5777 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5778 if (!sharedDevices.isEmpty()
5779 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5780 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5781 return false;
5782 }
5783 }
5784 return true;
5785}
5786
5787
Eric Laurentfa0f6742021-08-17 18:39:44 +02005788status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005789 const audio_attributes_t *attr,
5790 audio_io_handle_t *output) {
5791 *output = AUDIO_IO_HANDLE_NONE;
5792
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005793 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5794 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5795 audio_config_t *configPtr = nullptr;
5796 audio_config_t config;
5797 if (mixerConfig != nullptr) {
5798 config = audio_config_initializer(mixerConfig);
5799 configPtr = &config;
5800 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005801 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005802 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005803 return BAD_VALUE;
5804 }
5805
5806 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005807 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005808 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005809 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005810 return BAD_VALUE;
5811 }
5812
Eric Laurente191d1b2022-04-15 11:59:25 +02005813 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005814 for (size_t i = 0; i < mOutputs.size(); i++) {
5815 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005816 if (!desc->isDuplicated()
5817 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5818 spatializerOutputs.push_back(desc);
5819 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005820 }
5821 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005822 mSpatializerOutput.clear();
5823 bool outputsChanged = false;
5824 for (const auto& desc : spatializerOutputs) {
5825 if (desc->mProfile == profile
5826 && (configPtr == nullptr
5827 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5828 mSpatializerOutput = desc;
5829 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5830 } else {
5831 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5832 " and devices %s", __func__, desc->mIoHandle,
5833 configPtr != nullptr ? configPtr->channel_mask : 0,
5834 devices.toString().c_str());
5835 closeOutput(desc->mIoHandle);
5836 outputsChanged = true;
5837 }
Eric Laurent39095982021-08-24 18:29:27 +02005838 }
5839
Eric Laurente191d1b2022-04-15 11:59:25 +02005840 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005841 sp<SwAudioOutputDescriptor> desc =
5842 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005843 if (desc != nullptr) {
5844 mSpatializerOutput = desc;
5845 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005846 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005847 }
5848
5849 checkVirtualizerClientRoutes();
5850
Eric Laurente191d1b2022-04-15 11:59:25 +02005851 if (outputsChanged) {
5852 mPreviousOutputs = mOutputs;
5853 mpClientInterface->onAudioPortListUpdate();
5854 }
5855
5856 if (mSpatializerOutput == nullptr) {
5857 ALOGV("%s could not open spatializer output with requested config", __func__);
5858 return BAD_VALUE;
5859 }
Eric Laurent39095982021-08-24 18:29:27 +02005860 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005861 ALOGV("%s returning new spatializer output %d", __func__, *output);
5862 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005863}
5864
Eric Laurentfa0f6742021-08-17 18:39:44 +02005865status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5866 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005867 return INVALID_OPERATION;
5868 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005869 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005870 return BAD_VALUE;
5871 }
Eric Laurent39095982021-08-24 18:29:27 +02005872
Eric Laurente191d1b2022-04-15 11:59:25 +02005873 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5874 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5875 closeOutput(mSpatializerOutput->mIoHandle);
5876 //from now on mSpatializerOutput is null
5877 checkVirtualizerClientRoutes();
5878 }
Eric Laurent39095982021-08-24 18:29:27 +02005879
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005880 return NO_ERROR;
5881}
5882
Eric Laurente552edb2014-03-10 17:42:56 -07005883// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005884// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005885// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005886uint32_t AudioPolicyManager::nextAudioPortGeneration()
5887{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005888 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005889}
5890
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005891static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005892 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5893 !audioPolicyXmlConfigFile.empty()) {
5894 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5895 if (ret == NO_ERROR) {
5896 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005897 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005898 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005899 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005900 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005901}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005902
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005903AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5904 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005905 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005906 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005907 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005908 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005909 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005910 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005911 mAudioPortGeneration(1),
5912 mBeaconMuteRefCount(0),
5913 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005914 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005915 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005916 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005917 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005918{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005919}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005920
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005921AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5922 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5923{
5924 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005925}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005926
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005927void AudioPolicyManager::loadConfig() {
5928 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005929 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005930 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005931 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005932}
5933
5934status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005935 {
5936 auto engLib = EngineLibrary::load(
5937 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5938 if (!engLib) {
5939 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5940 return NO_INIT;
5941 }
5942 mEngine = engLib->createEngine();
5943 if (mEngine == nullptr) {
5944 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5945 return NO_INIT;
5946 }
François Gaffie2110e042015-03-24 08:41:51 +01005947 }
5948 mEngine->setObserver(this);
5949 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005950 if (status != NO_ERROR) {
5951 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5952 return status;
5953 }
François Gaffie2110e042015-03-24 08:41:51 +01005954
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005955 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005956 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5957 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5958
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005959 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005960 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005961 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005962
Eric Laurent3a4311c2014-03-17 12:00:47 -07005963 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005964 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5965 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5966 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005967 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005968 }
jiabin9ff780e2018-03-19 18:19:52 -07005969 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005970 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005971 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005972 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005973 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005974 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005975 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005976 }
5977 }
5978 }
Eric Laurente552edb2014-03-10 17:42:56 -07005979
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005980 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005981
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005982 // Silence ALOGV statements
5983 property_set("log.tag." LOG_TAG, "D");
5984
Eric Laurente552edb2014-03-10 17:42:56 -07005985 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005986 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005987}
5988
Eric Laurente0720872014-03-11 09:30:41 -07005989AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005990{
Eric Laurente552edb2014-03-10 17:42:56 -07005991 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005992 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005993 }
5994 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005995 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005996 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005997 mAvailableOutputDevices.clear();
5998 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005999 mOutputs.clear();
6000 mInputs.clear();
6001 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08006002 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006003 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006004}
6005
Eric Laurente0720872014-03-11 09:30:41 -07006006status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006007{
Eric Laurent87ffa392015-05-22 10:32:38 -07006008 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006009}
6010
Eric Laurente552edb2014-03-10 17:42:56 -07006011// ---
6012
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006013void AudioPolicyManager::onNewAudioModulesAvailable()
6014{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006015 DeviceVector newDevices;
6016 onNewAudioModulesAvailableInt(&newDevices);
6017 if (!newDevices.empty()) {
6018 nextAudioPortGeneration();
6019 mpClientInterface->onAudioPortListUpdate();
6020 }
6021}
6022
6023void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6024{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006025 for (const auto& hwModule : mHwModulesAll) {
6026 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6027 continue;
6028 }
6029 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6030 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6031 ALOGW("could not open HW module %s", hwModule->getName());
6032 continue;
6033 }
6034 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006035 // open all output streams needed to access attached devices.
6036 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006037 // This also validates mAvailableOutputDevices list
6038 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6039 if (!outProfile->canOpenNewIo()) {
6040 ALOGE("Invalid Output profile max open count %u for profile %s",
6041 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6042 continue;
6043 }
6044 if (!outProfile->hasSupportedDevices()) {
6045 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6046 continue;
6047 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006048 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6049 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006050 mTtsOutputAvailable = true;
6051 }
6052
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006053 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6054 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6055 sp<DeviceDescriptor> supportedDevice = 0;
6056 if (supportedDevices.contains(mDefaultOutputDevice)) {
6057 supportedDevice = mDefaultOutputDevice;
6058 } else {
6059 // choose first device present in profile's SupportedDevices also part of
6060 // mAvailableOutputDevices.
6061 if (availProfileDevices.isEmpty()) {
6062 continue;
6063 }
6064 supportedDevice = availProfileDevices.itemAt(0);
6065 }
6066 if (!mOutputDevicesAll.contains(supportedDevice)) {
6067 continue;
6068 }
6069 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6070 mpClientInterface);
6071 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006072 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6073 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006074 AUDIO_STREAM_DEFAULT,
6075 AUDIO_OUTPUT_FLAG_NONE, &output);
6076 if (status != NO_ERROR) {
6077 ALOGW("Cannot open output stream for devices %s on hw module %s",
6078 supportedDevice->toString().c_str(), hwModule->getName());
6079 continue;
6080 }
6081 for (const auto &device : availProfileDevices) {
6082 // give a valid ID to an attached device once confirmed it is reachable
6083 if (!device->isAttached()) {
6084 device->attach(hwModule);
6085 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006086 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006087 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006088 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6089 }
6090 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006091 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006092 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6093 mPrimaryOutput = outputDesc;
6094 }
Eric Laurent39095982021-08-24 18:29:27 +02006095 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006096 outputDesc->close();
6097 } else {
6098 addOutput(output, outputDesc);
6099 setOutputDevices(outputDesc,
6100 DeviceVector(supportedDevice),
6101 true,
6102 0,
6103 NULL);
6104 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006105 }
6106 // open input streams needed to access attached devices to validate
6107 // mAvailableInputDevices list
6108 for (const auto& inProfile : hwModule->getInputProfiles()) {
6109 if (!inProfile->canOpenNewIo()) {
6110 ALOGE("Invalid Input profile max open count %u for profile %s",
6111 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6112 continue;
6113 }
6114 if (!inProfile->hasSupportedDevices()) {
6115 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6116 continue;
6117 }
6118 // chose first device present in profile's SupportedDevices also part of
6119 // available input devices
6120 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6121 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6122 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006123 ALOGV("%s: Input device list is empty! for profile %s",
6124 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006125 continue;
6126 }
6127 sp<AudioInputDescriptor> inputDesc =
6128 new AudioInputDescriptor(inProfile, mpClientInterface);
6129
6130 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6131 status_t status = inputDesc->open(nullptr,
6132 availProfileDevices.itemAt(0),
6133 AUDIO_SOURCE_MIC,
6134 AUDIO_INPUT_FLAG_NONE,
6135 &input);
6136 if (status != NO_ERROR) {
6137 ALOGW("Cannot open input stream for device %s on hw module %s",
6138 availProfileDevices.toString().c_str(),
6139 hwModule->getName());
6140 continue;
6141 }
6142 for (const auto &device : availProfileDevices) {
6143 // give a valid ID to an attached device once confirmed it is reachable
6144 if (!device->isAttached()) {
6145 device->attach(hwModule);
6146 device->importAudioPortAndPickAudioProfile(inProfile, true);
6147 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006148 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006149 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6150 }
6151 }
6152 inputDesc->close();
6153 }
6154 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006155
6156 // Check if spatializer outputs can be closed until used.
6157 // mOutputs vector never contains duplicated outputs at this point.
6158 std::vector<audio_io_handle_t> outputsClosed;
6159 for (size_t i = 0; i < mOutputs.size(); i++) {
6160 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6161 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6162 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6163 outputsClosed.push_back(desc->mIoHandle);
6164 desc->close();
6165 }
6166 }
6167 for (auto output : outputsClosed) {
6168 removeOutput(output);
6169 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006170}
6171
Eric Laurent98e38192018-02-15 18:31:53 -08006172void AudioPolicyManager::addOutput(audio_io_handle_t output,
6173 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006174{
Eric Laurent1c333e22014-05-20 10:48:17 -07006175 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006176 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006177 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006178 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006179 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006180}
6181
François Gaffie53615e22015-03-19 09:24:12 +01006182void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6183{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006184 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6185 ALOGV("%s: removing primary output", __func__);
6186 mPrimaryOutput = nullptr;
6187 }
François Gaffie53615e22015-03-19 09:24:12 +01006188 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006189 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006190}
6191
Eric Laurent98e38192018-02-15 18:31:53 -08006192void AudioPolicyManager::addInput(audio_io_handle_t input,
6193 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006194{
Eric Laurent1c333e22014-05-20 10:48:17 -07006195 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006196 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006197}
Eric Laurente552edb2014-03-10 17:42:56 -07006198
François Gaffie11d30102018-11-02 16:09:09 +01006199status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006200 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006201 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006202{
François Gaffie11d30102018-11-02 16:09:09 +01006203 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006204 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006205 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006206
François Gaffie11d30102018-11-02 16:09:09 +01006207 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006208 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006209 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006210 }
Eric Laurente552edb2014-03-10 17:42:56 -07006211
Eric Laurent3b73df72014-03-11 09:06:29 -07006212 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006213 // first call getAudioPort to get the supported attributes from the HAL
6214 struct audio_port_v7 port = {};
6215 device->toAudioPort(&port);
6216 status_t status = mpClientInterface->getAudioPort(&port);
6217 if (status == NO_ERROR) {
6218 device->importAudioPort(port);
6219 }
6220
6221 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006222 for (size_t i = 0; i < mOutputs.size(); i++) {
6223 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006224 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006225 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006226 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6227 mOutputs.keyAt(i), device->toString().c_str());
6228 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006229 }
6230 }
6231 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006232 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006233 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006234 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6235 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006236 if (profile->supportsDevice(device)) {
6237 profiles.add(profile);
6238 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6239 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006240 }
6241 }
6242 }
6243
Eric Laurent7b279bb2015-12-14 10:18:23 -08006244 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006245
Eric Laurente552edb2014-03-10 17:42:56 -07006246 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006247 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006248 return BAD_VALUE;
6249 }
6250
6251 // open outputs for matching profiles if needed. Direct outputs are also opened to
6252 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6253 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006254 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006255
6256 // nothing to do if one output is already opened for this profile
6257 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006258 for (j = 0; j < outputs.size(); j++) {
6259 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006260 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006261 // matching profile: save the sample rates, format and channel masks supported
6262 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006263 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006264 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006265 }
Eric Laurente552edb2014-03-10 17:42:56 -07006266 break;
6267 }
6268 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006269 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006270 continue;
6271 }
6272
Eric Laurent3974e3b2017-12-07 17:58:43 -08006273 if (!profile->canOpenNewIo()) {
6274 ALOGW("Max Output number %u already opened for this profile %s",
6275 profile->maxOpenCount, profile->getTagName().c_str());
6276 continue;
6277 }
6278
Eric Laurent83efe1c2017-07-09 16:51:08 -07006279 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006280 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006281 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6282 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006283 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006284 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006285 profiles.removeAt(profile_index);
6286 profile_index--;
6287 } else {
6288 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006289 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006290 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006291 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6292 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006293 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006294 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006295
François Gaffie11d30102018-11-02 16:09:09 +01006296 if (device_distinguishes_on_address(deviceType)) {
6297 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6298 device->toString().c_str());
6299 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6300 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006301 }
Eric Laurente552edb2014-03-10 17:42:56 -07006302 ALOGV("checkOutputsForDevice(): adding output %d", output);
6303 }
6304 }
6305
6306 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006307 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006308 return BAD_VALUE;
6309 }
Eric Laurentd4692962014-05-05 18:13:44 -07006310 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006311 // check if one opened output is not needed any more after disconnecting one device
6312 for (size_t i = 0; i < mOutputs.size(); i++) {
6313 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006314 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006315 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006316 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006317 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006318 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006319 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006320 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6321 mOutputs.keyAt(i));
6322 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006323 }
Eric Laurente552edb2014-03-10 17:42:56 -07006324 }
6325 }
Eric Laurentd4692962014-05-05 18:13:44 -07006326 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006327 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006328 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6329 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006330 if (!profile->supportsDevice(device)) {
6331 continue;
6332 }
6333 ALOGV("checkOutputsForDevice(): "
6334 "clearing direct output profile %zu on module %s",
6335 j, hwModule->getName());
6336 profile->clearAudioProfiles();
6337 if (!profile->hasDynamicAudioProfile()) {
6338 continue;
6339 }
6340 // When a device is disconnected, if there is an IOProfile that contains dynamic
6341 // profiles and supports the disconnected device, call getAudioPort to repopulate
6342 // the capabilities of the devices that is supported by the IOProfile.
6343 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6344 if (supportedDevice == device ||
6345 !mAvailableOutputDevices.contains(supportedDevice)) {
6346 continue;
6347 }
6348 struct audio_port_v7 port;
6349 supportedDevice->toAudioPort(&port);
6350 status_t status = mpClientInterface->getAudioPort(&port);
6351 if (status == NO_ERROR) {
6352 supportedDevice->importAudioPort(port);
6353 }
Eric Laurente552edb2014-03-10 17:42:56 -07006354 }
6355 }
6356 }
6357 }
6358 return NO_ERROR;
6359}
6360
François Gaffie11d30102018-11-02 16:09:09 +01006361status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006362 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006363{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006364 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006365
François Gaffie11d30102018-11-02 16:09:09 +01006366 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006367 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006368 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006369 }
6370
Eric Laurentd4692962014-05-05 18:13:44 -07006371 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006372 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006373 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006374 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006375 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006376 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006377 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006378 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006379
François Gaffie11d30102018-11-02 16:09:09 +01006380 if (profile->supportsDevice(device)) {
6381 profiles.add(profile);
6382 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6383 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006384 }
6385 }
6386 }
6387
Eric Laurent0dd51852019-04-19 18:18:58 -07006388 if (profiles.isEmpty()) {
6389 ALOGW("%s: No input profile available for device %s",
6390 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006391 return BAD_VALUE;
6392 }
6393
6394 // open inputs for matching profiles if needed. Direct inputs are also opened to
6395 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6396 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6397
Eric Laurent1c333e22014-05-20 10:48:17 -07006398 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006399
Eric Laurentd4692962014-05-05 18:13:44 -07006400 // nothing to do if one input is already opened for this profile
6401 size_t input_index;
6402 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6403 desc = mInputs.valueAt(input_index);
6404 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006405 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006406 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006407 }
Eric Laurentd4692962014-05-05 18:13:44 -07006408 break;
6409 }
6410 }
6411 if (input_index != mInputs.size()) {
6412 continue;
6413 }
6414
Eric Laurent3974e3b2017-12-07 17:58:43 -08006415 if (!profile->canOpenNewIo()) {
6416 ALOGW("Max Input number %u already opened for this profile %s",
6417 profile->maxOpenCount, profile->getTagName().c_str());
6418 continue;
6419 }
6420
Eric Laurentfe231122017-11-17 17:48:06 -08006421 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006422 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006423 status_t status = desc->open(nullptr,
6424 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006425 AUDIO_SOURCE_MIC,
6426 AUDIO_INPUT_FLAG_NONE,
6427 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006428
Eric Laurentcf2c0212014-07-25 16:20:43 -07006429 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006430 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006431 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006432 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006433 mpClientInterface->setParameters(input, String8(param));
6434 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006435 }
François Gaffie11d30102018-11-02 16:09:09 +01006436 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006437 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006438 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006439 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006440 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006441 }
6442
Eric Laurent0dd51852019-04-19 18:18:58 -07006443 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006444 addInput(input, desc);
6445 }
6446 } // endif input != 0
6447
Eric Laurentcf2c0212014-07-25 16:20:43 -07006448 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006449 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006450 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006451 profiles.removeAt(profile_index);
6452 profile_index--;
6453 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006454 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006455 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006456 }
Eric Laurentd4692962014-05-05 18:13:44 -07006457 ALOGV("checkInputsForDevice(): adding input %d", input);
6458 }
6459 } // end scan profiles
6460
6461 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006462 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006463 return BAD_VALUE;
6464 }
6465 } else {
6466 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006467 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006468 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006469 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006470 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006471 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006472 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006473 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006474 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6475 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006476 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006477 }
6478 }
6479 }
6480 } // end disconnect
6481
6482 return NO_ERROR;
6483}
6484
6485
Eric Laurente0720872014-03-11 09:30:41 -07006486void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006487{
6488 ALOGV("closeOutput(%d)", output);
6489
François Gaffie1c878552018-11-22 16:53:21 +01006490 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6491 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006492 ALOGW("closeOutput() unknown output %d", output);
6493 return;
6494 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006495 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006496 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006497
Eric Laurente552edb2014-03-10 17:42:56 -07006498 // look for duplicated outputs connected to the output being removed.
6499 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006500 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6501 if (dupOutput->isDuplicated() &&
6502 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6503 sp<SwAudioOutputDescriptor> remainingOutput =
6504 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006505 // As all active tracks on duplicated output will be deleted,
6506 // and as they were also referenced on the other output, the reference
6507 // count for their stream type must be adjusted accordingly on
6508 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006509 const bool wasActive = remainingOutput->isActive();
6510 // Note: no-op on the closing output where all clients has already been set inactive
6511 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006512 // stop() will be a no op if the output is still active but is needed in case all
6513 // active streams refcounts where cleared above
6514 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006515 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006516 }
Eric Laurente552edb2014-03-10 17:42:56 -07006517 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6518 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6519
6520 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006521 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006522 }
6523 }
6524
Eric Laurent05b90f82014-08-27 15:32:29 -07006525 nextAudioPortGeneration();
6526
François Gaffie1c878552018-11-22 16:53:21 +01006527 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006528 if (index >= 0) {
6529 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006530 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6531 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006532 mAudioPatches.removeItemsAt(index);
6533 mpClientInterface->onAudioPatchListUpdate();
6534 }
6535
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006536 if (closingOutputWasActive) {
6537 closingOutput->stop();
6538 }
François Gaffie1c878552018-11-22 16:53:21 +01006539 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006540
François Gaffie53615e22015-03-19 09:24:12 +01006541 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006542 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006543 if (closingOutput == mSpatializerOutput) {
6544 mSpatializerOutput.clear();
6545 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006546
6547 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6548 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006549 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006550 bool directOutputOpen = false;
6551 for (size_t i = 0; i < mOutputs.size(); i++) {
6552 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6553 directOutputOpen = true;
6554 break;
6555 }
6556 }
6557 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006558 ALOGV("no direct outputs open, reset MSD patches");
6559 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6560 // how output devices for patching are resolved. Avoid by caching and reusing the
6561 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6562 // devices to patch to. This may be complicated by the fact that devices may become
6563 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006564 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006565 }
6566 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006567}
6568
6569void AudioPolicyManager::closeInput(audio_io_handle_t input)
6570{
6571 ALOGV("closeInput(%d)", input);
6572
6573 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6574 if (inputDesc == NULL) {
6575 ALOGW("closeInput() unknown input %d", input);
6576 return;
6577 }
6578
Eric Laurent6a94d692014-05-20 11:18:06 -07006579 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006580
François Gaffie11d30102018-11-02 16:09:09 +01006581 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006582 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006583 if (index >= 0) {
6584 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006585 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6586 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006587 mAudioPatches.removeItemsAt(index);
6588 mpClientInterface->onAudioPatchListUpdate();
6589 }
6590
Eric Laurentfe231122017-11-17 17:48:06 -08006591 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006592 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006593
François Gaffie11d30102018-11-02 16:09:09 +01006594 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6595 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006596 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006597 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006598 }
Eric Laurente552edb2014-03-10 17:42:56 -07006599}
6600
François Gaffie11d30102018-11-02 16:09:09 +01006601SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6602 const DeviceVector &devices,
6603 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006604{
6605 SortedVector<audio_io_handle_t> outputs;
6606
François Gaffie11d30102018-11-02 16:09:09 +01006607 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006608 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006609 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006610 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006611 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006612 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006613 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006614 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006615 outputs.add(openOutputs.keyAt(i));
6616 }
6617 }
6618 return outputs;
6619}
6620
Mikhail Naganov37977152018-07-11 15:54:44 -07006621void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6622{
6623 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6624 // output is suspended before any tracks are moved to it
6625 checkA2dpSuspend();
6626 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006627 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006628 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006629 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006630 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006631 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6632 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6633 // configuration changes will ultimately be rerouted correctly. We can still avoid
6634 // unnecessary rerouting by caching and reusing the arguments to
6635 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6636 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006637 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006638 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006639 // an event that changed routing likely occurred, inform upper layers
6640 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006641}
6642
François Gaffiec005e562018-11-06 15:04:49 +01006643bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6644 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006645{
François Gaffiec005e562018-11-06 15:04:49 +01006646 return mEngine->getProductStrategyForAttributes(lAttr) ==
6647 mEngine->getProductStrategyForAttributes(rAttr);
6648}
6649
Francois Gaffieff1eb522020-05-06 18:37:04 +02006650void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6651{
6652 for (size_t i = 0; i < mAudioSources.size(); i++) {
6653 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6654 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006655 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006656 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006657 connectAudioSource(sourceDesc);
6658 }
6659 }
6660}
6661
6662void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6663{
6664 for (size_t i = 0; i < mAudioSources.size(); i++) {
6665 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6666 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6667 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6668 disconnectAudioSource(sourceDesc);
6669 }
6670 }
6671}
6672
François Gaffiec005e562018-11-06 15:04:49 +01006673void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6674{
6675 auto psId = mEngine->getProductStrategyForAttributes(attr);
6676
6677 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6678 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006679
François Gaffie11d30102018-11-02 16:09:09 +01006680 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6681 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006682
Eric Laurentc209fe42020-06-05 18:11:23 -07006683 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006684 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006685 // take into account dynamic audio policies related changes: if a client is now associated
6686 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006687 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006688 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6689 if (desc->isDuplicated()) {
6690 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006691 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006692 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6693 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6694 continue;
6695 }
6696 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006697 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006698 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006699 if (status != OK) {
6700 continue;
6701 }
yucliuf4de36d2020-09-14 14:57:56 -07006702 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006703 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006704 maxLatency = desc->latency();
6705 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006706 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006707 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006708 }
6709 }
6710
Eric Laurent56ed8842022-11-15 16:04:41 +01006711 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006712 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6713 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006714 for (audio_io_handle_t srcOut : srcOutputs) {
6715 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006716 if (desc == nullptr) continue;
6717
6718 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006719 maxLatency = desc->latency();
6720 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006721
Eric Laurent56ed8842022-11-15 16:04:41 +01006722 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006723 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006724 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006725 // a client on a non direct outputs has necessarily a linear PCM format
6726 // so we can call selectOutput() safely
6727 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6728 client->flags(),
6729 client->config().format,
6730 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006731 client->config().sample_rate,
6732 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006733 if (newOutput != srcOut) {
6734 invalidate = true;
6735 break;
6736 }
6737 } else {
6738 sp<IOProfile> profile = getProfileForOutput(newDevices,
6739 client->config().sample_rate,
6740 client->config().format,
6741 client->config().channel_mask,
6742 client->flags(),
6743 true /* directOnly */);
6744 if (profile != desc->mProfile) {
6745 invalidate = true;
6746 break;
6747 }
6748 }
6749 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006750 // mute strategy while moving tracks from one output to another
6751 if (invalidate) {
6752 invalidatedOutputs.push_back(desc);
6753 if (desc->isStrategyActive(psId)) {
6754 setStrategyMute(psId, true, desc);
6755 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6756 newDevices.types());
6757 }
Eric Laurente552edb2014-03-10 17:42:56 -07006758 }
François Gaffiec005e562018-11-06 15:04:49 +01006759 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006760 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006761 connectAudioSource(source);
6762 }
Eric Laurente552edb2014-03-10 17:42:56 -07006763 }
6764
Eric Laurent56ed8842022-11-15 16:04:41 +01006765 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6766 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6767 std::to_string(srcOutputs[0]).c_str(),
6768 std::to_string(dstOutputs[0]).c_str());
6769
François Gaffiec005e562018-11-06 15:04:49 +01006770 // Move effects associated to this stream from previous output to new output
6771 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006772 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006773 }
François Gaffiec005e562018-11-06 15:04:49 +01006774 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006775 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006776 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006777 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006778 desc->setTracksInvalidatedStatusByStrategy(psId);
6779 }
Eric Laurente552edb2014-03-10 17:42:56 -07006780 }
6781 }
6782}
6783
Eric Laurente0720872014-03-11 09:30:41 -07006784void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006785{
François Gaffiec005e562018-11-06 15:04:49 +01006786 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6787 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6788 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006789 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006790 }
Eric Laurente552edb2014-03-10 17:42:56 -07006791}
6792
Kevin Rocard153f92d2018-12-18 18:33:28 -08006793void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006794 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006795 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006796 for (size_t i = 0; i < mOutputs.size(); i++) {
6797 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6798 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006799 sp<AudioPolicyMix> primaryMix;
6800 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006801 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006802 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006803 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6804 for (auto &secondaryMix : secondaryMixes) {
6805 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6806 if (outputDesc != nullptr &&
6807 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6808 secondaryDescs.push_back(outputDesc);
6809 }
6810 }
6811
jiabinc44b3462022-12-08 12:52:31 -08006812 if (status != OK &&
6813 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
6814 // When it failed to query secondary output, only invalidate the client that is not
6815 // MMAP. The reason is that MMAP stream will not support secondary output.
6816 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00006817 } else if (!std::equal(
6818 client->getSecondaryOutputs().begin(),
6819 client->getSecondaryOutputs().end(),
6820 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006821 if (!audio_is_linear_pcm(client->config().format)) {
6822 // If the format is not PCM, the tracks should be invalidated to get correct
6823 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08006824 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00006825 } else {
6826 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6827 std::vector<audio_io_handle_t> secondaryOutputIds;
6828 for (const auto &secondaryDesc: secondaryDescs) {
6829 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6830 weakSecondaryDescs.push_back(secondaryDesc);
6831 }
6832 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6833 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006834 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006835 }
6836 }
6837 }
jiabin10a03f12021-05-07 23:46:28 +00006838 if (!trackSecondaryOutputs.empty()) {
6839 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6840 }
jiabinc44b3462022-12-08 12:52:31 -08006841 if (!clientsToInvalidate.empty()) {
6842 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
6843 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006844 }
6845}
6846
Eric Laurent2517af32020-11-25 15:31:27 +01006847bool AudioPolicyManager::isScoRequestedForComm() const {
6848 AudioDeviceTypeAddrVector devices;
6849 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6850 for (const auto &device : devices) {
6851 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6852 return true;
6853 }
6854 }
6855 return false;
6856}
6857
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006858bool AudioPolicyManager::isHearingAidUsedForComm() const {
6859 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6860 true /*fromCache*/);
6861 for (const auto &device : devices) {
6862 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6863 return true;
6864 }
6865 }
6866 return false;
6867}
6868
6869
Eric Laurente0720872014-03-11 09:30:41 -07006870void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006871{
François Gaffie53615e22015-03-19 09:24:12 +01006872 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006873 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006874 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006875 return;
6876 }
6877
Eric Laurent3a4311c2014-03-17 12:00:47 -07006878 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006879 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6880 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006881 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006882
6883 // if suspended, restore A2DP output if:
6884 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006885 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006886 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006887 //
Eric Laurentf732e072016-08-03 19:30:28 -07006888 // if not suspended, suspend A2DP output if:
6889 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006890 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006891 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006892 //
6893 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006894 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006895 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006896 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006897 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006898
6899 mpClientInterface->restoreOutput(a2dpOutput);
6900 mA2dpSuspended = false;
6901 }
6902 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006903 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006904 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006905 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006906 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006907
6908 mpClientInterface->suspendOutput(a2dpOutput);
6909 mA2dpSuspended = true;
6910 }
6911 }
6912}
6913
François Gaffie11d30102018-11-02 16:09:09 +01006914DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6915 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006916{
François Gaffie11d30102018-11-02 16:09:09 +01006917 DeviceVector devices;
6918
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006919 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006920 if (index >= 0) {
6921 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006922 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006923 ALOGV("%s device %s forced by patch %d", __func__,
6924 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6925 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006926 }
6927 }
6928
Dean Wheatley514b4312020-06-17 21:45:00 +10006929 // Do not retrieve engine device for outputs through MSD
6930 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6931 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6932 return outputDesc->devices();
6933 }
6934
Eric Laurent97ac8712018-07-27 18:59:02 -07006935 // Honor explicit routing requests only if no client using default routing is active on this
6936 // input: a specific app can not force routing for other apps by setting a preferred device.
6937 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006938 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006939 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006940 if (device != nullptr) {
6941 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006942 }
6943
François Gaffiea807ef92018-11-05 10:44:33 +01006944 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6945 // of setForceUse / Default Bus device here
6946 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6947 if (device != nullptr) {
6948 return DeviceVector(device);
6949 }
6950
François Gaffiec005e562018-11-06 15:04:49 +01006951 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6952 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6953 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306954 auto hasStreamActive = [&](auto stream) {
6955 return hasStream(streams, stream) && isStreamActive(stream, 0);
6956 };
Eric Laurent484e9272018-06-07 17:29:23 -07006957
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306958 auto doGetOutputDevicesForVoice = [&]() {
6959 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006960 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306961 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006962 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6963 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306964 };
6965
6966 // With low-latency playing on speaker, music on WFD, when the first low-latency
6967 // output is stopped, getNewOutputDevices checks for a product strategy
6968 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006969 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306970 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6971 // stream is associated to the output descriptor.
6972 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6973 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6974 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6975 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006976 // Retrieval of devices for voice DL is done on primary output profile, cannot
6977 // check the route (would force modifying configuration file for this profile)
6978 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6979 break;
6980 }
Eric Laurente552edb2014-03-10 17:42:56 -07006981 }
François Gaffiec005e562018-11-06 15:04:49 +01006982 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006983 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006984}
6985
François Gaffie11d30102018-11-02 16:09:09 +01006986sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6987 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006988{
François Gaffie11d30102018-11-02 16:09:09 +01006989 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006990
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006991 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006992 if (index >= 0) {
6993 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006994 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006995 ALOGV("getNewInputDevice() device %s forced by patch %d",
6996 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6997 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006998 }
6999 }
7000
Eric Laurent97ac8712018-07-27 18:59:02 -07007001 // Honor explicit routing requests only if no client using default routing is active on this
7002 // input: a specific app can not force routing for other apps by setting a preferred device.
7003 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007004 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7005 if (device != nullptr) {
7006 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007007 }
7008
Eric Laurentdc95a252018-04-12 12:46:56 -07007009 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007010 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007011 audio_attributes_t attributes;
7012 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007013 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007014 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7015 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007016 attributes = topClient->attributes();
7017 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007018 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007019 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007020 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7021 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007022 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007023 }
7024
Francois Gaffie716e1432019-01-14 16:58:59 +01007025 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7026 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007027 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007028 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007029 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007030 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007031
Eric Laurente552edb2014-03-10 17:42:56 -07007032 return device;
7033}
7034
Eric Laurent794fde22016-03-11 09:50:45 -08007035bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7036 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007037 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007038}
7039
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007040status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007041 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007042 if (devices == nullptr) {
7043 return BAD_VALUE;
7044 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007045
Andy Hung6d23c0f2022-02-16 09:37:15 -08007046 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007047 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7048 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007049 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007050 for (const auto& device : curDevices) {
7051 devices->push_back(device->getDeviceTypeAddr());
7052 }
7053 return NO_ERROR;
7054}
7055
Eric Laurente0720872014-03-11 09:30:41 -07007056void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007057 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007058 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007059 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007060 updateDevicesAndOutputs();
7061 break;
7062 default:
7063 break;
7064 }
7065}
7066
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007067uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007068
7069 // skip beacon mute management if a dedicated TTS output is available
7070 if (mTtsOutputAvailable) {
7071 return 0;
7072 }
7073
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007074 switch(event) {
7075 case STARTING_OUTPUT:
7076 mBeaconMuteRefCount++;
7077 break;
7078 case STOPPING_OUTPUT:
7079 if (mBeaconMuteRefCount > 0) {
7080 mBeaconMuteRefCount--;
7081 }
7082 break;
7083 case STARTING_BEACON:
7084 mBeaconPlayingRefCount++;
7085 break;
7086 case STOPPING_BEACON:
7087 if (mBeaconPlayingRefCount > 0) {
7088 mBeaconPlayingRefCount--;
7089 }
7090 break;
7091 }
7092
7093 if (mBeaconMuteRefCount > 0) {
7094 // any playback causes beacon to be muted
7095 return setBeaconMute(true);
7096 } else {
7097 // no other playback: unmute when beacon starts playing, mute when it stops
7098 return setBeaconMute(mBeaconPlayingRefCount == 0);
7099 }
7100}
7101
7102uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7103 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7104 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7105 // keep track of muted state to avoid repeating mute/unmute operations
7106 if (mBeaconMuted != mute) {
7107 // mute/unmute AUDIO_STREAM_TTS on all outputs
7108 ALOGV("\t muting %d", mute);
7109 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007110 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7111 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7112 ALOGV("\t no tts volume source available");
7113 return 0;
7114 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007115 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007116 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007117 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007118 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007119 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007120 maxLatency = latency;
7121 }
7122 }
7123 mBeaconMuted = mute;
7124 return maxLatency;
7125 }
7126 return 0;
7127}
7128
Eric Laurente0720872014-03-11 09:30:41 -07007129void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007130{
François Gaffiec005e562018-11-06 15:04:49 +01007131 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007132 mPreviousOutputs = mOutputs;
7133}
7134
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007135uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007136 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007137 uint32_t delayMs)
7138{
7139 // mute/unmute strategies using an incompatible device combination
7140 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7141 // if unmuting, unmute only after the specified delay
7142 if (outputDesc->isDuplicated()) {
7143 return 0;
7144 }
7145
7146 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007147 DeviceVector devices = outputDesc->devices();
7148 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007149
François Gaffiec005e562018-11-06 15:04:49 +01007150 auto productStrategies = mEngine->getOrderedProductStrategies();
7151 for (const auto &productStrategy : productStrategies) {
7152 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7153 DeviceVector curDevices =
7154 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7155 curDevices = curDevices.filter(outputDesc->supportedDevices());
7156 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007157 bool doMute = false;
7158
François Gaffiec005e562018-11-06 15:04:49 +01007159 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007160 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007161 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7162 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007163 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007164 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007165 }
Eric Laurent99401132014-05-07 19:48:15 -07007166 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007167 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007168 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007169 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007170 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007171 continue;
7172 }
François Gaffiec005e562018-11-06 15:04:49 +01007173 ALOGVV("%s() %s (curDevice %s)", __func__,
7174 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7175 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7176 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007177 if (mute) {
7178 // FIXME: should not need to double latency if volume could be applied
7179 // immediately by the audioflinger mixer. We must account for the delay
7180 // between now and the next time the audioflinger thread for this output
7181 // will process a buffer (which corresponds to one buffer size,
7182 // usually 1/2 or 1/4 of the latency).
7183 if (muteWaitMs < desc->latency() * 2) {
7184 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007185 }
7186 }
7187 }
7188 }
7189 }
7190 }
7191
Eric Laurent99401132014-05-07 19:48:15 -07007192 // temporary mute output if device selection changes to avoid volume bursts due to
7193 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007194 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007195 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007196
Eric Laurentdc462862016-07-19 12:29:53 -07007197 if (muteWaitMs < tempMuteWaitMs) {
7198 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007199 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007200
7201 // If recommended duration is defined, replace temporary mute duration to avoid
7202 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7203 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7204 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7205 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7206 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7207
François Gaffieaaac0fd2018-11-22 17:56:39 +01007208 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7209 // make sure that we do not start the temporary mute period too early in case of
7210 // delayed device change
7211 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7212 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007213 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007214 }
7215 }
7216
Eric Laurente552edb2014-03-10 17:42:56 -07007217 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7218 if (muteWaitMs > delayMs) {
7219 muteWaitMs -= delayMs;
7220 usleep(muteWaitMs * 1000);
7221 return muteWaitMs;
7222 }
7223 return 0;
7224}
7225
François Gaffie11d30102018-11-02 16:09:09 +01007226uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7227 const DeviceVector &devices,
7228 bool force,
7229 int delayMs,
7230 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007231 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007232{
jiabin3ff8d7d2022-12-13 06:27:44 +00007233 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007234 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007235 uint32_t muteWaitMs;
7236
7237 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007238 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7239 nullptr /* patchHandle */, requiresMuteCheck);
7240 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7241 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007242 return muteWaitMs;
7243 }
Eric Laurente552edb2014-03-10 17:42:56 -07007244
7245 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007246 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007247 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007248 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007249
François Gaffie11d30102018-11-02 16:09:09 +01007250 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7251
7252 if (!filteredDevices.isEmpty()) {
7253 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007254 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007255
7256 // if the outputs are not materially active, there is no need to mute.
7257 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007258 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007259 } else {
7260 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7261 muteWaitMs = 0;
7262 }
Eric Laurente552edb2014-03-10 17:42:56 -07007263
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007264 bool outputRouted = outputDesc->isRouted();
7265
Eric Laurent79ea9582020-06-11 18:49:24 -07007266 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7267 // output profile or if new device is not supported AND previous device(s) is(are) still
7268 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007269 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007270 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7271 // restore previous device after evaluating strategy mute state
7272 outputDesc->setDevices(prevDevices);
7273 return muteWaitMs;
7274 }
7275
Eric Laurente552edb2014-03-10 17:42:56 -07007276 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007277 // the requested device is AUDIO_DEVICE_NONE
7278 // OR the requested device is the same as current device
7279 // AND force is not specified
7280 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007281 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007282 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007283 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7284 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007285 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7286 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7287 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7288 }
Eric Laurente552edb2014-03-10 17:42:56 -07007289 return muteWaitMs;
7290 }
7291
François Gaffie11d30102018-11-02 16:09:09 +01007292 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007293
Eric Laurente552edb2014-03-10 17:42:56 -07007294 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007295 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007296 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007297 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007298 PatchBuilder patchBuilder;
7299 patchBuilder.addSource(outputDesc);
7300 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7301 for (const auto &filteredDevice : filteredDevices) {
7302 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007303 }
7304
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007305 // Add half reported latency to delayMs when muteWaitMs is null in order
7306 // to avoid disordered sequence of muting volume and changing devices.
7307 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7308 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007309 }
Eric Laurente552edb2014-03-10 17:42:56 -07007310
7311 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007312 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007313
7314 return muteWaitMs;
7315}
7316
Eric Laurentc75307b2015-03-17 15:29:32 -07007317status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007318 int delayMs,
7319 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007320{
Eric Laurent6a94d692014-05-20 11:18:06 -07007321 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007322 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7323 return INVALID_OPERATION;
7324 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007325 if (patchHandle) {
7326 index = mAudioPatches.indexOfKey(*patchHandle);
7327 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007328 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007329 }
7330 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007331 return INVALID_OPERATION;
7332 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007333 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007334 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007335 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007336 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007337 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007338 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007339 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007340 return status;
7341}
7342
7343status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007344 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007345 bool force,
7346 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007347{
7348 status_t status = NO_ERROR;
7349
Eric Laurent1f2f2232014-06-02 12:01:23 -07007350 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007351 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7352 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007353
François Gaffie11d30102018-11-02 16:09:09 +01007354 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007355 PatchBuilder patchBuilder;
7356 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007357 // AUDIO_SOURCE_HOTWORD is for internal use only:
7358 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007359 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7360 auto result = usecase;
7361 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7362 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7363 }
7364 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007365 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007366 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007367 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007368 }
7369 }
7370 return status;
7371}
7372
Eric Laurent6a94d692014-05-20 11:18:06 -07007373status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7374 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007375{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007376 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007377 ssize_t index;
7378 if (patchHandle) {
7379 index = mAudioPatches.indexOfKey(*patchHandle);
7380 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007381 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007382 }
7383 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007384 return INVALID_OPERATION;
7385 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007386 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007387 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007388 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007389 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007390 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007391 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007392 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007393 return status;
7394}
7395
François Gaffie11d30102018-11-02 16:09:09 +01007396sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007397 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007398 audio_format_t& format,
7399 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007400 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007401{
7402 // Choose an input profile based on the requested capture parameters: select the first available
7403 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007404 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007405 //
7406 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7407 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007408
jiabin2fd710d2022-05-02 23:20:22 +00007409 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7410 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007411
jiabin2fd710d2022-05-02 23:20:22 +00007412 for (;;) {
7413 sp<IOProfile> firstInexact = nullptr;
7414 uint32_t updatedSamplingRate = 0;
7415 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7416 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7417 for (const auto& hwModule : mHwModules) {
7418 for (const auto& profile : hwModule->getInputProfiles()) {
7419 // profile->log();
7420 //updatedFormat = format;
7421 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7422 &samplingRate /*updatedSamplingRate*/,
7423 format,
7424 &format, /*updatedFormat*/
7425 channelMask,
7426 &channelMask /*updatedChannelMask*/,
7427 // FIXME ugly cast
7428 (audio_output_flags_t) flags,
7429 true /*exactMatchRequiredForInputFlags*/)) {
7430 return profile;
7431 }
7432 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7433 samplingRate,
7434 &updatedSamplingRate,
7435 format,
7436 &updatedFormat,
7437 channelMask,
7438 &updatedChannelMask,
7439 // FIXME ugly cast
7440 (audio_output_flags_t) flags,
7441 false /*exactMatchRequiredForInputFlags*/)) {
7442 firstInexact = profile;
7443 }
7444 }
7445 }
7446
7447 if (firstInexact != nullptr) {
7448 samplingRate = updatedSamplingRate;
7449 format = updatedFormat;
7450 channelMask = updatedChannelMask;
7451 return firstInexact;
7452 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7453 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7454 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7455 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7456 flags = AUDIO_INPUT_FLAG_NONE;
7457 } else { // fail
7458 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7459 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7460 samplingRate, format, channelMask, oriFlags);
7461 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007462 }
7463 }
jiabin2fd710d2022-05-02 23:20:22 +00007464
7465 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007466}
7467
François Gaffieaaac0fd2018-11-22 17:56:39 +01007468float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7469 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007470 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007471 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007472{
jiabin9a3361e2019-10-01 09:38:30 -07007473 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007474
7475 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7476 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7477 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7478 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007479 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7480 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7481 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7482 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7483 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007484
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007485 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007486 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7487 mOutputs.isActive(ringVolumeSrc, 0)) {
7488 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007489 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007490 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007491 }
7492
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007493 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007494 if ((volumeSource != callVolumeSrc && (isInCall() ||
7495 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007496 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007497 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7498 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007499 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7500 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7501 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007502 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007503 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007504 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007505 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007506 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007507 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007508 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7509 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7510 // programmatically muted.
7511 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7512 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7513 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007514 bool exemptFromCapping =
7515 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7516 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007517 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7518 volumeSource, volumeDb);
7519 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007520 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7521 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7522 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007523 }
7524 }
Eric Laurente552edb2014-03-10 17:42:56 -07007525 // if a headset is connected, apply the following rules to ring tones and notifications
7526 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007527 // - always attenuate notifications volume by 6dB
7528 // - attenuate ring tones volume by 6dB unless music is not playing and
7529 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007530 // - if music is playing, always limit the volume to current music volume,
7531 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007532 if (!Intersection(deviceTypes,
7533 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7534 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007535 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7536 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007537 ((volumeSource == alarmVolumeSrc ||
7538 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007539 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7540 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7541 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007542 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7543 curves.canBeMuted()) {
7544
Eric Laurente552edb2014-03-10 17:42:56 -07007545 // when the phone is ringing we must consider that music could have been paused just before
7546 // by the music application and behave as if music was active if the last music track was
7547 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007548 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007549 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007550 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007551 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007552 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7553 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007554 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007555 float musicVolDb = computeVolume(musicCurves,
7556 musicVolumeSrc,
7557 musicCurves.getVolumeIndex(musicDevice),
7558 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007559 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7560 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7561 if (volumeDb > minVolDb) {
7562 volumeDb = minVolDb;
7563 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007564 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007565 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7566 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7567 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007568 // on A2DP, also ensure notification volume is not too low compared to media when
7569 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007570 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007571 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007572 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7573 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007574 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7575 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007576 }
7577 }
jiabin9a3361e2019-10-01 09:38:30 -07007578 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007579 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007580 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007581 }
7582 }
7583
François Gaffie43c73442018-11-08 08:21:55 +01007584 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007585}
7586
Eric Laurent3839bc02018-07-10 18:33:34 -07007587int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007588 VolumeSource fromVolumeSource,
7589 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007590{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007591 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007592 return srcIndex;
7593 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007594 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7595 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007596 float minSrc = (float)srcCurves.getVolumeIndexMin();
7597 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7598 float minDst = (float)dstCurves.getVolumeIndexMin();
7599 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007600
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007601 // preserve mute request or correct range
7602 if (srcIndex < minSrc) {
7603 if (srcIndex == 0) {
7604 return 0;
7605 }
7606 srcIndex = minSrc;
7607 } else if (srcIndex > maxSrc) {
7608 srcIndex = maxSrc;
7609 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007610 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7611}
7612
François Gaffieaaac0fd2018-11-22 17:56:39 +01007613status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7614 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007615 int index,
7616 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007617 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007618 int delayMs,
7619 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007620{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007621 // do not change actual attributes volume if the attributes is muted
7622 if (outputDesc->isMuted(volumeSource)) {
7623 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7624 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007625 return NO_ERROR;
7626 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007627 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7628 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7629 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7630 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007631
Eric Laurent2517af32020-11-25 15:31:27 +01007632 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007633 bool isHAUsed = isHearingAidUsedForComm();
7634
Eric Laurente552edb2014-03-10 17:42:56 -07007635 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007636 // if sco and call follow same curves, bypass forceUseForComm
7637 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007638 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007639 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007640 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007641 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007642 // Do not return an error here as AudioService will always set both voice call
7643 // and bluetooth SCO volumes due to stream aliasing.
7644 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007645 }
jiabin9a3361e2019-10-01 09:38:30 -07007646 if (deviceTypes.empty()) {
7647 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007648 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007649
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007650 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7651 ALOGE("invalid volume index range");
7652 return BAD_VALUE;
7653 }
7654
jiabin9a3361e2019-10-01 09:38:30 -07007655 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7656 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007657 // Force VoIP volume to max for bluetooth SCO device except if muted
7658 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007659 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007660 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007661 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007662 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007663 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007664 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007665
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007666 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007667 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007668 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01007669 if (isVoiceVolSrc) {
7670 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007671 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007672 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007673 }
Eric Laurent18fba842016-03-31 14:41:26 -07007674 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007675 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7676 mLastVoiceVolume = voiceVolume;
7677 }
7678 }
Eric Laurente552edb2014-03-10 17:42:56 -07007679 return NO_ERROR;
7680}
7681
Eric Laurentc75307b2015-03-17 15:29:32 -07007682void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007683 const DeviceTypeSet& deviceTypes,
7684 int delayMs,
7685 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007686{
jiabincd510522020-01-22 09:40:55 -08007687 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007688 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7689 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7690 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007691 curves.getVolumeIndex(deviceTypes),
7692 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007693 }
7694}
7695
François Gaffiec005e562018-11-06 15:04:49 +01007696void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7697 bool on,
7698 const sp<AudioOutputDescriptor>& outputDesc,
7699 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007700 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007701{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007702 std::vector<VolumeSource> sourcesToMute;
7703 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7704 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7705 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007706 VolumeSource source = toVolumeSource(attributes, false);
7707 if ((source != VOLUME_SOURCE_NONE) &&
7708 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7709 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007710 sourcesToMute.push_back(source);
7711 }
Eric Laurente552edb2014-03-10 17:42:56 -07007712 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007713 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007714 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007715 }
7716
Eric Laurente552edb2014-03-10 17:42:56 -07007717}
7718
François Gaffieaaac0fd2018-11-22 17:56:39 +01007719void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7720 bool on,
7721 const sp<AudioOutputDescriptor>& outputDesc,
7722 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007723 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007724{
jiabin9a3361e2019-10-01 09:38:30 -07007725 if (deviceTypes.empty()) {
7726 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007727 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007728 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007729 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007730 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007731 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007732 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007733 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7734 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007735 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007736 }
7737 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007738 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7739 // ignored
7740 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007741 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007742 if (!outputDesc->isMuted(volumeSource)) {
7743 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007744 return;
7745 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007746 if (outputDesc->decMuteCount(volumeSource) == 0) {
7747 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007748 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007749 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007750 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007751 delayMs);
7752 }
7753 }
7754}
7755
François Gaffie53615e22015-03-19 09:24:12 +01007756bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7757{
François Gaffiec005e562018-11-06 15:04:49 +01007758 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007759 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7760 return true;
7761 }
7762
7763 // has known usage?
7764 switch (paa->usage) {
7765 case AUDIO_USAGE_UNKNOWN:
7766 case AUDIO_USAGE_MEDIA:
7767 case AUDIO_USAGE_VOICE_COMMUNICATION:
7768 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7769 case AUDIO_USAGE_ALARM:
7770 case AUDIO_USAGE_NOTIFICATION:
7771 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7772 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7773 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7774 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7775 case AUDIO_USAGE_NOTIFICATION_EVENT:
7776 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7777 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7778 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7779 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007780 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007781 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007782 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007783 case AUDIO_USAGE_EMERGENCY:
7784 case AUDIO_USAGE_SAFETY:
7785 case AUDIO_USAGE_VEHICLE_STATUS:
7786 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007787 break;
7788 default:
7789 return false;
7790 }
7791 return true;
7792}
7793
François Gaffie2110e042015-03-24 08:41:51 +01007794audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7795{
7796 return mEngine->getForceUse(usage);
7797}
7798
Eric Laurent96d1dda2022-03-14 17:14:19 +01007799bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007800 return isStateInCall(mEngine->getPhoneState());
7801}
7802
Eric Laurent96d1dda2022-03-14 17:14:19 +01007803bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007804 return is_state_in_call(state);
7805}
7806
Eric Laurentf9cccec2022-11-16 19:12:00 +01007807bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007808 audio_mode_t mode = mEngine->getPhoneState();
7809 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007810 || (mode == AUDIO_MODE_CALL_SCREEN)
7811 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007812}
7813
Eric Laurentf9cccec2022-11-16 19:12:00 +01007814bool AudioPolicyManager::isInCallOrScreening() const {
7815 audio_mode_t mode = mEngine->getPhoneState();
7816 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7817}
7818
Eric Laurentd60560a2015-04-10 11:31:20 -07007819void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7820{
7821 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007822 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007823 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007824 sourceDesc->sinkDevice()->equals(deviceDesc))
7825 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007826 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007827 }
7828 }
7829
7830 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7831 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7832 bool release = false;
7833 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7834 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7835 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7836 source->ext.device.type == deviceDesc->type()) {
7837 release = true;
7838 }
7839 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007840 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007841 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7842 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7843 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007844 sink->ext.device.type == deviceDesc->type() &&
7845 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7846 || strncmp(sink->ext.device.address, address,
7847 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007848 release = true;
7849 }
7850 }
7851 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007852 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7853 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007854 }
7855 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007856
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007857 mInputs.clearSessionRoutesForDevice(deviceDesc);
7858
Francois Gaffie716e1432019-01-14 16:58:59 +01007859 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007860}
7861
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007862void AudioPolicyManager::modifySurroundFormats(
7863 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007864 std::unordered_set<audio_format_t> enforcedSurround(
7865 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007866 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7867 for (const auto& pair : mConfig.getSurroundFormats()) {
7868 allSurround.insert(pair.first);
7869 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7870 }
Phil Burk09bc4612016-02-24 15:58:15 -08007871
7872 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7873 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007874 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007875 // This is the resulting set of formats depending on the surround mode:
7876 // 'all surround' = allSurround
7877 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7878 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7879 // 'manual surround' = mManualSurroundFormats
7880 // AUTO: formats v 'enforced surround'
7881 // ALWAYS: formats v 'all surround' v 'enforced surround'
7882 // NEVER: formats ^ 'non-surround'
7883 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007884
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007885 std::unordered_set<audio_format_t> formatSet;
7886 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7887 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007888 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007889 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007890 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007891 formatSet.insert(*formatIter);
7892 }
7893 }
7894 } else {
7895 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7896 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007897 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007898
jiabin81772902018-04-02 17:52:27 -07007899 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007900 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007901 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7902 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7903 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007904 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007905 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7906 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7907 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007908 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007909 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007910 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007911 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007912 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007913 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007914}
7915
jiabin06e4bab2019-07-29 10:13:34 -07007916void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7917 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007918 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7919 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7920
7921 // If NEVER, then remove support for channelMasks > stereo.
7922 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007923 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7924 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007925 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007926 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007927 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007928 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007929 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007930 }
7931 }
jiabin81772902018-04-02 17:52:27 -07007932 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7933 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7934 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007935 bool supports5dot1 = false;
7936 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007937 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007938 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7939 supports5dot1 = true;
7940 break;
7941 }
7942 }
7943 // If not then add 5.1 support.
7944 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007945 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007946 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007947 }
Phil Burk09bc4612016-02-24 15:58:15 -08007948 }
7949}
7950
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007951void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007952 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007953 AudioProfileVector &profiles)
7954{
7955 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007956 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007957
François Gaffie112b0af2015-11-19 16:13:25 +01007958 // Format MUST be checked first to update the list of AudioProfile
7959 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007960 reply = mpClientInterface->getParameters(
7961 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007962 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007963 AudioParameter repliedParameters(reply);
7964 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007965 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007966 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7967 return;
7968 }
Phil Burk09bc4612016-02-24 15:58:15 -08007969 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007970 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007971 if (device == AUDIO_DEVICE_OUT_HDMI
7972 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007973 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007974 }
jiabin3e277cc2019-09-10 14:27:34 -07007975 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007976 }
François Gaffie112b0af2015-11-19 16:13:25 +01007977
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007978 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007979 ChannelMaskSet channelMasks;
7980 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007981 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007982 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007983
7984 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007985 reply = mpClientInterface->getParameters(
7986 ioHandle,
7987 requestedParameters.toString() + ";" +
7988 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007989 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007990 AudioParameter repliedParameters(reply);
7991 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007992 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007993 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007994 }
7995 }
7996 if (profiles.hasDynamicChannelsFor(format)) {
7997 reply = mpClientInterface->getParameters(ioHandle,
7998 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007999 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01008000 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008001 AudioParameter repliedParameters(reply);
8002 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008003 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08008004 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008005 if (device == AUDIO_DEVICE_OUT_HDMI
8006 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008007 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07008008 }
François Gaffie112b0af2015-11-19 16:13:25 +01008009 }
8010 }
jiabin3e277cc2019-09-10 14:27:34 -07008011 addDynamicAudioProfileAndSort(
8012 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008013 }
8014}
Eric Laurentd60560a2015-04-10 11:31:20 -07008015
Mikhail Naganovdc769682018-05-04 15:34:08 -07008016status_t AudioPolicyManager::installPatch(const char *caller,
8017 audio_patch_handle_t *patchHandle,
8018 AudioIODescriptorInterface *ioDescriptor,
8019 const struct audio_patch *patch,
8020 int delayMs)
8021{
8022 ssize_t index = mAudioPatches.indexOfKey(
8023 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8024 *patchHandle : ioDescriptor->getPatchHandle());
8025 sp<AudioPatch> patchDesc;
8026 status_t status = installPatch(
8027 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8028 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008029 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008030 }
8031 return status;
8032}
8033
8034status_t AudioPolicyManager::installPatch(const char *caller,
8035 ssize_t index,
8036 audio_patch_handle_t *patchHandle,
8037 const struct audio_patch *patch,
8038 int delayMs,
8039 uid_t uid,
8040 sp<AudioPatch> *patchDescPtr)
8041{
8042 sp<AudioPatch> patchDesc;
8043 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8044 if (index >= 0) {
8045 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008046 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008047 }
8048
8049 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8050 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8051 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8052 if (status == NO_ERROR) {
8053 if (index < 0) {
8054 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008055 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008056 } else {
8057 patchDesc->mPatch = *patch;
8058 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008059 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008060 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008061 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008062 }
8063 nextAudioPortGeneration();
8064 mpClientInterface->onAudioPatchListUpdate();
8065 }
8066 if (patchDescPtr) *patchDescPtr = patchDesc;
8067 return status;
8068}
8069
jiabinbce0c1d2020-10-05 11:20:18 -07008070bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8071{
8072 const TrackClientVector activeClients = output->getActiveClients();
8073 if (activeClients.empty()) {
8074 return true;
8075 }
8076 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8077 if (index < 0) {
8078 ALOGE("%s, no audio patch found while there are active clients on output %d",
8079 __func__, output->getId());
8080 return false;
8081 }
8082 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8083 DeviceVector routedDevices;
8084 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8085 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8086 patchDesc->mPatch.sinks[i].id);
8087 if (device == nullptr) {
8088 ALOGE("%s, no audio device found with id(%d)",
8089 __func__, patchDesc->mPatch.sinks[i].id);
8090 return false;
8091 }
8092 routedDevices.add(device);
8093 }
8094 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008095 if (client->isInvalid()) {
8096 // No need to take care about invalidated clients.
8097 continue;
8098 }
jiabinbce0c1d2020-10-05 11:20:18 -07008099 sp<DeviceDescriptor> preferredDevice =
8100 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8101 if (mEngine->getOutputDevicesForAttributes(
8102 client->attributes(), preferredDevice, false) == routedDevices) {
8103 return false;
8104 }
8105 }
8106 return true;
8107}
8108
8109sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008110 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008111 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8112 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008113{
8114 for (const auto& device : devices) {
8115 // TODO: This should be checking if the profile supports the device combo.
8116 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008117 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8118 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008119 return nullptr;
8120 }
8121 }
8122 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8123 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008124 status_t status = desc->open(halConfig, mixerConfig, devices,
8125 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008126 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008127 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008128 return nullptr;
8129 }
8130
8131 // Here is where the out_set_parameters() for card & device gets called
8132 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8133 const audio_devices_t deviceType = device->type();
8134 const String8 &address = String8(device->address().c_str());
8135 if (!address.isEmpty()) {
8136 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8137 mpClientInterface->setParameters(output, String8(param));
8138 free(param);
8139 }
8140 updateAudioProfiles(device, output, profile->getAudioProfiles());
8141 if (!profile->hasValidAudioProfile()) {
8142 ALOGW("%s() missing param", __func__);
8143 desc->close();
8144 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008145 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8146 // Reopen the output with the best audio profile picked by APM when the profile supports
8147 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008148 desc->close();
8149 output = AUDIO_IO_HANDLE_NONE;
8150 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8151 profile->pickAudioProfile(
8152 config.sample_rate, config.channel_mask, config.format);
8153 config.offload_info.sample_rate = config.sample_rate;
8154 config.offload_info.channel_mask = config.channel_mask;
8155 config.offload_info.format = config.format;
8156
jiabina84c3d32022-12-02 18:59:55 +00008157 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008158 if (status != NO_ERROR) {
8159 return nullptr;
8160 }
8161 }
8162
8163 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008164
baek.kim -61c20122022-07-27 10:05:32 +00008165 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8166 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8167
jiabinbce0c1d2020-10-05 11:20:18 -07008168 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8169 sp<AudioPolicyMix> policyMix;
8170 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8171 policyMix->setOutput(desc);
8172 desc->mPolicyMix = policyMix;
8173 } else {
8174 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8175 address.string());
8176 }
8177
baek.kim -61c20122022-07-27 10:05:32 +00008178 } else if (hasPrimaryOutput() && speaker != nullptr
8179 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008180 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8181 // no duplicated output for:
8182 // - direct outputs
8183 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008184 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008185 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8186
8187 //TODO: configure audio effect output stage here
8188
8189 // open a duplicating output thread for the new output and the primary output
8190 sp<SwAudioOutputDescriptor> dupOutputDesc =
8191 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8192 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8193 if (status == NO_ERROR) {
8194 // add duplicated output descriptor
8195 addOutput(duplicatedOutput, dupOutputDesc);
8196 } else {
8197 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8198 mPrimaryOutput->mIoHandle, output);
8199 desc->close();
8200 removeOutput(output);
8201 nextAudioPortGeneration();
8202 return nullptr;
8203 }
8204 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008205 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8206 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8207 mPrimaryOutput = desc;
8208 }
jiabinbce0c1d2020-10-05 11:20:18 -07008209 return desc;
8210}
8211
jiabinf1c73972022-04-14 16:28:52 -07008212status_t AudioPolicyManager::getDevicesForAttributes(
8213 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8214 // Devices are determined in the following precedence:
8215 //
8216 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8217 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8218 //
8219 // If no such dynamic policy then
8220 // 2) Devices containing an active client using setPreferredDevice
8221 // with same strategy as the attributes.
8222 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8223 //
8224 // If no corresponding active client with setPreferredDevice then
8225 // 3) Devices associated with the strategy determined by the attributes
8226 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8227 //
8228 // See related getOutputForAttrInt().
8229
8230 // check dynamic policies but only for primary descriptors (secondary not used for audible
8231 // audio routing, only used for duplication for playback capture)
8232 sp<AudioPolicyMix> policyMix;
8233 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02008234 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07008235 nullptr /* secondaryMixes */);
8236 if (status != OK) {
8237 return status;
8238 }
8239
8240 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8241 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8242 // as they are unaffected by device/stream volume
8243 // (per SwAudioOutputDescriptor::isFixedVolume()).
8244 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8245 ) {
8246 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8247 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8248 devices.add(deviceDesc);
8249 } else {
8250 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8251 // which selects setPreferredDevice if active. This means forVolume call
8252 // will take an active setPreferredDevice, if such exists.
8253
8254 devices = mEngine->getOutputDevicesForAttributes(
8255 attr, nullptr /* preferredDevice */, false /* fromCache */);
8256 }
8257
8258 if (forVolume) {
8259 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8260 // for single volume control in AudioService (such relationship should exist if
8261 // SPEAKER_SAFE is present).
8262 //
8263 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8264 DeviceVector speakerSafeDevices =
8265 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8266 if (!speakerSafeDevices.isEmpty()) {
8267 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8268 devices.remove(speakerSafeDevices);
8269 }
8270 }
8271
8272 return NO_ERROR;
8273}
8274
8275status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8276 AudioProfileVector& audioProfiles,
8277 uint32_t flags,
8278 bool isInput) {
8279 for (const auto& hwModule : mHwModules) {
8280 // the MSD module checks for different conditions
8281 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8282 continue;
8283 }
8284 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8285 : hwModule->getOutputProfiles();
8286 for (const auto& profile : ioProfiles) {
8287 if (!profile->areAllDevicesSupported(devices) ||
8288 !profile->isCompatibleProfileForFlags(
8289 flags, false /*exactMatchRequiredForInputFlags*/)) {
8290 continue;
8291 }
8292 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8293 }
8294 }
8295
8296 if (!isInput) {
8297 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8298 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8299 if (msdModule != nullptr) {
8300 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8301 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8302 for (const auto &profile: msdModule->getOutputProfiles()) {
8303 if (!profile->asAudioPort()->isDirectOutput()) {
8304 continue;
8305 }
8306 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8307 }
8308 } else {
8309 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8310 }
8311 }
8312 }
8313
8314 return NO_ERROR;
8315}
8316
jiabin3ff8d7d2022-12-13 06:27:44 +00008317sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8318 const audio_config_t *config,
8319 audio_output_flags_t flags,
8320 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008321 closeOutput(outputDesc->mIoHandle);
8322 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8323 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8324 if (preferredOutput == nullptr) {
8325 ALOGE("%s failed to reopen output device=%d, caller=%s",
8326 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008327 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008328 return preferredOutput;
8329}
8330
8331void AudioPolicyManager::reopenOutputsWithDevices(
8332 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8333 for (const auto& [output, devices] : outputsToReopen) {
8334 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8335 closeOutput(output);
8336 openOutputWithProfileAndDevice(desc->mProfile, devices);
8337 }
jiabina84c3d32022-12-02 18:59:55 +00008338}
8339
jiabinc44b3462022-12-08 12:52:31 -08008340PortHandleVector AudioPolicyManager::getClientsForStream(
8341 audio_stream_type_t streamType) const {
8342 PortHandleVector clients;
8343 for (size_t i = 0; i < mOutputs.size(); ++i) {
8344 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8345 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8346 }
8347 return clients;
8348}
8349
8350void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8351 PortHandleVector clients;
8352 for (auto stream : streams) {
8353 PortHandleVector clientsForStream = getClientsForStream(stream);
8354 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8355 }
8356 mpClientInterface->invalidateTracks(clients);
8357}
8358
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008359} // namespace android