blob: 9df2cf3f88b4593fc2b5cef6ea00e6a5785eb764 [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 Nairc18e9a12022-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 Naganov0566bac2022-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 Nairc18e9a12022-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
Eric Laurente552edb2014-03-10 17:42:56 -0700253 } break;
254
255 default:
François Gaffie11d30102018-11-02 16:09:09 +0100256 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700257 return BAD_VALUE;
258 }
259
Eric Laurent736a1022019-03-27 18:28:46 -0700260 // Propagate device availability to Engine
261 setEngineDeviceConnectionState(device, state);
262
Eric Laurentae970022019-01-29 14:25:04 -0800263 // No need to evaluate playback routing when connecting a remote submix
264 // output device used by a dynamic policy of type recorder as no
265 // playback use case is affected.
266 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700267 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800268 for (audio_io_handle_t output : outputs) {
269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800270 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
271 if (policyMix != nullptr
272 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700273 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800274 doCheckForDeviceAndOutputChanges = false;
275 break;
276 }
277 }
278 }
279
280 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700281 // outputs must be closed after checkOutputForAllStrategies() is executed
282 if (!outputs.isEmpty()) {
283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100285 // close unused outputs after device disconnection or direct outputs that have
286 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200287 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200288 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
289 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200290 (desc->mDirectOpenCount == 0))
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
292 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent96d1dda2022-03-14 17:14:19 +0100356 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
357
Eric Laurent72aa32f2014-05-30 18:51:48 -0700358 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700359 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700360 } // end if is output device
361
Eric Laurente552edb2014-03-10 17:42:56 -0700362 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700363 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100364 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700365 switch (state)
366 {
367 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700368 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700369 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700371 return INVALID_OPERATION;
372 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700373
374 if (mAvailableInputDevices.add(device) < 0) {
375 return NO_MEMORY;
376 }
377
François Gaffie44481e72016-04-20 07:49:57 +0200378 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
379 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100380 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200381
Eric Laurent0dd51852019-04-19 18:18:58 -0700382 if (checkInputsForDevice(device, state) != NO_ERROR) {
383 mAvailableInputDevices.remove(device);
384
François Gaffie11d30102018-11-02 16:09:09 +0100385 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100386
387 mHwModules.cleanUpForDevice(device);
388
Eric Laurentd4692962014-05-05 18:13:44 -0700389 return INVALID_OPERATION;
390 }
391
Eric Laurentd4692962014-05-05 18:13:44 -0700392 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700393
394 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700395 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100397 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700398 return INVALID_OPERATION;
399 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700402
403 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100404 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700405
François Gaffie11d30102018-11-02 16:09:09 +0100406 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700407
408 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100409
410 // remove device from mReportedFormatsMap cache
411 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700412 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700413
414 default:
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return BAD_VALUE;
417 }
418
Eric Laurent736a1022019-03-27 18:28:46 -0700419 // Propagate device availability to Engine
420 setEngineDeviceConnectionState(device, state);
421
Eric Laurent0dd51852019-04-19 18:18:58 -0700422 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700423 // As the input device list can impact the output device selection, update
424 // getDeviceForStrategy() cache
425 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700426
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100427 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200428 // Reconnect Audio Source
429 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
430 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
431 checkAudioSourceForAttributes(attributes);
432 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100434 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700435 }
436
Eric Laurentb52c1522014-05-20 11:27:36 -0700437 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700439 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700440
François Gaffie11d30102018-11-02 16:09:09 +0100441 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700442 return BAD_VALUE;
443}
444
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100445status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
446 const char* device_name,
Atneya Nairc18e9a12022-12-18 16:45:15 -0800447 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100448 DeviceDescriptorBase devDescr(device, device_address);
449 devDescr.setName(device_name);
450 return devDescr.writeToParcelable(aidlPort);
451}
452
Eric Laurent736a1022019-03-27 18:28:46 -0700453void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
454 audio_policy_dev_state_t state) {
455
456 // the Engine does not have to know about remote submix devices used by dynamic audio policies
457 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
458 return;
459 }
460 mEngine->setDeviceConnectionState(device, state);
461}
462
463
Eric Laurente0720872014-03-11 09:30:41 -0700464audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100465 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700466{
Eric Laurent634b7142016-04-20 13:48:02 -0700467 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
469 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700470 (strlen(device_address) != 0)/*matchAddress*/);
471
472 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100473 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700474 device, device_address);
475 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
476 }
François Gaffie53615e22015-03-19 09:24:12 +0100477
Eric Laurent3a4311c2014-03-17 12:00:47 -0700478 DeviceVector *deviceVector;
479
Eric Laurente552edb2014-03-10 17:42:56 -0700480 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700482 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700483 deviceVector = &mAvailableInputDevices;
484 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100485 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700486 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700487 }
Eric Laurent634b7142016-04-20 13:48:02 -0700488
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800489 return (deviceVector->getDevice(
490 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700491 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800492}
493
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800494status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
495 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800496 const char *device_name,
497 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800498{
499 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700500 String8 reply;
501 AudioParameter param;
502 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800503
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800504 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
505 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800506
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800507 // connect/disconnect only 1 device at a time
508 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
509
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700511 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513 // Nothing to do: device is not connected
514 return NO_ERROR;
515 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700518 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 // configure codecs.
520 // Handle two specific cases by sending a set parameter to
521 // configure A2DP codecs. No need to toggle device state.
522 // Case 1: A2DP active device switches from primary to primary
523 // module
524 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200525 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700526 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
528 if (availablePrimaryOutputDevices().contains(devDesc) &&
529 (module != 0 && module->getHandle() == primaryHandle)) {
530 reply = mpClientInterface->getParameters(
531 AUDIO_IO_HANDLE_NONE,
532 String8(AudioParameter::keyReconfigA2dpSupported));
533 AudioParameter repliedParameters(reply);
534 repliedParameters.getInt(
535 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
536 if (isReconfigA2dpSupported) {
537 const String8 key(AudioParameter::keyReconfigA2dp);
538 param.add(key, String8("true"));
539 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
540 devDesc->setEncodedFormat(encodedFormat);
541 return NO_ERROR;
542 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 }
544 }
cnx421bd2dcc42020-07-11 14:58:44 +0800545 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
546 for (size_t i = 0; i < mOutputs.size(); i++) {
547 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
548 // mute media strategies and delay device switch by the largest
549 // This avoid sending the music tail into the earpiece or headset.
550 setStrategyMute(musicStrategy, true, desc);
551 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
552 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
553 nullptr, true /*fromCache*/).types());
554 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800555 // Toggle the device state: UNAVAILABLE -> AVAILABLE
556 // This will force reading again the device configuration
557 status = setDeviceConnectionState(device,
558 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 device_address, device_name,
560 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561 if (status != NO_ERROR) {
562 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
563 status);
564 return status;
565 }
566
567 status = setDeviceConnectionState(device,
568 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800569 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 if (status != NO_ERROR) {
571 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
572 status);
573 return status;
574 }
575
576 return NO_ERROR;
577}
578
Pattydd807582021-11-04 21:01:03 +0800579status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
580 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581{
Pattydd807582021-11-04 21:01:03 +0800582 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800583 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800584 std::unordered_set<audio_format_t> formatSet;
585 sp<HwModule> primaryModule =
586 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700587 if (primaryModule == nullptr) {
588 ALOGE("%s() unable to get primary module", __func__);
589 return NO_INIT;
590 }
Pattydd807582021-11-04 21:01:03 +0800591
592 DeviceTypeSet audioDeviceSet;
593
594 switch(device) {
595 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
596 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
597 break;
598 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huangf5082dd2022-07-06 00:14:12 +0800599 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
600 break;
601 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
602 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800603 break;
604 default:
605 ALOGE("%s() device type 0x%08x not supported", __func__, device);
606 return BAD_VALUE;
607 }
608
jiabin9a3361e2019-10-01 09:38:30 -0700609 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800610 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800611 for (const auto& device : declaredDevices) {
612 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800613 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800615 return status;
616}
617
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100618DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
619{
620 DeviceVector rxSinkdevices{};
621 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
622 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
623 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
624 auto rxSinkDevice = rxSinkdevices.itemAt(0);
625 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
626 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
627 // retrieve Rx Source device descriptor
628 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
630
631 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
632 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
633 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
634 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
635 return DeviceVector(rxSinkDevice);
636 }
637 }
638 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
639 // the device returned is not necessarily reachable via this output
640 // (filter later by setOutputDevices())
641 return getNewOutputDevices(mPrimaryOutput, fromCache);
642}
643
644status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
645{
646 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
647 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
648 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
649 }
650 return INVALID_OPERATION;
651}
652
653status_t AudioPolicyManager::updateCallRoutingInternal(
654 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700655{
656 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100657 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700658 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700659 if(!hasPrimaryOutput() ||
660 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100661 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700662 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100664
Francois Gaffie716e1432019-01-14 16:58:59 +0100665 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100666 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100668
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100669 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100670 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671
Francois Gaffie601801d2021-06-22 13:27:39 +0200672 disconnectTelephonyAudioSource(mCallRxSourceClient);
673 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
François Gaffie9eb18552018-11-05 10:33:26 +0100675 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700676 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100677 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700678 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100679 // retrieve Rx Source and Tx Sink device descriptors
680 sp<DeviceDescriptor> rxSourceDevice =
681 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
682 String8(),
683 AUDIO_FORMAT_DEFAULT);
684 sp<DeviceDescriptor> txSinkDevice =
685 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
686 String8(),
687 AUDIO_FORMAT_DEFAULT);
688
689 // RX and TX Telephony device are declared by Primary Audio HAL
690 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
691 (telephonyRxModule->getHalVersionMajor() >= 3)) {
692 if (rxSourceDevice == 0 || txSinkDevice == 0) {
693 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGE("%s() no telephony Tx and/or RX device", __func__);
695 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100696 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100697 // createAudioPatchInternal now supports both HW / SW bridging
698 createRxPatch = true;
699 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100700 } else {
701 // If the RX device is on the primary HW module, then use legacy routing method for
702 // voice calls via setOutputDevice() on primary output.
703 // Otherwise, create two audio patches for TX and RX path.
704 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
705 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700706 // If the TX device is also on the primary HW module, setOutputDevice() will take care
707 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100708 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
709 (txSinkDevice != 0);
710 }
711 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
712 // Otherwise, create two audio patches for TX and RX path.
713 if (!createRxPatch) {
714 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700715 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200716 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800717 // If the TX device is on the primary HW module but RX device is
718 // on other HW module, SinkMetaData of telephony input should handle it
719 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700720 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700721 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100722 // terminate active capture if on the same HW module as the call TX source device
723 // FIXME: would be better to refine to only inputs whose profile connects to the
724 // call TX device but this information is not in the audio patch and logic here must be
725 // symmetric to the one in startInput()
726 for (const auto& activeDesc : mInputs.getActiveInputs()) {
727 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
728 closeActiveClients(activeDesc);
729 }
730 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200731 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800732 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100733 if (waitMs != nullptr) {
734 *waitMs = muteWaitMs;
735 }
736 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800737}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738
Mikhail Naganov100f0122018-11-29 11:22:16 -0800739bool AudioPolicyManager::isDeviceOfModule(
740 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
741 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
742 if (module != 0) {
743 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
744 .indexOf(devDesc) != NAME_NOT_FOUND
745 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
746 .indexOf(devDesc) != NAME_NOT_FOUND;
747 }
748 return false;
749}
750
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200751void AudioPolicyManager::connectTelephonyRxAudioSource()
752{
Francois Gaffie601801d2021-06-22 13:27:39 +0200753 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754 const struct audio_port_config source = {
755 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
756 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
757 };
758 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200759 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
760 ALOGE_IF(mCallRxSourceClient == nullptr,
761 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200762}
763
Francois Gaffie601801d2021-06-22 13:27:39 +0200764void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765{
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 if (clientDesc == nullptr) {
767 return;
768 }
769 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
770 "%s error stopping audio source", __func__);
771 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200772}
773
774void AudioPolicyManager::connectTelephonyTxAudioSource(
775 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
776 uint32_t delayMs)
777{
Francois Gaffie601801d2021-06-22 13:27:39 +0200778 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779 if (srcDevice == nullptr || sinkDevice == nullptr) {
780 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
781 return;
782 }
783 PatchBuilder patchBuilder;
784 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
785 ALOGV("%s between source %s and sink %s", __func__,
786 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200787 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200788 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
789
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200790 struct audio_port_config source = {};
791 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 mCallTxSourceClient = new InternalSourceClientDescriptor(
793 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200794 mCommunnicationStrategy, toVolumeSource(aa));
795 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
796 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
798 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200799 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
800 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200802 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200803}
804
Eric Laurente0720872014-03-11 09:30:41 -0700805void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700806{
807 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100808 // store previous phone state for management of sonification strategy below
809 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100810 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100811
812 if (mEngine->setPhoneState(state) != NO_ERROR) {
813 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700814 return;
815 }
François Gaffie2110e042015-03-24 08:41:51 +0100816 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700817 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700818 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700819 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800820 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 }
822
François Gaffie2110e042015-03-24 08:41:51 +0100823 /**
824 * Switching to or from incall state or switching between telephony and VoIP lead to force
825 * routing command.
826 */
Eric Laurent74b71512019-11-06 17:21:57 -0800827 bool force = ((isStateInCall(oldState) != isStateInCall(state))
828 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700829
830 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700831 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700832
Eric Laurente552edb2014-03-10 17:42:56 -0700833 int delayMs = 0;
834 if (isStateInCall(state)) {
835 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100836 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
837 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700838 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700839 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 // mute media and sonification strategies and delay device switch by the largest
841 // latency of any output where either strategy is active.
842 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100843 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
844 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
845 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700846 (delayMs < (int)desc->latency()*2)) {
847 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700848 }
François Gaffiec005e562018-11-06 15:04:49 +0100849 setStrategyMute(musicStrategy, true, desc);
850 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
851 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
852 nullptr, true /*fromCache*/).types());
853 setStrategyMute(sonificationStrategy, true, desc);
854 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
855 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
856 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700857 }
858 }
859
Eric Laurent87ffa392015-05-22 10:32:38 -0700860 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700861 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100862 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700863 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100864 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
865 // force routing command to audio hardware when ending call
866 // even if no device change is needed
867 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
868 rxDevices = mPrimaryOutput->devices();
869 }
870 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200871 disconnectTelephonyAudioSource(mCallRxSourceClient);
872 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100873 }
François Gaffie11d30102018-11-02 16:09:09 +0100874 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700875 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700876 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700877
878 // reevaluate routing on all outputs in case tracks have been started during the call
879 for (size_t i = 0; i < mOutputs.size(); i++) {
880 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100881 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200882 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
883 bool forceRouting = !newDevices.isEmpty();
884 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
885 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700886 }
887 }
888
Eric Laurent96d1dda2022-03-14 17:14:19 +0100889 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
890
Eric Laurente552edb2014-03-10 17:42:56 -0700891 if (isStateInCall(state)) {
892 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700893 // force reevaluating accessibility routing when call starts
894 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 }
896
897 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100898 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
899 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700900}
901
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700902audio_mode_t AudioPolicyManager::getPhoneState() {
903 return mEngine->getPhoneState();
904}
905
Eric Laurente0720872014-03-11 09:30:41 -0700906void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100907 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700908{
François Gaffie2110e042015-03-24 08:41:51 +0100909 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700910 if (config == mEngine->getForceUse(usage)) {
911 return;
912 }
Eric Laurente552edb2014-03-10 17:42:56 -0700913
François Gaffie2110e042015-03-24 08:41:51 +0100914 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
915 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
916 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700917 }
François Gaffie2110e042015-03-24 08:41:51 +0100918 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
919 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
920 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700921
922 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700923 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800924
Eric Laurent22fcda22019-05-17 16:28:47 -0700925 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
926 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
927 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
928 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
929 }
930
Eric Laurentdc462862016-07-19 12:29:53 -0700931 //FIXME: workaround for truncated touch sounds
932 // to be removed when the problem is handled by system UI
933 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700934 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
935 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
936 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700937
938 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100939 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700940}
941
Eric Laurente0720872014-03-11 09:30:41 -0700942void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700943{
944 ALOGV("setSystemProperty() property %s, value %s", property, value);
945}
946
Dorin Drimusecc9f422022-03-09 17:57:40 +0100947// Find an MSD output profile compatible with the parameters passed.
948// When "directOnly" is set, restrict search to profiles for direct outputs.
949sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
950 const DeviceVector& devices,
951 uint32_t samplingRate,
952 audio_format_t format,
953 audio_channel_mask_t channelMask,
954 audio_output_flags_t flags,
955 bool directOnly)
956{
957 flags = getRelevantFlags(flags, directOnly);
958
959 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
960 if (msdModule != nullptr) {
961 // for the msd module check if there are patches to the output devices
962 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
963 HwModuleCollection modules;
964 modules.add(msdModule);
965 return searchCompatibleProfileHwModules(
966 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
967 flags, directOnly);
968 }
969 }
970 return nullptr;
971}
972
Michael Chana94fbb22018-04-24 14:31:19 +1000973// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
974// search to profiles for direct outputs.
975sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100976 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000977 uint32_t samplingRate,
978 audio_format_t format,
979 audio_channel_mask_t channelMask,
980 audio_output_flags_t flags,
981 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700982{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100983 flags = getRelevantFlags(flags, directOnly);
984
985 return searchCompatibleProfileHwModules(
986 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
987}
988
989audio_output_flags_t AudioPolicyManager::getRelevantFlags (
990 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000991 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100992 // only retain flags that will drive the direct output profile selection
993 // if explicitly requested
994 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000995 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100996 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
997 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000998 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100999 return flags;
1000}
Eric Laurent861a6282015-05-18 15:40:16 -07001001
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1003 const HwModuleCollection& hwModules,
1004 const DeviceVector& devices,
1005 uint32_t samplingRate,
1006 audio_format_t format,
1007 audio_channel_mask_t channelMask,
1008 audio_output_flags_t flags,
1009 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001010 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001011 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001012 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001013 if (!curProfile->isCompatibleProfile(devices,
1014 samplingRate, NULL /*updatedSamplingRate*/,
1015 format, NULL /*updatedFormat*/,
1016 channelMask, NULL /*updatedChannelMask*/,
1017 flags)) {
1018 continue;
1019 }
1020 // reject profiles not corresponding to a device currently available
1021 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1022 continue;
1023 }
1024 // reject profiles if connected device does not support codec
1025 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1026 continue;
1027 }
1028 if (!directOnly) {
1029 return curProfile;
1030 }
1031
1032 // when searching for direct outputs, if several profiles are compatible, give priority
1033 // to one with offload capability
Patty Huangf5082dd2022-07-06 00:14:12 +08001034 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001035 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001036 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 }
1038 profile = curProfile;
1039 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1040 break;
1041 }
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
1043 }
Eric Laurent861a6282015-05-18 15:40:16 -07001044 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001045}
1046
Eric Laurentfa0f6742021-08-17 18:39:44 +02001047sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001048 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001049{
1050 for (const auto& hwModule : mHwModules) {
1051 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001052 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001053 continue;
1054 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001055 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001056 // reject profiles not corresponding to a device currently available
1057 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1058 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1059 continue;
1060 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001061 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1062 != devices.size()) {
1063 continue;
1064 }
1065 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001066 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1067 return curProfile;
1068 }
1069 }
1070 return nullptr;
1071}
1072
Eric Laurentf4e63452017-11-06 19:31:46 +00001073audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001074{
François Gaffiec005e562018-11-06 15:04:49 +01001075 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001076
1077 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1078 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1079 // format, flags, etc. This may result in some discrepancy for functions that utilize
1080 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1081 // and AudioSystem::getOutputSamplingRate().
1082
François Gaffie11d30102018-11-02 16:09:09 +01001083 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001084 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
François Gaffie11d30102018-11-02 16:09:09 +01001086 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1087 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001088 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001089}
1090
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001091status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1092 const audio_attributes_t *srcAttr,
1093 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001094{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001095 if (srcAttr != NULL) {
1096 if (!isValidAttributes(srcAttr)) {
1097 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1098 __func__,
1099 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1100 srcAttr->tags);
1101 return BAD_VALUE;
1102 }
1103 *dstAttr = *srcAttr;
1104 } else {
1105 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1106 ALOGE("%s: invalid stream type", __func__);
1107 return BAD_VALUE;
1108 }
François Gaffiec005e562018-11-06 15:04:49 +01001109 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001111
1112 // Only honor audibility enforced when required. The client will be
1113 // forced to reconnect if the forced usage changes.
1114 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001115 dstAttr->flags = static_cast<audio_flags_mask_t>(
1116 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001117 }
1118
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001119 return NO_ERROR;
1120}
1121
Kevin Rocard153f92d2018-12-18 18:33:28 -08001122status_t AudioPolicyManager::getOutputForAttrInt(
1123 audio_attributes_t *resultAttr,
1124 audio_io_handle_t *output,
1125 audio_session_t session,
1126 const audio_attributes_t *attr,
1127 audio_stream_type_t *stream,
1128 uid_t uid,
1129 const audio_config_t *config,
1130 audio_output_flags_t *flags,
1131 audio_port_handle_t *selectedDeviceId,
1132 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001133 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001134 output_type_t *outputType,
1135 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136{
François Gaffiec005e562018-11-06 15:04:49 +01001137 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001138 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001139 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001140 const sp<DeviceDescriptor> requestedDevice =
1141 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1142
Eric Laurent8a1095a2019-11-08 14:44:16 -08001143 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001144 *isSpatialized = false;
1145
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001146 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1147 if (status != NO_ERROR) {
1148 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001149 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001150 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001151 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001152 }
François Gaffiec005e562018-11-06 15:04:49 +01001153 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001154
François Gaffiec005e562018-11-06 15:04:49 +01001155 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1156 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001157
Kevin Rocard153f92d2018-12-18 18:33:28 -08001158 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1159 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1160 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001161 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001162 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1163 .channel_mask = config->channel_mask,
1164 .format = config->format,
1165 };
1166 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1167 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001168 if (status != OK) {
1169 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001170 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001171
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001174
1175 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001176 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1177 && !audio_is_linear_pcm(config->format)) {
1178 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001179 return BAD_VALUE;
1180 }
1181 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001182 sp<DeviceDescriptor> deviceDesc =
1183 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1184 primaryMix->mDeviceAddress,
1185 AUDIO_FORMAT_DEFAULT);
1186 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001187 bool tryDirectForFlags = policyDesc == nullptr ||
1188 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1189 // if a direct output can be opened to deliver the track's multi-channel content to the
1190 // output rather than being downmixed by the primary output, then use this direct
1191 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1192 // mix.
1193 bool tryDirectForChannelMask = policyDesc != nullptr
1194 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1195 audio_channel_count_from_out_mask(config->channel_mask));
1196 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001197 audio_io_handle_t newOutput;
1198 status = openDirectOutput(
1199 *stream, session, config,
1200 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1201 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001202 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 policyDesc = mOutputs.valueFor(newOutput);
1204 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001205 } else if (tryDirectForFlags) {
1206 policyDesc = nullptr;
1207 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 }
1209 if (policyDesc != nullptr) {
1210 policyDesc->mPolicyMix = primaryMix;
1211 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001212 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001213
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001214 ALOGV("getOutputForAttr() returns output %d", *output);
1215 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1216 *outputType = API_OUT_MIX_PLAYBACK;
1217 } else {
1218 *outputType = API_OUTPUT_LEGACY;
1219 }
1220 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001221 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001222 }
François Gaffiec005e562018-11-06 15:04:49 +01001223 // Virtual sources must always be dynamicaly or explicitly routed
1224 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1225 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1226 return BAD_VALUE;
1227 }
1228 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1229 // in order to let the choice of the order to future vendor engine
1230 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001231
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001232 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001233 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001234 }
1235
Nadav Barb2f18162018-07-18 13:01:53 +03001236 // Set incall music only if device was explicitly set, and fallback to the device which is
1237 // chosen by the engine if not.
1238 // FIXME: provide a more generic approach which is not device specific and move this back
1239 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001240 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001241 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001242 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001243 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001244 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001245 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001246 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001247 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001248 }
1249 }
1250
François Gaffiec005e562018-11-06 15:04:49 +01001251 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1252 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1253 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001254
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001255 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001256 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001257 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001258 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001259 ALOGV("%s() Using MSD devices %s instead of devices %s",
1260 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001261 } else {
1262 *output = AUDIO_IO_HANDLE_NONE;
1263 }
1264 }
1265 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001266 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001267 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001269 if (*output == AUDIO_IO_HANDLE_NONE) {
1270 return INVALID_OPERATION;
1271 }
Paul McLeanaa981192015-03-21 09:55:15 -07001272
François Gaffiec005e562018-11-06 15:04:49 +01001273 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001274 for (auto &outputDevice : outputDevices) {
1275 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1276 *selectedDeviceId = outputDevice->getId();
1277 break;
1278 }
1279 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001280
Eric Laurent8a1095a2019-11-08 14:44:16 -08001281 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1282 *outputType = API_OUTPUT_TELEPHONY_TX;
1283 } else {
1284 *outputType = API_OUTPUT_LEGACY;
1285 }
1286
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001287 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1288
1289 return NO_ERROR;
1290}
1291
1292status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1293 audio_io_handle_t *output,
1294 audio_session_t session,
1295 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001296 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001297 const audio_config_t *config,
1298 audio_output_flags_t *flags,
1299 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001300 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001301 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001302 output_type_t *outputType,
1303 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001304{
1305 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1306 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1307 return INVALID_OPERATION;
1308 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001309 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001310 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001311 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001312 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001313 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001314 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001315 const sp<DeviceDescriptor> requestedDevice =
1316 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1317
1318 // Prevent from storing invalid requested device id in clients
1319 const audio_port_handle_t sanitizedRequestedPortId =
1320 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1321 *selectedDeviceId = sanitizedRequestedPortId;
1322
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001324 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001325 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001326 if (status != NO_ERROR) {
1327 return status;
1328 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001329 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001330 if (secondaryOutputs != nullptr) {
1331 for (auto &secondaryMix : secondaryMixes) {
1332 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1333 if (outputDesc != nullptr &&
1334 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1335 secondaryOutputs->push_back(outputDesc->mIoHandle);
1336 weakSecondaryOutputDescs.push_back(outputDesc);
1337 }
1338 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001339 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001340
Eric Laurent8fc147b2018-07-22 19:13:55 -07001341 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001342 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001343 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001344 };
jiabin4ef93452019-09-10 14:29:54 -07001345 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001346
Eric Laurentc209fe42020-06-05 18:11:23 -07001347 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001348 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001349 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001350 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001351 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001352 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001353 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001354 std::move(weakSecondaryOutputDescs),
1355 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001356 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001357
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001358 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1359 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001360
Eric Laurente83b55d2014-11-14 10:06:21 -08001361 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001362}
1363
Eric Laurentc529cf62020-04-17 18:19:10 -07001364status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1365 audio_session_t session,
1366 const audio_config_t *config,
1367 audio_output_flags_t flags,
1368 const DeviceVector &devices,
1369 audio_io_handle_t *output) {
1370
1371 *output = AUDIO_IO_HANDLE_NONE;
1372
1373 // skip direct output selection if the request can obviously be attached to a mixed output
1374 // and not explicitly requested
1375 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1376 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1377 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1378 return NAME_NOT_FOUND;
1379 }
1380
1381 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1382 // This prevents creating an offloaded track and tearing it down immediately after start
1383 // when audioflinger detects there is an active non offloadable effect.
1384 // FIXME: We should check the audio session here but we do not have it in this context.
1385 // This may prevent offloading in rare situations where effects are left active by apps
1386 // in the background.
1387 sp<IOProfile> profile;
1388 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1389 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1390 profile = getProfileForOutput(
1391 devices, config->sample_rate, config->format, config->channel_mask,
1392 flags, true /* directOnly */);
1393 }
1394
1395 if (profile == nullptr) {
1396 return NAME_NOT_FOUND;
1397 }
1398
1399 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1400 for (size_t i = 0; i < mOutputs.size(); i++) {
1401 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1402 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1403 // reuse direct output if currently open by the same client
1404 // and configured with same parameters
1405 if ((config->sample_rate == desc->getSamplingRate()) &&
1406 (config->format == desc->getFormat()) &&
1407 (config->channel_mask == desc->getChannelMask()) &&
1408 (session == desc->mDirectClientSession)) {
1409 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001410 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001411 mOutputs.keyAt(i), session);
1412 *output = mOutputs.keyAt(i);
1413 return NO_ERROR;
1414 }
1415 }
1416 }
1417
1418 if (!profile->canOpenNewIo()) {
1419 return NAME_NOT_FOUND;
1420 }
1421
1422 sp<SwAudioOutputDescriptor> outputDesc =
1423 new SwAudioOutputDescriptor(profile, mpClientInterface);
1424
Michael Chan6fb34492020-12-08 15:44:49 +11001425 // An MSD patch may be using the only output stream that can service this request. Release
1426 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001427 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001428
Eric Laurentf1f22e72021-07-13 14:04:14 +02001429 status_t status =
1430 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001431
1432 // only accept an output with the requested parameters
1433 if (status != NO_ERROR ||
1434 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1435 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1436 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1437 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1438 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1439 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1440 config->channel_mask, outputDesc->getChannelMask());
1441 if (*output != AUDIO_IO_HANDLE_NONE) {
1442 outputDesc->close();
1443 }
1444 // fall back to mixer output if possible when the direct output could not be open
1445 if (audio_is_linear_pcm(config->format) &&
1446 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1447 return NAME_NOT_FOUND;
1448 }
1449 *output = AUDIO_IO_HANDLE_NONE;
1450 return BAD_VALUE;
1451 }
1452 outputDesc->mDirectOpenCount = 1;
1453 outputDesc->mDirectClientSession = session;
1454
1455 addOutput(*output, outputDesc);
1456 mPreviousOutputs = mOutputs;
1457 ALOGV("%s returns new direct output %d", __func__, *output);
1458 mpClientInterface->onAudioPortListUpdate();
1459 return NO_ERROR;
1460}
1461
François Gaffie11d30102018-11-02 16:09:09 +01001462audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1463 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001464 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001465 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001466 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001467 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001468 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001469 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001470{
Andy Hungc88b0642018-04-27 15:42:35 -07001471 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001472
jiabine375d412019-02-26 12:54:53 -08001473 // Discard haptic channel mask when forcing muting haptic channels.
1474 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001475 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1476 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001477
Eric Laurente552edb2014-03-10 17:42:56 -07001478 // open a direct output if required by specified parameters
1479 //force direct flag if offload flag is set: offloading implies a direct output stream
1480 // and all common behaviors are driven by checking only the direct flag
1481 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001482 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1483 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001484 }
Nadav Bar766fb022018-01-07 12:18:03 +02001485 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1486 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001487 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001488
1489 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1490
Eric Laurente83b55d2014-11-14 10:06:21 -08001491 // only allow deep buffering for music stream type
1492 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001493 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001494 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001495 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001496 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1497 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001498 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001499 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001500 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001501 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001502 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001503 audio_is_linear_pcm(config->format) &&
1504 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001505 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001506 AUDIO_OUTPUT_FLAG_DIRECT);
1507 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001508 }
Eric Laurente552edb2014-03-10 17:42:56 -07001509
Carter Hsua3abb402021-10-26 11:11:20 +08001510 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1511 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1512 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1513 }
1514
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001515 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001516 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001517 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001518 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001519 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001520 }
1521
Eric Laurentc529cf62020-04-17 18:19:10 -07001522 audio_config_t directConfig = *config;
1523 directConfig.channel_mask = channelMask;
1524 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1525 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001526 return output;
1527 }
1528
Eric Laurent14cbfca2016-03-17 09:42:16 -07001529 // A request for HW A/V sync cannot fallback to a mixed output because time
1530 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001531 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001532 return AUDIO_IO_HANDLE_NONE;
1533 }
1534
Eric Laurente552edb2014-03-10 17:42:56 -07001535 // ignoring channel mask due to downmix capability in mixer
1536
1537 // open a non direct output
1538
1539 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001540 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001541 // get which output is suitable for the specified stream. The actual
1542 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001543 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001544
Eric Laurent8838a382014-09-08 16:44:28 -07001545 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001546 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001547 output = selectOutput(
1548 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001549 }
François Gaffie11d30102018-11-02 16:09:09 +01001550 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001551 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001552 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001553
Eric Laurente552edb2014-03-10 17:42:56 -07001554 return output;
1555}
1556
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001557sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001558 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1559 mAvailableInputDevices);
1560 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1561}
1562
1563DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1564 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1565 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001566}
1567
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001568const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001569 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001570 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1571 if (msdModule != 0) {
1572 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1573 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1574 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1575 const struct audio_port_config *source = &patch->mPatch.sources[j];
1576 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1577 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001578 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001579 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001580 }
1581 }
1582 }
1583 return msdPatches;
1584}
1585
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001586bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1587 ssize_t index = mAudioPatches.indexOfKey(handle);
1588 if (index < 0) {
1589 return false;
1590 }
1591 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1592 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1593 if (msdModule == nullptr) {
1594 return false;
1595 }
1596 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1597 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1598 return true;
1599 }
1600 index = getMsdOutputPatches().indexOfKey(handle);
1601 if (index < 0) {
1602 return false;
1603 }
1604 return true;
1605}
1606
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001607status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1608 const InputProfileCollection &inputProfiles,
1609 const OutputProfileCollection &outputProfiles,
1610 const sp<DeviceDescriptor> &sourceDevice,
1611 const sp<DeviceDescriptor> &sinkDevice,
1612 AudioProfileVector& sourceProfiles,
1613 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001614 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001615 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001616 return NO_INIT;
1617 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001618 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001619 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001620 return NO_INIT;
1621 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1624 inProfile->supportsDevice(sourceDevice)) {
1625 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 }
1627 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001629 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630 outProfile->supportsDevice(sinkDevice)) {
1631 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 }
1633 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001634 return NO_ERROR;
1635}
1636
1637status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1638 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1639 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1640{
Dean Wheatley16809da2022-12-09 14:55:46 +11001641 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1642 static const std::vector<audio_format_t> formatsOrder = {{
1643 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1644 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1645 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1646 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1647 // preferred).
1648 std::vector<audio_channel_mask_t> masks = {{
1649 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1650 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1651 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1652 // insert index masks (higher counts most preferred) as preferred over position masks
1653 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1654 masks.insert(
1655 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1656 }
1657 return masks;
1658 }();
1659
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001660 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001661 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1662 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001663 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001664 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1665 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001666 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001667 }
1668 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1669 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1670 sinkConfig->format = bestSinkConfig.format;
1671 // For encoded streams force direct flag to prevent downstream mixing.
1672 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1673 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001674 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1675 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001676 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001677 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1678 // raw and IEC61937 framed streams.
1679 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1680 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1681 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1683 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001684 sourceConfig->channel_mask =
1685 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1686 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1687 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 sourceConfig->format = bestSinkConfig.format;
1689 // Copy input stream directly without any processing (e.g. resampling).
1690 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1691 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1692 if (hwAvSync) {
1693 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1694 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1695 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1696 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1697 }
1698 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1699 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1700 sinkConfig->config_mask |= config_mask;
1701 sourceConfig->config_mask |= config_mask;
1702 return NO_ERROR;
1703}
1704
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001705PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1706 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707{
1708 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001709 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1710 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1711 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1712 if (deviceModule == nullptr) {
1713 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1714 return patchBuilder;
1715 }
1716 const InputProfileCollection inputProfiles = msdIsSource ?
1717 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1718 const OutputProfileCollection outputProfiles = msdIsSource ?
1719 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1720
1721 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1722 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1723 device : getMsdAudioOutDevices().itemAt(0);
1724 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1725
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1727 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001728 AudioProfileVector sourceProfiles;
1729 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1731 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001732 for (auto hwAvSync : { true, false }) {
1733 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1734 sourceProfiles, sinkProfiles) != NO_ERROR) {
1735 continue;
1736 }
1737 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1738 &sinkConfig) == NO_ERROR) {
1739 // Found a matching config. Re-create PatchBuilder with this config.
1740 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1741 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001743 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001744 " supporting PCM format conversion.", __func__);
1745 return patchBuilder;
1746}
1747
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001748status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001749 DeviceVector devices;
1750 if (outputDevices != nullptr && outputDevices->size() > 0) {
1751 devices.add(*outputDevices);
1752 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001753 // Use media strategy for unspecified output device. This should only
1754 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1755 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001756 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001757 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001758 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001759 }
Michael Chan6fb34492020-12-08 15:44:49 +11001760 std::vector<PatchBuilder> patchesToCreate;
1761 for (auto i = 0u; i < devices.size(); ++i) {
1762 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001763 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001764 }
1765 // Retain only the MSD patches associated with outputDevices request.
1766 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001767 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001768 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1769 auto retainedPatch = false;
1770 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1771 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1772 patchesToRemove.removeItemsAt(i);
1773 retainedPatch = true;
1774 break;
1775 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 }
Michael Chan6fb34492020-12-08 15:44:49 +11001777 if (retainedPatch) {
1778 it = patchesToCreate.erase(it);
1779 continue;
1780 }
1781 ++it;
1782 }
1783 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1784 return NO_ERROR;
1785 }
1786 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1787 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001788 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001789 }
Michael Chan6fb34492020-12-08 15:44:49 +11001790 status_t status = NO_ERROR;
1791 for (const auto &p : patchesToCreate) {
1792 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1793 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1794 char message[256];
1795 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1796 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1797 currStatus == NO_ERROR ? "Success" : "Error",
1798 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1799 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1800 if (currStatus == NO_ERROR) {
1801 ALOGD("%s", message);
1802 } else {
1803 ALOGE("%s", message);
1804 if (status == NO_ERROR) {
1805 status = currStatus;
1806 }
1807 }
1808 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001809 return status;
1810}
1811
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001812void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1813 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001814 for (size_t i = 0; i < msdPatches.size(); i++) {
1815 const auto& patch = msdPatches[i];
1816 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1817 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1818 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1819 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1820 releaseAudioPatch(patch->getHandle(), mUidCached);
1821 break;
1822 }
1823 }
1824 }
1825}
1826
Dorin Drimus94d94412022-02-02 09:05:02 +01001827bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1828 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1829 AudioPatchCollection msdPatches = getMsdOutputPatches();
1830 for (size_t i = 0; i < msdPatches.size(); i++) {
1831 const auto& patch = msdPatches[i];
1832 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1833 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1834 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1835 const auto& foundDevice = devicesToCheck.getDevice(
1836 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1837 if (foundDevice != nullptr) {
1838 devicesToCheck.remove(foundDevice);
1839 if (devicesToCheck.isEmpty()) {
1840 return true;
1841 }
1842 }
1843 }
1844 }
1845 }
1846 return false;
1847}
1848
Eric Laurente0720872014-03-11 09:30:41 -07001849audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001850 audio_output_flags_t flags,
1851 audio_format_t format,
1852 audio_channel_mask_t channelMask,
1853 uint32_t samplingRate,
1854 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001855{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001856 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1857 "%s called with format %#x", __func__, format);
1858
jiabinebb6af42020-06-09 17:31:17 -07001859 // Return the output that haptic-generating attached to when 1) session id is specified,
1860 // 2) haptic-generating effect exists for given session id and 3) the output that
1861 // haptic-generating effect attached to is in given outputs.
1862 if (sessionId != AUDIO_SESSION_NONE) {
1863 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1864 sessionId, FX_IID_HAPTICGENERATOR);
1865 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1866 return hapticGeneratingOutput;
1867 }
1868 }
1869
Eric Laurent16c66dd2019-05-01 17:54:10 -07001870 // Flags disqualifying an output: the match must happen before calling selectOutput()
1871 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1872 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1873
1874 // Flags expressing a functional request: must be honored in priority over
1875 // other criteria
1876 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1877 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001878 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1879 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001880 // Flags expressing a performance request: have lower priority than serving
1881 // requested sampling rate or channel mask
1882 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1883 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1884 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1885
1886 const audio_output_flags_t functionalFlags =
1887 (audio_output_flags_t)(flags & kFunctionalFlags);
1888 const audio_output_flags_t performanceFlags =
1889 (audio_output_flags_t)(flags & kPerformanceFlags);
1890
1891 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1892
Eric Laurente552edb2014-03-10 17:42:56 -07001893 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001894 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001895 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001896 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001898 // with tiebreak preferring the minimum number of extra functional flags
1899 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001900 // 3: the output supporting the exact channel mask
1901 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001902 // 5: the output with the highest sampling rate if the requested sample rate is
1903 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001904 // 6: the output with the highest number of requested performance flags
1905 // 7: the output with the bit depth the closest to the requested one
1906 // 8: the primary output
1907 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001908
Eric Laurent16c66dd2019-05-01 17:54:10 -07001909 // matching criteria values in priority order for best matching output so far
1910 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001911
Eric Laurent16c66dd2019-05-01 17:54:10 -07001912 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1913 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1914 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001915
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001916 for (audio_io_handle_t output : outputs) {
1917 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001918 // matching criteria values in priority order for current output
1919 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001920
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 if (outputDesc->isDuplicated()) {
1922 continue;
1923 }
1924 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1925 continue;
1926 }
Eric Laurent8838a382014-09-08 16:44:28 -07001927
Eric Laurent16c66dd2019-05-01 17:54:10 -07001928 // If haptic channel is specified, use the haptic output if present.
1929 // When using haptic output, same audio format and sample rate are required.
1930 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001931 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1933 continue;
1934 }
1935 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001936 && format == outputDesc->getFormat()
1937 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 currentMatchCriteria[0] = outputHapticChannelCount;
1939 }
1940
1941 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001942 const int matchingFunctionalFlags =
1943 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1944 const int totalFunctionalFlags =
1945 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1946 // Prefer matching functional flags, but subtract unnecessary functional flags.
1947 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001948
1949 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001950 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1951 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001952 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1953 channelCount <= outputChannelCount) {
1954 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001955 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1956 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001957 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001958 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001959 currentMatchCriteria[3] = outputChannelCount;
1960 }
1961
1962 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001963 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001964 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001965 }
1966
1967 // performance flags match
1968 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1969
1970 // format match
1971 if (format != AUDIO_FORMAT_INVALID) {
1972 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001973 PolicyAudioPort::kFormatDistanceMax -
1974 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001975 }
1976
1977 // primary output match
1978 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1979
1980 // compare match criteria by priority then value
1981 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1982 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1983 bestMatchCriteria = currentMatchCriteria;
1984 bestOutput = output;
1985
1986 std::stringstream result;
1987 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1988 std::ostream_iterator<int>(result, " "));
1989 ALOGV("%s new bestOutput %d criteria %s",
1990 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001991 }
1992 }
1993
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001995}
1996
Eric Laurent8fc147b2018-07-22 19:13:55 -07001997status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001998{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001999 ALOGV("%s portId %d", __FUNCTION__, portId);
2000
2001 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2002 if (outputDesc == 0) {
2003 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002004 return BAD_VALUE;
2005 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002006 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002007
Eric Laurent8fc147b2018-07-22 19:13:55 -07002008 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002009 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002010
Eric Laurent733ce942017-12-07 12:18:25 -08002011 status_t status = outputDesc->start();
2012 if (status != NO_ERROR) {
2013 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002014 }
2015
Eric Laurent97ac8712018-07-27 18:59:02 -07002016 uint32_t delayMs;
2017 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002018
2019 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002020 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002021 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002022 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002023 if (delayMs != 0) {
2024 usleep(delayMs * 1000);
2025 }
2026
2027 return status;
2028}
2029
Eric Laurent96d1dda2022-03-14 17:14:19 +01002030bool AudioPolicyManager::isLeUnicastActive() const {
2031 if (isInCall()) {
2032 return true;
2033 }
2034 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2035}
2036
2037bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2038 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2039 return false;
2040 }
2041 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2042 ALOGV("%s active %d", __func__, active);
2043 return active;
2044}
2045
Eric Laurent97ac8712018-07-27 18:59:02 -07002046status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2047 const sp<TrackClientDescriptor>& client,
2048 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002049{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002050 // cannot start playback of STREAM_TTS if any other output is being used
2051 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002052
2053 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002054 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002055 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002056 auto clientStrategy = client->strategy();
2057 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002058 if (stream == AUDIO_STREAM_TTS) {
2059 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002060 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002061 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002062 return INVALID_OPERATION;
2063 } else {
2064 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2065 }
2066 } else {
2067 // some playback other than beacon starts
2068 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2069 }
2070
Eric Laurent77305a62016-07-25 16:39:22 -07002071 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002072 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002073 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002074
François Gaffie11d30102018-11-02 16:09:09 +01002075 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002076 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002077 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002078 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002079 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002080 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002081 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002082 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002083 } else {
2084 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002085 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002086 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2087 AUDIO_FORMAT_DEFAULT);
2088 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2089 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002090 }
2091
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002092 // requiresMuteCheck is false when we can bypass mute strategy.
2093 // It covers a common case when there is no materially active audio
2094 // and muting would result in unnecessary delay and dropped audio.
2095 const uint32_t outputLatencyMs = outputDesc->latency();
2096 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002097 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002098
Eric Laurente552edb2014-03-10 17:42:56 -07002099 // increment usage count for this stream on the requested output:
2100 // NOTE that the usage count is the same for duplicated output and hardware output which is
2101 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002102 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002103
2104 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002105 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2106 client->isPreferredDeviceForExclusiveUse()) {
2107 // Preferred device may be exclusive, use only if no other active clients on this output
2108 devices = DeviceVector(
2109 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2110 } else {
2111 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2112 }
François Gaffie11d30102018-11-02 16:09:09 +01002113 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002114 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002115 }
2116 }
Eric Laurente552edb2014-03-10 17:42:56 -07002117
François Gaffiec005e562018-11-06 15:04:49 +01002118 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002119 selectOutputForMusicEffects();
2120 }
2121
François Gaffie1c878552018-11-22 16:53:21 +01002122 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002123 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002124 if (devices.isEmpty()) {
2125 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002126 }
François Gaffiec005e562018-11-06 15:04:49 +01002127 bool shouldWait =
2128 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2129 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2130 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002131 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002132 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002133 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002134 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002135 // An output has a shared device if
2136 // - managed by the same hw module
2137 // - supports the currently selected device
2138 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002139 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002140
Eric Laurent77305a62016-07-25 16:39:22 -07002141 // force a device change if any other output is:
2142 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002143 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002144 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002145 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002146 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002147 // change the device currently selected by the other output.
2148 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002149 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002150 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002151 force = true;
2152 }
2153 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002154 // a notification so that audio focus effect can propagate, or that a mute/unmute
2155 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002156 const uint32_t latencyMs = desc->latency();
2157 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2158
2159 if (shouldWait && isActive && (waitMs < latencyMs)) {
2160 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002161 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002162
2163 // Require mute check if another output is on a shared device
2164 // and currently active to have proper drain and avoid pops.
2165 // Note restoring AudioTracks onto this output needs to invoke
2166 // a volume ramp if there is no mute.
2167 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002168 }
2169 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002170
2171 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002172 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002173
Eric Laurente552edb2014-03-10 17:42:56 -07002174 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002175 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002176 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002177 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002178 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002179 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002180 outputDesc->useHwGain() /*force*/)) {
2181 // request AudioService to reinitialize the volume curves asynchronously
2182 ALOGE("checkAndSetVolume failed, requesting volume range init");
2183 mpClientInterface->onVolumeRangeInitRequest();
2184 };
Eric Laurente552edb2014-03-10 17:42:56 -07002185
2186 // update the outputs if starting an output with a stream that can affect notification
2187 // routing
2188 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002189
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002190 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002191 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002192 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2193 }
Eric Laurentdc462862016-07-19 12:29:53 -07002194
2195 if (waitMs > muteWaitMs) {
2196 *delayMs = waitMs - muteWaitMs;
2197 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002198
2199 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2200 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2201 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2202 // change occurs after the MixerThread starts and causes a stream volume
2203 // glitch.
2204 //
2205 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002206 }
Eric Laurentdc462862016-07-19 12:29:53 -07002207
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002208 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002209 mEngine->getForceUse(
2210 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002211 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002212 }
2213
Eric Laurent97ac8712018-07-27 18:59:02 -07002214 // Automatically enable the remote submix input when output is started on a re routing mix
2215 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002216 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2217 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002218 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2219 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2220 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002221 "remote-submix",
2222 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002223 }
2224
Eric Laurent96d1dda2022-03-14 17:14:19 +01002225 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2226
Eric Laurente552edb2014-03-10 17:42:56 -07002227 return NO_ERROR;
2228}
2229
Eric Laurent96d1dda2022-03-14 17:14:19 +01002230void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2231 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2232 bool isUnicastActive = isLeUnicastActive();
2233
2234 if (wasUnicastActive != isUnicastActive) {
2235 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2236 for (size_t i = 0; i < mOutputs.size(); i++) {
2237 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2238 if (desc != ignoredOutput && desc->isActive()
2239 && ((isUnicastActive &&
2240 !desc->devices().
2241 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2242 || (wasUnicastActive &&
2243 !desc->devices().getDevicesFromTypes(
2244 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2245 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2246 bool force = desc->devices() != newDevices;
2247 setOutputDevices(desc, newDevices, force, delayMs);
2248 // re-apply device specific volume if not done by setOutputDevice()
2249 if (!force) {
2250 applyStreamVolumes(desc, newDevices.types(), delayMs);
2251 }
2252 }
2253 }
2254 }
2255}
2256
Eric Laurent8fc147b2018-07-22 19:13:55 -07002257status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002258{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002259 ALOGV("%s portId %d", __FUNCTION__, portId);
2260
2261 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2262 if (outputDesc == 0) {
2263 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002264 return BAD_VALUE;
2265 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002266 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002267
Eric Laurent97ac8712018-07-27 18:59:02 -07002268 ALOGV("stopOutput() output %d, stream %d, session %d",
2269 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002270
Eric Laurent97ac8712018-07-27 18:59:02 -07002271 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002272
Eric Laurent733ce942017-12-07 12:18:25 -08002273 if (status == NO_ERROR ) {
2274 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002275 }
2276 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002277}
2278
Eric Laurent97ac8712018-07-27 18:59:02 -07002279status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2280 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002281{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002282 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002283 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002284 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002285 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002286
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002287 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2288
François Gaffie1c878552018-11-22 16:53:21 +01002289 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2290 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002291 // Automatically disable the remote submix input when output is stopped on a
2292 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002293 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002294 if (isSingleDeviceType(
2295 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002296 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002297 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002298 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2299 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002300 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002301 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002302 }
2303 }
2304 bool forceDeviceUpdate = false;
2305 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002306 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002307 forceDeviceUpdate = true;
2308 }
2309
Eric Laurente552edb2014-03-10 17:42:56 -07002310 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002311 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002312
Eric Laurente552edb2014-03-10 17:42:56 -07002313 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002314 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002315 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002316 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002317
2318 // If the routing does not change, if an output is routed on a device using HwGain
2319 // (aka setAudioPortConfig) and there are still active clients following different
2320 // volume group(s), force reapply volume
2321 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2322 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2323
Eric Laurente552edb2014-03-10 17:42:56 -07002324 // delay the device switch by twice the latency because stopOutput() is executed when
2325 // the track stop() command is received and at that time the audio track buffer can
2326 // still contain data that needs to be drained. The latency only covers the audio HAL
2327 // and kernel buffers. Also the latency does not always include additional delay in the
2328 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002329 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2330 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002331
2332 // force restoring the device selection on other active outputs if it differs from the
2333 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002334 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002335 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002336 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002337 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002338 desc->isActive() &&
2339 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002340 (newDevices != desc->devices())) {
2341 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2342 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002343
François Gaffie11d30102018-11-02 16:09:09 +01002344 setOutputDevices(desc, newDevices2, force, delayMs);
2345
Eric Laurent57de36c2016-09-28 16:59:11 -07002346 // re-apply device specific volume if not done by setOutputDevice()
2347 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002348 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002349 }
Eric Laurente552edb2014-03-10 17:42:56 -07002350 }
2351 }
2352 // update the outputs if stopping one with a stream that can affect notification routing
2353 handleNotificationRoutingForStream(stream);
2354 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002355
2356 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2357 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002358 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002359 }
2360
François Gaffiec005e562018-11-06 15:04:49 +01002361 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002362 selectOutputForMusicEffects();
2363 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002364
2365 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2366
Eric Laurente552edb2014-03-10 17:42:56 -07002367 return NO_ERROR;
2368 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002369 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002370 return INVALID_OPERATION;
2371 }
2372}
2373
jiabinbce0c1d2020-10-05 11:20:18 -07002374bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002375{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002376 ALOGV("%s portId %d", __FUNCTION__, portId);
2377
2378 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2379 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002380 // If an output descriptor is closed due to a device routing change,
2381 // then there are race conditions with releaseOutput from tracks
2382 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2383 // destroyed shortly thereafter.
2384 //
2385 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002386 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002387 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002388 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002389
2390 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002391
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302392 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2393 if (outputDesc->isClientActive(client)) {
2394 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2395 stopOutput(portId);
2396 }
2397
Eric Laurent8fc147b2018-07-22 19:13:55 -07002398 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2399 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002400 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002401 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002402 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002403 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002404 if (--outputDesc->mDirectOpenCount == 0) {
2405 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002406 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002407 }
2408 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302409
Andy Hung39efb7a2018-09-26 15:39:28 -07002410 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002411 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2412 // The output is pending reopened to query dynamic profiles and
2413 // there is no active clients
2414 closeOutput(outputDesc->mIoHandle);
2415 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2416 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2417 if (newOutputDesc == nullptr) {
2418 ALOGE("%s failed to open output", __func__);
2419 }
2420 return true;
2421 }
2422 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002423}
2424
Eric Laurentcaf7f482014-11-25 17:50:47 -08002425status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2426 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002427 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002428 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002429 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002430 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002431 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002432 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002433 input_type_t *inputType,
2434 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002435{
François Gaffiec005e562018-11-06 15:04:49 +01002436 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002437 "flags %#x attributes=%s requested device ID %d",
2438 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2439 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002440
Eric Laurentad2e7b92017-09-14 20:06:42 -07002441 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002442 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002443 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002444 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002445 sp<AudioInputDescriptor> inputDesc;
2446 sp<RecordClientDescriptor> clientDesc;
2447 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002448 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002449 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002450
2451 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2452 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2453 return INVALID_OPERATION;
2454 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002455
Francois Gaffie716e1432019-01-14 16:58:59 +01002456 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2457 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002458 }
2459
Paul McLean466dc8e2015-04-17 13:15:36 -06002460 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002461 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002462 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002463
Eric Laurentad2e7b92017-09-14 20:06:42 -07002464 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2465 // possible
2466 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2467 *input != AUDIO_IO_HANDLE_NONE) {
2468 ssize_t index = mInputs.indexOfKey(*input);
2469 if (index < 0) {
2470 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2471 status = BAD_VALUE;
2472 goto error;
2473 }
2474 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002475 RecordClientVector clients = inputDesc->getClientsForSession(session);
2476 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002477 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2478 status = BAD_VALUE;
2479 goto error;
2480 }
2481 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2482 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002483 // corresponds to a new client and is only permitted from the same UID.
2484 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002485 if (clients.size() > 1) {
2486 for (const auto& client : clients) {
2487 // The client map is ordered by key values (portId) and portIds are allocated
2488 // incrementaly. So the first client in this list is the one opened by audio flinger
2489 // when the mmap stream is created and should be ignored as it does not correspond
2490 // to an actual client
2491 if (client == *clients.cbegin()) {
2492 continue;
2493 }
2494 if (uid != client->uid() && !client->isSilenced()) {
2495 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2496 uid, client->portId(), client->uid());
2497 status = INVALID_OPERATION;
2498 goto error;
2499 }
Eric Laurent331679c2018-04-16 17:03:16 -07002500 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002501 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002502 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002503 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002504
Eric Laurentfecbceb2021-02-09 14:46:43 +01002505 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002506 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002507 }
2508
2509 *input = AUDIO_IO_HANDLE_NONE;
2510 *inputType = API_INPUT_INVALID;
2511
Francois Gaffie716e1432019-01-14 16:58:59 +01002512 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2513 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2514 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002515 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002516 ALOGW("%s could not find input mix for attr %s",
2517 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002518 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002519 }
jiabinc1de2df2019-05-07 14:26:40 -07002520 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2521 String8(attr->tags + strlen("addr=")),
2522 AUDIO_FORMAT_DEFAULT);
2523 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002524 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002525 __func__, attributes.source, attributes.tags);
2526 status = BAD_VALUE;
2527 goto error;
2528 }
2529
Kevin Rocard25f9b052019-02-27 15:08:54 -08002530 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2531 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2532 } else {
2533 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2534 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002535 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002536 if (explicitRoutingDevice != nullptr) {
2537 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002539 // Prevent from storing invalid requested device id in clients
2540 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002541 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002542 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2543 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002544 }
François Gaffie11d30102018-11-02 16:09:09 +01002545 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002546 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002547 status = BAD_VALUE;
2548 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002549 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002550 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2551 *inputType = API_INPUT_MIX_CAPTURE;
2552 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002553 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2554 // there is an external policy, but this input is attached to a mix of recorders,
2555 // meaning it receives audio injected into the framework, so the recorder doesn't
2556 // know about it and is therefore considered "legacy"
2557 *inputType = API_INPUT_LEGACY;
2558 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002559 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002560 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002561 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002562 } else {
2563 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002564 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002565
Eric Laurent599c7582015-12-07 18:05:55 -08002566 }
2567
François Gaffiec005e562018-11-06 15:04:49 +01002568 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002569 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002570 status = INVALID_OPERATION;
2571 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002572 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002573
Eric Laurent8f42ea12018-08-08 09:08:25 -07002574exit:
2575
François Gaffiec005e562018-11-06 15:04:49 +01002576 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2577 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002578
Francois Gaffie716e1432019-01-14 16:58:59 +01002579 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002580 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002581 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002582
Mikhail Naganov2996f672019-04-18 12:29:59 -07002583 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002584 requestedDeviceId, attributes.source, flags,
2585 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002586 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002587 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002588
2589 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2590 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002591
Eric Laurent599c7582015-12-07 18:05:55 -08002592 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002593
2594error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002595 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002596}
2597
2598
François Gaffie11d30102018-11-02 16:09:09 +01002599audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002600 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002601 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002602 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002603 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002604 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002605{
2606 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002607 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002608 bool isSoundTrigger = false;
2609
François Gaffiec005e562018-11-06 15:04:49 +01002610 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002611 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2612 if (index >= 0) {
2613 input = mSoundTriggerSessions.valueFor(session);
2614 isSoundTrigger = true;
2615 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2616 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2617 } else {
2618 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002619 }
François Gaffiec005e562018-11-06 15:04:49 +01002620 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002621 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002622 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002623 }
2624
Carter Hsua3abb402021-10-26 11:11:20 +08002625 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2626 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2627 }
2628
Andy Hungf129b032015-04-07 13:45:50 -07002629 // find a compatible input profile (not necessarily identical in parameters)
2630 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002631 // sampling rate and flags may be updated by getInputProfile
2632 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2633 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002634 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002635 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002636 audio_input_flags_t profileFlags = flags;
2637 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002638 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002639 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002640 profileFlags);
2641 if (profile != 0) {
2642 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002643 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2644 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002645 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002646 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2647 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002648 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002649 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002650 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002651 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002652 }
Eric Laurente552edb2014-03-10 17:42:56 -07002653 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002654 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002655 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002656 if (samplingRate == 0) {
2657 samplingRate = profileSamplingRate;
2658 }
Eric Laurente552edb2014-03-10 17:42:56 -07002659
Eric Laurent322b4d22015-04-03 15:57:54 -07002660 if (profile->getModuleHandle() == 0) {
2661 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002662 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002663 }
2664
Eric Laurentec376dc2021-04-08 20:41:22 +02002665 // Reuse an already opened input if a client with the same session ID already exists
2666 // on that input
2667 for (size_t i = 0; i < mInputs.size(); i++) {
2668 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2669 if (desc->mProfile != profile) {
2670 continue;
2671 }
2672 RecordClientVector clients = desc->clientsList();
2673 for (const auto &client : clients) {
2674 if (session == client->session()) {
2675 return desc->mIoHandle;
2676 }
2677 }
2678 }
2679
Eric Laurent3974e3b2017-12-07 17:58:43 -08002680 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002681 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002682 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002683 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002684 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002685 continue;
2686 }
2687 // if sound trigger, reuse input if used by other sound trigger on same session
2688 // else
2689 // reuse input if active client app is not in IDLE state
2690 //
2691 RecordClientVector clients = desc->clientsList();
2692 bool doClose = false;
2693 for (const auto& client : clients) {
2694 if (isSoundTrigger != client->isSoundTrigger()) {
2695 continue;
2696 }
2697 if (client->isSoundTrigger()) {
2698 if (session == client->session()) {
2699 return desc->mIoHandle;
2700 }
2701 continue;
2702 }
2703 if (client->active() && client->appState() != APP_STATE_IDLE) {
2704 return desc->mIoHandle;
2705 }
2706 doClose = true;
2707 }
2708 if (doClose) {
2709 closeInput(desc->mIoHandle);
2710 } else {
2711 i++;
2712 }
2713 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002714 }
2715
Eric Laurentfe231122017-11-17 17:48:06 -08002716 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002717
Eric Laurentfe231122017-11-17 17:48:06 -08002718 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2719 lConfig.sample_rate = profileSamplingRate;
2720 lConfig.channel_mask = profileChannelMask;
2721 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002722
François Gaffie11d30102018-11-02 16:09:09 +01002723 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002724
2725 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002726 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002727 (profileSamplingRate != lConfig.sample_rate) ||
2728 !audio_formats_match(profileFormat, lConfig.format) ||
2729 (profileChannelMask != lConfig.channel_mask)) {
2730 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002731 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002732 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002733 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002734 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002735 }
Eric Laurent599c7582015-12-07 18:05:55 -08002736 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002737 }
2738
Eric Laurentc722f302014-12-10 11:21:49 -08002739 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002740
Eric Laurent599c7582015-12-07 18:05:55 -08002741 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002742 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002743
Eric Laurent599c7582015-12-07 18:05:55 -08002744 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002745}
2746
Eric Laurent4eb58f12018-12-07 16:41:02 -08002747status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002748{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002749 ALOGV("%s portId %d", __FUNCTION__, portId);
2750
2751 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2752 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002753 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002754 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002755 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002756 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002757 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 if (client->active()) {
2759 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2760 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002761 }
2762
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763 audio_session_t session = client->session();
2764
Eric Laurent4eb58f12018-12-07 16:41:02 -08002765 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002766
Eric Laurent4eb58f12018-12-07 16:41:02 -08002767 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002768
Eric Laurent4eb58f12018-12-07 16:41:02 -08002769 status_t status = inputDesc->start();
2770 if (status != NO_ERROR) {
2771 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002772 }
Eric Laurente552edb2014-03-10 17:42:56 -07002773
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002774 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002775 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002776 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002777
Eric Laurent8f42ea12018-08-08 09:08:25 -07002778 // indicate active capture to sound trigger service if starting capture from a mic on
2779 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002780 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002781 if (device != nullptr) {
2782 status = setInputDevice(input, device, true /* force */);
2783 } else {
2784 ALOGW("%s no new input device can be found for descriptor %d",
2785 __FUNCTION__, inputDesc->getId());
2786 status = BAD_VALUE;
2787 }
Eric Laurente552edb2014-03-10 17:42:56 -07002788
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002789 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002790 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002791 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002792 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002793 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2794 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002796 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002797
François Gaffie11d30102018-11-02 16:09:09 +01002798 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2799 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002800 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002801 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002802 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002803
Eric Laurent8f42ea12018-08-08 09:08:25 -07002804 // automatically enable the remote submix output when input is started if not
2805 // used by a policy mix of type MIX_TYPE_RECORDERS
2806 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002807 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002808 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002809 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002810 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002811 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2812 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002813 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002814 if (address != "") {
2815 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2816 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002817 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002818 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002819 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002820 } else if (status != NO_ERROR) {
2821 // Restore client activity state.
2822 inputDesc->setClientActive(client, false);
2823 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002824 }
2825
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002826 ALOGV("%s input %d source = %d status = %d exit",
2827 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002828
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002829 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002830}
2831
Eric Laurent8fc147b2018-07-22 19:13:55 -07002832status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002833{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 ALOGV("%s portId %d", __FUNCTION__, portId);
2835
2836 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2837 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002838 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002839 return BAD_VALUE;
2840 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002841 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002842 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002843 if (!client->active()) {
2844 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002845 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002846 }
Carter Hsue6139d52021-07-08 10:30:20 +08002847 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002848 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002849
Eric Laurent8f42ea12018-08-08 09:08:25 -07002850 inputDesc->stop();
2851 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002852 auto current_source = inputDesc->source();
2853 setInputDevice(input, getNewInputDevice(inputDesc),
2854 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002856 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002857 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002858 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002859 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2860 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002861 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002862 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002863
2864 // automatically disable the remote submix output when input is stopped if not
2865 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002866 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002867 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002868 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002870 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2871 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 }
2873 if (address != "") {
2874 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2875 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002876 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002877 }
2878 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879 resetInputDevice(input);
2880
2881 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2882 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002883 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2884 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002885 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002886 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002887 }
2888 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002889 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002890 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002891}
2892
Eric Laurent8fc147b2018-07-22 19:13:55 -07002893void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002894{
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 Laurente552edb2014-03-10 17:42:56 -07002900 return;
2901 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002902 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002903 audio_io_handle_t input = inputDesc->mIoHandle;
2904
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002906
Andy Hung39efb7a2018-09-26 15:39:28 -07002907 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002908
Andy Hung39efb7a2018-09-26 15:39:28 -07002909 if (inputDesc->getClientCount() > 0) {
2910 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002911 return;
2912 }
2913
Eric Laurent05b90f82014-08-27 15:32:29 -07002914 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002915 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002917}
2918
Eric Laurent8f42ea12018-08-08 09:08:25 -07002919void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002920{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002921 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002922
2923 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002924 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002925 }
2926}
2927
Eric Laurent8f42ea12018-08-08 09:08:25 -07002928void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2929{
2930 stopInput(portId);
2931 releaseInput(portId);
2932}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002933
Eric Laurent0dd51852019-04-19 18:18:58 -07002934void AudioPolicyManager::checkCloseInputs() {
2935 // After connecting or disconnecting an input device, close input if:
2936 // - it has no client (was just opened to check profile) OR
2937 // - none of its supported devices are connected anymore OR
2938 // - one of its clients cannot be routed to one of its supported
2939 // devices anymore. Otherwise update device selection
2940 std::vector<audio_io_handle_t> inputsToClose;
2941 for (size_t i = 0; i < mInputs.size(); i++) {
2942 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2943 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002944 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002945 inputsToClose.push_back(mInputs.keyAt(i));
2946 } else {
2947 bool close = false;
2948 for (const auto& client : input->clientsList()) {
2949 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002950 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002951 if (!input->supportedDevices().contains(device)) {
2952 close = true;
2953 break;
2954 }
2955 }
2956 if (close) {
2957 inputsToClose.push_back(mInputs.keyAt(i));
2958 } else {
2959 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2960 }
2961 }
2962 }
2963
2964 for (const audio_io_handle_t handle : inputsToClose) {
2965 ALOGV("%s closing input %d", __func__, handle);
2966 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002967 }
Eric Laurentd4692962014-05-05 18:13:44 -07002968}
2969
François Gaffie251c7f02018-11-07 10:41:08 +01002970void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002971{
2972 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002973 if (indexMin < 0 || indexMax < 0) {
2974 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2975 return;
2976 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002977 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002978
2979 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002980 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2981 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002982 continue;
2983 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002984 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002985 }
Eric Laurente552edb2014-03-10 17:42:56 -07002986}
2987
Eric Laurente0720872014-03-11 09:30:41 -07002988status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002989 int index,
2990 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002991{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002992 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002993 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2994 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2995 return NO_ERROR;
2996 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997 ALOGV("%s: stream %s attributes=%s", __func__,
2998 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002999 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003000}
3001
Eric Laurente0720872014-03-11 09:30:41 -07003002status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003003 int *index,
3004 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003005{
François Gaffiec005e562018-11-06 15:04:49 +01003006 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3007 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003008 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003009 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003010 deviceTypes = mEngine->getOutputDevicesForStream(
3011 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003012 }
jiabin9a3361e2019-10-01 09:38:30 -07003013 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003014}
3015
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003016status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003017 int index,
3018 audio_devices_t device)
3019{
3020 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003021 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3022 if (group == VOLUME_GROUP_NONE) {
3023 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003024 return BAD_VALUE;
3025 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003026 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003027 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003028 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003029 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003030 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3031 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3032 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3033 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003034 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3035
3036 status = setVolumeCurveIndex(index, device, curves);
3037 if (status != NO_ERROR) {
3038 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3039 return status;
3040 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003041
jiabin9a3361e2019-10-01 09:38:30 -07003042 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003043 auto curCurvAttrs = curves.getAttributes();
3044 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3045 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003046 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003047 } else if (!curves.getStreamTypes().empty()) {
3048 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003049 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003050 } else {
3051 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3052 return BAD_VALUE;
3053 }
jiabin9a3361e2019-10-01 09:38:30 -07003054 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3055 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003056
François Gaffiecfe17322018-11-07 13:41:29 +01003057 // update volume on all outputs and streams matching the following:
3058 // - The requested stream (or a stream matching for volume control) is active on the output
3059 // - The device (or devices) selected by the engine for this stream includes
3060 // the requested device
3061 // - For non default requested device, currently selected device on the output is either the
3062 // requested device or one of the devices selected by the engine for this stream
3063 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3064 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003065 for (size_t i = 0; i < mOutputs.size(); i++) {
3066 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003067 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003068
jiabin9a3361e2019-10-01 09:38:30 -07003069 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3070 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003071 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003072
3073 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003074 continue;
3075 }
3076 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3077 curDevices.find(device) == curDevices.end()) {
3078 continue;
3079 }
3080 bool applyVolume = false;
3081 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3082 curSrcDevices.insert(device);
3083 applyVolume = (curSrcDevices.find(
3084 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3085 } else {
3086 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3087 }
3088 if (!applyVolume) {
3089 continue; // next output
3090 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003091 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3092 // If a higher priority strategy is active, and the output is routed to a device with a
3093 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003094 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003095 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003096 // If the volume source is active with higher priority source, ensure at least Sw Muted
3097 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003098 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3099 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3100 false /*preferredDevice*/);
3101 if (activeClients.empty()) {
3102 continue;
3103 }
3104 bool isPreempted = false;
3105 bool isHigherPriority = productStrategy < strategy;
3106 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003107 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003108 ALOGV("%s: Strategy=%d (\nrequester:\n"
3109 " group %d, volumeGroup=%d attributes=%s)\n"
3110 " higher priority source active:\n"
3111 " volumeGroup=%d attributes=%s) \n"
3112 " on output %zu, bailing out", __func__, productStrategy,
3113 group, group, toString(attributes).c_str(),
3114 client->volumeSource(), toString(client->attributes()).c_str(), i);
3115 applyVolume = false;
3116 isPreempted = true;
3117 break;
3118 }
3119 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003120 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003121 applyVolume = true;
3122 }
3123 }
3124 if (isPreempted || applyVolume) {
3125 break;
3126 }
3127 }
3128 if (!applyVolume) {
3129 continue; // next output
3130 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003131 }
François Gaffieed91f582020-01-31 10:35:37 +01003132 //FIXME: workaround for truncated touch sounds
3133 // delayed volume change for system stream to be removed when the problem is
3134 // handled by system UI
3135 status_t volStatus = checkAndSetVolume(
3136 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003137 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003138 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3139 if (volStatus != NO_ERROR) {
3140 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003141 }
3142 }
François Gaffiecfe17322018-11-07 13:41:29 +01003143 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3144 return status;
3145}
3146
François Gaffieaaac0fd2018-11-22 17:56:39 +01003147status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003148 audio_devices_t device,
3149 IVolumeCurves &volumeCurves)
3150{
3151 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3152 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003153 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3154 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003155 (index > volumeCurves.getVolumeIndexMax())) {
3156 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3157 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3158 return BAD_VALUE;
3159 }
3160 if (!audio_is_output_device(device)) {
3161 return BAD_VALUE;
3162 }
3163
3164 // Force max volume if stream cannot be muted
3165 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3166
François Gaffieaaac0fd2018-11-22 17:56:39 +01003167 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003168 volumeCurves.addCurrentVolumeIndex(device, index);
3169 return NO_ERROR;
3170}
3171
3172status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3173 int &index,
3174 audio_devices_t device)
3175{
3176 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3177 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003178 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003179 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003180 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003181 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003182 }
jiabin9a3361e2019-10-01 09:38:30 -07003183 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003184}
3185
3186status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3187 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003188 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003189{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003190 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003191 return BAD_VALUE;
3192 }
jiabin9a3361e2019-10-01 09:38:30 -07003193 index = curves.getVolumeIndex(deviceTypes);
3194 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003195 return NO_ERROR;
3196}
3197
3198status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3199 int &index)
3200{
3201 index = getVolumeCurves(attr).getVolumeIndexMin();
3202 return NO_ERROR;
3203}
3204
3205status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3206 int &index)
3207{
3208 index = getVolumeCurves(attr).getVolumeIndexMax();
3209 return NO_ERROR;
3210}
3211
Eric Laurent36829f92017-04-07 19:04:42 -07003212audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003213{
3214 // select one output among several suitable for global effects.
3215 // The priority is as follows:
3216 // 1: An offloaded output. If the effect ends up not being offloadable,
3217 // AudioFlinger will invalidate the track and the offloaded output
3218 // will be closed causing the effect to be moved to a PCM output.
3219 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003220 // 3: The primary output
3221 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003222
François Gaffiec005e562018-11-06 15:04:49 +01003223 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3224 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003225 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003226
Eric Laurent36829f92017-04-07 19:04:42 -07003227 if (outputs.size() == 0) {
3228 return AUDIO_IO_HANDLE_NONE;
3229 }
Eric Laurente552edb2014-03-10 17:42:56 -07003230
Eric Laurent36829f92017-04-07 19:04:42 -07003231 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3232 bool activeOnly = true;
3233
3234 while (output == AUDIO_IO_HANDLE_NONE) {
3235 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3236 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3237 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3238
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003239 for (audio_io_handle_t output : outputs) {
3240 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003241 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003242 continue;
3243 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003244 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3245 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003246 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003247 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003248 }
3249 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003250 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003251 }
3252 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003253 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003254 }
3255 }
3256 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3257 output = outputOffloaded;
3258 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3259 output = outputDeepBuffer;
3260 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3261 output = outputPrimary;
3262 } else {
3263 output = outputs[0];
3264 }
3265 activeOnly = false;
3266 }
3267
3268 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003269 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003270 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3271 mMusicEffectOutput = output;
3272 }
3273
3274 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003275 return output;
3276}
3277
Eric Laurent36829f92017-04-07 19:04:42 -07003278audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3279{
3280 return selectOutputForMusicEffects();
3281}
3282
Eric Laurente0720872014-03-11 09:30:41 -07003283status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003284 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003285 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003286 int session,
3287 int id)
3288{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003289 if (session != AUDIO_SESSION_DEVICE) {
3290 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003291 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003292 index = mInputs.indexOfKey(io);
3293 if (index < 0) {
3294 ALOGW("registerEffect() unknown io %d", io);
3295 return INVALID_OPERATION;
3296 }
Eric Laurente552edb2014-03-10 17:42:56 -07003297 }
3298 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003299 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3300 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3301 || strategy == PRODUCT_STRATEGY_NONE));
3302 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003303}
3304
Eric Laurentc241b0d2018-11-28 09:08:49 -08003305status_t AudioPolicyManager::unregisterEffect(int id)
3306{
3307 if (mEffects.getEffect(id) == nullptr) {
3308 return INVALID_OPERATION;
3309 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003310 if (mEffects.isEffectEnabled(id)) {
3311 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3312 setEffectEnabled(id, false);
3313 }
3314 return mEffects.unregisterEffect(id);
3315}
3316
3317status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3318{
3319 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3320 if (effect == nullptr) {
3321 return INVALID_OPERATION;
3322 }
3323
3324 status_t status = mEffects.setEffectEnabled(id, enabled);
3325 if (status == NO_ERROR) {
3326 mInputs.trackEffectEnabled(effect, enabled);
3327 }
3328 return status;
3329}
3330
Eric Laurent6c796322019-04-09 14:13:17 -07003331
3332status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3333{
3334 mEffects.moveEffects(ids, io);
3335 return NO_ERROR;
3336}
3337
Eric Laurentc75307b2015-03-17 15:29:32 -07003338bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3339{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003340 auto vs = toVolumeSource(stream, false);
3341 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003342}
3343
3344bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3345{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003346 auto vs = toVolumeSource(stream, false);
3347 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003348}
3349
Eric Laurente0720872014-03-11 09:30:41 -07003350bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003351{
3352 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003353 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003354 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003355 return true;
3356 }
3357 }
3358 return false;
3359}
3360
Eric Laurent275e8e92014-11-30 15:14:47 -08003361// Register a list of custom mixes with their attributes and format.
3362// When a mix is registered, corresponding input and output profiles are
3363// added to the remote submix hw module. The profile contains only the
3364// parameters (sampling rate, format...) specified by the mix.
3365// The corresponding input remote submix device is also connected.
3366//
3367// When a remote submix device is connected, the address is checked to select the
3368// appropriate profile and the corresponding input or output stream is opened.
3369//
3370// When capture starts, getInputForAttr() will:
3371// - 1 look for a mix matching the address passed in attribtutes tags if any
3372// - 2 if none found, getDeviceForInputSource() will:
3373// - 2.1 look for a mix matching the attributes source
3374// - 2.2 if none found, default to device selection by policy rules
3375// At this time, the corresponding output remote submix device is also connected
3376// and active playback use cases can be transferred to this mix if needed when reconnecting
3377// after AudioTracks are invalidated
3378//
3379// When playback starts, getOutputForAttr() will:
3380// - 1 look for a mix matching the address passed in attribtutes tags if any
3381// - 2 if none found, look for a mix matching the attributes usage
3382// - 3 if none found, default to device and output selection by policy rules.
3383
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003384status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003385{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003386 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3387 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003388 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003389 sp<HwModule> rSubmixModule;
3390 // examine each mix's route type
3391 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003392 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003393 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3394 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3395 ALOGE("Unsupported Policy Mix %zu of %zu: "
3396 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3397 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003398 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003399 break;
3400 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003401 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3402 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003403 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003404 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3405 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003406 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003407 rSubmixModule = mHwModules.getModuleFromName(
3408 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3409 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003410 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003411 i);
3412 res = INVALID_OPERATION;
3413 break;
3414 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003415 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003416
Eric Laurent97ac8712018-07-27 18:59:02 -07003417 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003418 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003419 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003420 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003421 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3422 } else {
3423 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3424 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003425 }
François Gaffie036e1e92015-03-19 10:16:24 +01003426
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003427 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003428 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003429 res = INVALID_OPERATION;
3430 break;
3431 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003432 audio_config_t outputConfig = mix.mFormat;
3433 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003434 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3435 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003436 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3437 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003438 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003439 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003440 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003441 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003442
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003443 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003444 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3445 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3446 ALOGE("Failed to set remote submix device available, type %u, address %s",
3447 mix.mDeviceType, address.string());
3448 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003449 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003450 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3451 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003452 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003453 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003454 i, mixes.size(), type, address.string());
3455
3456 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3457 mix.mDeviceType, mix.mDeviceAddress,
3458 String8(), AUDIO_FORMAT_DEFAULT);
3459 if (device == nullptr) {
3460 res = INVALID_OPERATION;
3461 break;
3462 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003463
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003464 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003465 // First try to find an already opened output supporting the device
3466 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003468
Eric Laurentc529cf62020-04-17 18:19:10 -07003469 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003470 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003471 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3472 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003473 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003474 } else {
3475 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003476 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003477 }
3478 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003479 // If no output found, try to find a direct output profile supporting the device
3480 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3481 sp<HwModule> module = mHwModules[i];
3482 for (size_t j = 0;
3483 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3484 j++) {
3485 sp<IOProfile> profile = module->getOutputProfiles()[j];
3486 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3487 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3488 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3489 address.string());
3490 res = INVALID_OPERATION;
3491 } else {
3492 foundOutput = true;
3493 }
3494 }
3495 }
3496 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003497 if (res != NO_ERROR) {
3498 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003499 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003500 res = INVALID_OPERATION;
3501 break;
3502 } else if (!foundOutput) {
3503 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003504 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003505 res = INVALID_OPERATION;
3506 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003507 } else {
3508 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003509 }
Eric Laurentc722f302014-12-10 11:21:49 -08003510 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003511 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003512 if (res != NO_ERROR) {
3513 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003514 } else if (checkOutputs) {
3515 checkForDeviceAndOutputChanges();
3516 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003517 }
3518 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003519}
3520
3521status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3522{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003523 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003524 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003525 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003526 sp<HwModule> rSubmixModule;
3527 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003528 for (const auto& mix : mixes) {
3529 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003530
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003531 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003532 rSubmixModule = mHwModules.getModuleFromName(
3533 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3534 if (rSubmixModule == 0) {
3535 res = INVALID_OPERATION;
3536 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003537 }
3538 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003539
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003540 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003541
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003542 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 res = INVALID_OPERATION;
3544 continue;
3545 }
3546
Kevin Rocard04ed0462019-05-02 17:53:24 -07003547 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3548 if (getDeviceConnectionState(device, address.string()) ==
3549 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3550 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3551 address.string(), "remote-submix",
3552 AUDIO_FORMAT_DEFAULT);
3553 if (res != OK) {
3554 ALOGE("Error making RemoteSubmix device unavailable for mix "
3555 "with type %d, address %s", device, address.string());
3556 }
3557 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003558 }
jiabin5740f082019-08-19 15:08:30 -07003559 rSubmixModule->removeOutputProfile(address.c_str());
3560 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003561
Kevin Rocard153f92d2018-12-18 18:33:28 -08003562 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003563 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003564 res = INVALID_OPERATION;
3565 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003566 } else {
3567 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003568 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003569 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003570 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003571 if (res == NO_ERROR && checkOutputs) {
3572 checkForDeviceAndOutputChanges();
3573 updateCallAndOutputRouting();
3574 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003575 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003576}
3577
Mikhail Naganov100f0122018-11-29 11:22:16 -08003578void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3579{
3580 size_t i = 0;
3581 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3582 for (const auto& fmt : mManualSurroundFormats) {
3583 if (i++ != 0) dst->append(", ");
3584 std::string sfmt;
3585 FormatConverter::toString(fmt, sfmt);
3586 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3587 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3588 }
3589}
3590
Eric Laurentc529cf62020-04-17 18:19:10 -07003591// Returns true if all devices types match the predicate and are supported by one HW module
3592bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003593 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003594 std::function<bool(audio_devices_t)> predicate,
3595 const char *context) {
3596 for (size_t i = 0; i < devices.size(); i++) {
3597 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003598 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003599 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003600 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003601 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003602 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003603 return false;
3604 }
3605 }
3606 return true;
3607}
3608
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003609status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003610 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003611 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003612 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3613 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003614 }
3615 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003616 if (res != NO_ERROR) {
3617 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3618 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003619 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003620
3621 checkForDeviceAndOutputChanges();
3622 updateCallAndOutputRouting();
3623
3624 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003625}
3626
3627status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3628 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003629 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3630 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003631 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003632 __FUNCTION__, uid);
3633 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003634 }
3635
Eric Laurentc529cf62020-04-17 18:19:10 -07003636 checkForDeviceAndOutputChanges();
3637 updateCallAndOutputRouting();
3638
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003639 return res;
3640}
3641
Eric Laurent2517af32020-11-25 15:31:27 +01003642
jiabin0a488932020-08-07 17:32:40 -07003643status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3644 device_role_t role,
3645 const AudioDeviceTypeAddrVector &devices) {
3646 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3647 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003648
Eric Laurentc529cf62020-04-17 18:19:10 -07003649 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003650 return BAD_VALUE;
3651 }
jiabin0a488932020-08-07 17:32:40 -07003652 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003653 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003654 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3655 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003656 return status;
3657 }
3658
3659 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003660
3661 bool forceVolumeReeval = false;
3662 // FIXME: workaround for truncated touch sounds
3663 // to be removed when the problem is handled by system UI
3664 uint32_t delayMs = 0;
3665 if (strategy == mCommunnicationStrategy) {
3666 forceVolumeReeval = true;
3667 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3668 updateInputRouting();
3669 }
3670 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003671
3672 return NO_ERROR;
3673}
3674
3675void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3676{
3677 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003678 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003679 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003680 // Only apply special touch sound delay once
3681 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003682 }
3683 for (size_t i = 0; i < mOutputs.size(); i++) {
3684 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3685 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003686 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3687 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003688 // As done in setDeviceConnectionState, we could also fix default device issue by
3689 // preventing the force re-routing in case of default dev that distinguishes on address.
3690 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003691 bool forceRouting = !newDevices.isEmpty();
3692 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3693 true /*requiresMuteCheck*/,
3694 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003695 // Only apply special touch sound delay once
3696 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003697 }
3698 if (forceVolumeReeval && !newDevices.isEmpty()) {
3699 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3700 }
3701 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003702 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003703}
3704
Eric Laurent2517af32020-11-25 15:31:27 +01003705void AudioPolicyManager::updateInputRouting() {
3706 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303707 // Skip for hotword recording as the input device switch
3708 // is handled within sound trigger HAL
3709 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3710 continue;
3711 }
Eric Laurent2517af32020-11-25 15:31:27 +01003712 auto newDevice = getNewInputDevice(activeDesc);
3713 // Force new input selection if the new device can not be reached via current input
3714 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3715 setInputDevice(activeDesc->mIoHandle, newDevice);
3716 } else {
3717 closeInput(activeDesc->mIoHandle);
3718 }
3719 }
3720}
3721
jiabin0a488932020-08-07 17:32:40 -07003722status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3723 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003724{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003725 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003726
jiabin0a488932020-08-07 17:32:40 -07003727 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003728 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003729 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3730 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003731 return status;
3732 }
3733
3734 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003735
3736 bool forceVolumeReeval = false;
3737 // FIXME: workaround for truncated touch sounds
3738 // to be removed when the problem is handled by system UI
3739 uint32_t delayMs = 0;
3740 if (strategy == mCommunnicationStrategy) {
3741 forceVolumeReeval = true;
3742 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3743 updateInputRouting();
3744 }
3745 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003746
3747 return NO_ERROR;
3748}
3749
jiabin0a488932020-08-07 17:32:40 -07003750status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3751 device_role_t role,
3752 AudioDeviceTypeAddrVector &devices) {
3753 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003754}
3755
Jiabin Huang3b98d322020-09-03 17:54:16 +00003756status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3757 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3758 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3759 dumpAudioDeviceTypeAddrVector(devices).c_str());
3760
Mikhail Naganov55773032020-10-01 15:08:13 -07003761 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003762 return BAD_VALUE;
3763 }
3764 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3765 ALOGW_IF(status != NO_ERROR,
3766 "Engine could not set preferred devices %s for audio source %d role %d",
3767 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3768
3769 return status;
3770}
3771
3772status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3773 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3774 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3775 dumpAudioDeviceTypeAddrVector(devices).c_str());
3776
Mikhail Naganov55773032020-10-01 15:08:13 -07003777 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003778 return BAD_VALUE;
3779 }
3780 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3781 ALOGW_IF(status != NO_ERROR,
3782 "Engine could not add preferred devices %s for audio source %d role %d",
3783 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3784
Eric Laurent2517af32020-11-25 15:31:27 +01003785 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003786 return status;
3787}
3788
3789status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3790 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3791{
3792 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3793 dumpAudioDeviceTypeAddrVector(devices).c_str());
3794
Mikhail Naganov55773032020-10-01 15:08:13 -07003795 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003796 return BAD_VALUE;
3797 }
3798
3799 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3800 audioSource, role, devices);
3801 ALOGW_IF(status != NO_ERROR,
3802 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3803
Eric Laurent2517af32020-11-25 15:31:27 +01003804 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003805 return status;
3806}
3807
3808status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3809 device_role_t role) {
3810 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3811
3812 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3813 ALOGW_IF(status != NO_ERROR,
3814 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3815
Eric Laurent2517af32020-11-25 15:31:27 +01003816 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003817 return status;
3818}
3819
3820status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3821 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3822 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3823}
3824
Oscar Azucena90e77632019-11-27 17:12:28 -08003825status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003826 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003827 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003828 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3829 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003830 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003831 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3832 if (status != NO_ERROR) {
3833 ALOGE("%s() could not set device affinity for userId %d",
3834 __FUNCTION__, userId);
3835 return status;
3836 }
3837
3838 // reevaluate outputs for all devices
3839 checkForDeviceAndOutputChanges();
3840 updateCallAndOutputRouting();
3841
3842 return NO_ERROR;
3843}
3844
3845status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003846 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003847 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3848 if (status != NO_ERROR) {
3849 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3850 __FUNCTION__, userId);
3851 return status;
3852 }
3853
3854 // reevaluate outputs for all devices
3855 checkForDeviceAndOutputChanges();
3856 updateCallAndOutputRouting();
3857
3858 return NO_ERROR;
3859}
3860
Andy Hungc29d82b2018-10-05 12:23:17 -07003861void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003862{
Andy Hungc29d82b2018-10-05 12:23:17 -07003863 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003864 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003865 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003866 std::string stateLiteral;
3867 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003868 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003869 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3870 "communications", "media", "record", "dock", "system",
3871 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3872 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3873 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003874 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3875 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3876 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3877 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3878 dst->append(" (MANUAL: ");
3879 dumpManualSurroundFormats(dst);
3880 dst->append(")");
3881 }
3882 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003883 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003884 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3885 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003886 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003887 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003888
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003889 dst->append("\n");
3890 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3891 dst->append("\n");
3892 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003893 mHwModulesAll.dump(dst);
3894 mOutputs.dump(dst);
3895 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003896 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003897 mAudioPatches.dump(dst);
3898 mPolicyMixes.dump(dst);
3899 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003900
Kevin Rocardb99cc752019-03-21 20:52:24 -07003901 dst->appendFormat(" AllowedCapturePolicies:\n");
3902 for (auto& policy : mAllowedCapturePolicies) {
3903 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3904 }
3905
François Gaffiec005e562018-11-06 15:04:49 +01003906 dst->appendFormat("\nPolicy Engine dump:\n");
3907 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003908}
3909
3910status_t AudioPolicyManager::dump(int fd)
3911{
3912 String8 result;
3913 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003914 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003915 return NO_ERROR;
3916}
3917
Kevin Rocardb99cc752019-03-21 20:52:24 -07003918status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3919{
3920 mAllowedCapturePolicies[uid] = capturePolicy;
3921 return NO_ERROR;
3922}
3923
Eric Laurente552edb2014-03-10 17:42:56 -07003924// This function checks for the parameters which can be offloaded.
3925// This can be enhanced depending on the capability of the DSP and policy
3926// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003927audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003928{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003929 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003930 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003931 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003932 offloadInfo.format,
3933 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3934 offloadInfo.has_video);
3935
jiabin2b9d5a12021-12-10 01:06:29 +00003936 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003937 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003938 }
3939
3940 // See if there is a profile to support this.
3941 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003942 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003943 offloadInfo.sample_rate,
3944 offloadInfo.format,
3945 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003946 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3947 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003948 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3949 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3950 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003951 if (profile == nullptr) {
3952 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3953 }
3954 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3955 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3956 }
3957 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003958}
3959
Michael Chana94fbb22018-04-24 14:31:19 +10003960bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3961 const audio_attributes_t& attributes) {
3962 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003963 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003964 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3965 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003966 config.sample_rate,
3967 config.format,
3968 config.channel_mask,
3969 output_flags,
3970 true /* directOnly */);
3971 ALOGV("%s() profile %sfound with name: %s, "
3972 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3973 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003974 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003975 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003976
3977 // also try the MSD module if compatible profile not found
3978 if (profile == nullptr) {
3979 profile = getMsdProfileForOutput(outputDevices,
3980 config.sample_rate,
3981 config.format,
3982 config.channel_mask,
3983 output_flags,
3984 true /* directOnly */);
3985 ALOGV("%s() MSD profile %sfound with name: %s, "
3986 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3987 __FUNCTION__, profile != 0 ? "" : "NOT ",
3988 (profile != 0 ? profile->getTagName().c_str() : "null"),
3989 config.sample_rate, config.format, config.channel_mask, output_flags);
3990 }
3991 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003992}
3993
jiabin2b9d5a12021-12-10 01:06:29 +00003994bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3995 bool durationIgnored) {
3996 if (mMasterMono) {
3997 return false; // no offloading if mono is set.
3998 }
3999
4000 // Check if offload has been disabled
4001 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4002 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4003 return false;
4004 }
4005
4006 // Check if stream type is music, then only allow offload as of now.
4007 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4008 {
4009 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4010 return false;
4011 }
4012
4013 //TODO: enable audio offloading with video when ready
4014 const bool allowOffloadWithVideo =
4015 property_get_bool("audio.offload.video", false /* default_value */);
4016 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4017 ALOGV("%s: has_video == true, returning false", __func__);
4018 return false;
4019 }
4020
4021 //If duration is less than minimum value defined in property, return false
4022 const int min_duration_secs = property_get_int32(
4023 "audio.offload.min.duration.secs", -1 /* default_value */);
4024 if (!durationIgnored) {
4025 if (min_duration_secs >= 0) {
4026 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4027 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4028 __func__, min_duration_secs);
4029 return false;
4030 }
4031 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4032 ALOGV("%s: Offload denied by duration < default min(=%u)",
4033 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4034 return false;
4035 }
4036 }
4037
4038 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4039 // creating an offloaded track and tearing it down immediately after start when audioflinger
4040 // detects there is an active non offloadable effect.
4041 // FIXME: We should check the audio session here but we do not have it in this context.
4042 // This may prevent offloading in rare situations where effects are left active by apps
4043 // in the background.
4044 if (mEffects.isNonOffloadableEffectEnabled()) {
4045 return false;
4046 }
4047
4048 return true;
4049}
4050
4051audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4052 const audio_config_t *config) {
4053 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4054 offloadInfo.format = config->format;
4055 offloadInfo.sample_rate = config->sample_rate;
4056 offloadInfo.channel_mask = config->channel_mask;
4057 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4058 offloadInfo.has_video = false;
4059 offloadInfo.is_streaming = false;
4060 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4061
4062 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4063 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4064 audio_flags_to_audio_output_flags(attr->flags, &flags);
4065 // only retain flags that will drive compressed offload or passthrough
4066 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4067 if (offloadPossible) {
4068 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4069 }
4070 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4071
Dorin Drimusfae3c642022-03-17 18:36:30 +01004072 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004073 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004074 DeviceVector outputDevices = engineOutputDevices;
4075 // the MSD module checks for different conditions and output devices
4076 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4077 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4078 continue;
4079 }
4080 outputDevices = getMsdAudioOutDevices();
4081 }
jiabin2b9d5a12021-12-10 01:06:29 +00004082 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004083 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004084 config->sample_rate, nullptr /*updatedSamplingRate*/,
4085 config->format, nullptr /*updatedFormat*/,
4086 config->channel_mask, nullptr /*updatedChannelMask*/,
4087 flags)) {
4088 continue;
4089 }
4090 // reject profiles not corresponding to a device currently available
4091 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4092 continue;
4093 }
4094 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4095 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004096 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004097 != AUDIO_DIRECT_NOT_SUPPORTED) {
4098 // Already reports offload gapless supported. No need to report offload support.
4099 continue;
4100 }
4101 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4102 != AUDIO_OUTPUT_FLAG_NONE) {
4103 // If offload gapless is reported, no need to report offload support.
4104 directMode = (audio_direct_mode_t) ((directMode &
4105 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4106 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4107 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004108 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004109 }
4110 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004111 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004112 }
4113 }
4114 }
4115 return directMode;
4116}
4117
Dorin Drimusf2196d82022-01-03 12:11:18 +01004118status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4119 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004120 if (mEffects.isNonOffloadableEffectEnabled()) {
4121 return OK;
4122 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004123 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004124 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004125 if (status != OK) {
4126 return status;
4127 }
4128 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4129 if (devices.empty()) {
4130 return OK; // no output devices for the attributes
4131 }
4132
4133 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004134 // the MSD module checks for different conditions
4135 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4136 continue;
4137 }
4138 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4139 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004140 continue;
4141 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004142 // allow only profiles that support all the available and routed devices
4143 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004144 != devices.size()) {
4145 continue;
4146 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004147 audioProfilesVector.addAllValidProfiles(
4148 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004149 }
4150 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004151
4152 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4153 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4154 if (msdModule != nullptr) {
4155 if (msdHasPatchesToAllDevices(devices)) {
4156 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4157 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4158 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4159 continue;
4160 }
4161 audioProfilesVector.addAllValidProfiles(
4162 outputProfile->asAudioPort()->getAudioProfiles());
4163 }
4164 } else {
4165 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4166 }
4167 }
4168
Dorin Drimusf2196d82022-01-03 12:11:18 +01004169 return NO_ERROR;
4170}
4171
Eric Laurent6a94d692014-05-20 11:18:06 -07004172status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4173 audio_port_type_t type,
4174 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004175 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004176 unsigned int *generation)
4177{
jiabin19cdba52020-11-24 11:28:58 -08004178 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4179 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004180 return BAD_VALUE;
4181 }
4182 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004183 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 *num_ports = 0;
4185 }
4186
4187 size_t portsWritten = 0;
4188 size_t portsMax = *num_ports;
4189 *num_ports = 0;
4190 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004191 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4192 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004194 for (const auto& dev : mAvailableOutputDevices) {
4195 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004196 continue;
4197 }
4198 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004199 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004200 }
4201 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004202 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 }
4204 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004205 for (const auto& dev : mAvailableInputDevices) {
4206 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004207 continue;
4208 }
4209 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004210 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004211 }
4212 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004213 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 }
4215 }
4216 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4217 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4218 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4219 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4220 }
4221 *num_ports += mInputs.size();
4222 }
4223 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004224 size_t numOutputs = 0;
4225 for (size_t i = 0; i < mOutputs.size(); i++) {
4226 if (!mOutputs[i]->isDuplicated()) {
4227 numOutputs++;
4228 if (portsWritten < portsMax) {
4229 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4230 }
4231 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004232 }
Eric Laurent84c70242014-06-23 08:46:27 -07004233 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004234 }
4235 }
4236 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004237 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004238 return NO_ERROR;
4239}
4240
jiabin19cdba52020-11-24 11:28:58 -08004241status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004242{
Eric Laurent99fcae42018-05-17 16:59:18 -07004243 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4244 return BAD_VALUE;
4245 }
4246 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4247 if (dev != 0) {
4248 dev->toAudioPort(port);
4249 return NO_ERROR;
4250 }
4251 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4252 if (dev != 0) {
4253 dev->toAudioPort(port);
4254 return NO_ERROR;
4255 }
4256 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4257 if (out != 0) {
4258 out->toAudioPort(port);
4259 return NO_ERROR;
4260 }
4261 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4262 if (in != 0) {
4263 in->toAudioPort(port);
4264 return NO_ERROR;
4265 }
4266 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004267}
4268
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004269status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4270 audio_patch_handle_t *handle,
4271 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004272{
François Gaffieafd4cea2019-11-18 15:50:22 +01004273 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004274 if (handle == NULL || patch == NULL) {
4275 return BAD_VALUE;
4276 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004277 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004278 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004279 return BAD_VALUE;
4280 }
4281 // only one source per audio patch supported for now
4282 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004283 return INVALID_OPERATION;
4284 }
Eric Laurent874c42872014-08-08 15:13:39 -07004285 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004286 return INVALID_OPERATION;
4287 }
Eric Laurent874c42872014-08-08 15:13:39 -07004288 for (size_t i = 0; i < patch->num_sinks; i++) {
4289 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4290 return INVALID_OPERATION;
4291 }
4292 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004293
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004294 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4295 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4296 if (srcDevice == nullptr || sinkDevice == nullptr) {
4297 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4298 return BAD_VALUE;
4299 }
4300 ALOGV("%s between source %s and sink %s", __func__,
4301 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4302 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4303 // Default attributes, default volume priority, not to infer with non raw audio patches.
4304 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4305 const struct audio_port_config *source = &patch->sources[0];
4306 sp<SourceClientDescriptor> sourceDesc =
4307 new InternalSourceClientDescriptor(
4308 portId, uid, attributes, *source, srcDevice, sinkDevice,
4309 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4310
4311 status_t status =
4312 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4313
4314 if (status != NO_ERROR) {
4315 return INVALID_OPERATION;
4316 }
4317 mAudioSources.add(portId, sourceDesc);
4318 return NO_ERROR;
4319}
4320
4321status_t AudioPolicyManager::connectAudioSourceToSink(
4322 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4323 const struct audio_patch *patch,
4324 audio_patch_handle_t &handle,
4325 uid_t uid, uint32_t delayMs)
4326{
4327 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4328 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4329 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4330 return INVALID_OPERATION;
4331 }
4332 sourceDesc->connect(handle, sinkDevice);
4333 if (isMsdPatch(handle)) {
4334 return NO_ERROR;
4335 }
4336 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4337 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4338 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4339 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4340 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4341 goto FailurePatchAdded;
4342 }
4343 status = swOutput->start();
4344 if (status != NO_ERROR) {
4345 goto FailureSourceAdded;
4346 }
4347 swOutput->addClient(sourceDesc);
4348 status = startSource(swOutput, sourceDesc, &delayMs);
4349 if (status != NO_ERROR) {
4350 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4351 goto FailureSourceActive;
4352 }
4353 if (delayMs != 0) {
4354 usleep(delayMs * 1000);
4355 }
4356 return NO_ERROR;
4357
4358FailureSourceActive:
4359 swOutput->stop();
4360 releaseOutput(sourceDesc->portId());
4361FailureSourceAdded:
4362 sourceDesc->setSwOutput(nullptr);
4363FailurePatchAdded:
4364 releaseAudioPatchInternal(handle);
4365 return INVALID_OPERATION;
4366}
4367
4368status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4369 audio_patch_handle_t *handle,
4370 uid_t uid, uint32_t delayMs,
4371 const sp<SourceClientDescriptor>& sourceDesc)
4372{
4373 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004374 sp<AudioPatch> patchDesc;
4375 ssize_t index = mAudioPatches.indexOfKey(*handle);
4376
François Gaffieafd4cea2019-11-18 15:50:22 +01004377 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4378 patch->sources[0].role,
4379 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004380#if LOG_NDEBUG == 0
4381 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004382 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4383 patch->sinks[i].role,
4384 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004385 }
4386#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004387
4388 if (index >= 0) {
4389 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004390 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4391 __func__, mUidCached, patchDesc->getUid(), uid);
4392 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004393 return INVALID_OPERATION;
4394 }
4395 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004396 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004397 }
4398
4399 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004400 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004402 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 return BAD_VALUE;
4404 }
Eric Laurent84c70242014-06-23 08:46:27 -07004405 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4406 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 if (patchDesc != 0) {
4408 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004409 ALOGV("%s source id differs for patch current id %d new id %d",
4410 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004411 return BAD_VALUE;
4412 }
4413 }
Eric Laurent874c42872014-08-08 15:13:39 -07004414 DeviceVector devices;
4415 for (size_t i = 0; i < patch->num_sinks; i++) {
4416 // Only support mix to devices connection
4417 // TODO add support for mix to mix connection
4418 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004419 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004420 return INVALID_OPERATION;
4421 }
4422 sp<DeviceDescriptor> devDesc =
4423 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4424 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004425 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004426 return BAD_VALUE;
4427 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004428
François Gaffie11d30102018-11-02 16:09:09 +01004429 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004430 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004431 NULL, // updatedSamplingRate
4432 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004433 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004434 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004435 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004436 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004437 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004438 return INVALID_OPERATION;
4439 }
4440 devices.add(devDesc);
4441 }
4442 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004443 return INVALID_OPERATION;
4444 }
Eric Laurent874c42872014-08-08 15:13:39 -07004445
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004447 ALOGV("%s setting device %s on output %d",
4448 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004449 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004450 index = mAudioPatches.indexOfKey(*handle);
4451 if (index >= 0) {
4452 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004453 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 }
4455 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004456 patchDesc->setUid(uid);
4457 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004459 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004460 return INVALID_OPERATION;
4461 }
4462 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4463 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4464 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004465 // only one sink supported when connecting an input device to a mix
4466 if (patch->num_sinks > 1) {
4467 return INVALID_OPERATION;
4468 }
François Gaffie53615e22015-03-19 09:24:12 +01004469 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 if (inputDesc == NULL) {
4471 return BAD_VALUE;
4472 }
4473 if (patchDesc != 0) {
4474 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4475 return BAD_VALUE;
4476 }
4477 }
François Gaffie11d30102018-11-02 16:09:09 +01004478 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004479 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004480 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004481 return BAD_VALUE;
4482 }
4483
François Gaffie11d30102018-11-02 16:09:09 +01004484 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004485 patch->sinks[0].sample_rate,
4486 NULL, /*updatedSampleRate*/
4487 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004488 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004489 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004490 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004491 // FIXME for the parameter type,
4492 // and the NONE
4493 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004494 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004495 return INVALID_OPERATION;
4496 }
4497 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004498 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004499 device->toString().c_str(), inputDesc->mIoHandle);
4500 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 index = mAudioPatches.indexOfKey(*handle);
4502 if (index >= 0) {
4503 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 }
4506 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004507 patchDesc->setUid(uid);
4508 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004509 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004510 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004511 return INVALID_OPERATION;
4512 }
4513 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4514 // device to device connection
4515 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004516 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 return BAD_VALUE;
4518 }
4519 }
François Gaffie11d30102018-11-02 16:09:09 +01004520 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004521 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004522 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004523 return BAD_VALUE;
4524 }
Eric Laurent874c42872014-08-08 15:13:39 -07004525
Eric Laurent6a94d692014-05-20 11:18:06 -07004526 //update source and sink with our own data as the data passed in the patch may
4527 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004528 PatchBuilder patchBuilder;
4529 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004530
4531 // if first sink is to MSD, establish single MSD patch
4532 if (getMsdAudioOutDevices().contains(
4533 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4534 ALOGV("%s patching to MSD", __FUNCTION__);
4535 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4536 goto installPatch;
4537 }
4538
François Gaffieafd4cea2019-11-18 15:50:22 +01004539 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4540 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004541
Eric Laurent874c42872014-08-08 15:13:39 -07004542 for (size_t i = 0; i < patch->num_sinks; i++) {
4543 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004544 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004545 return INVALID_OPERATION;
4546 }
François Gaffie11d30102018-11-02 16:09:09 +01004547 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004548 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004549 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004550 return BAD_VALUE;
4551 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004552 audio_port_config sinkPortConfig = {};
4553 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4554 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004555
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004556 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4557 // volume management purpose (tracking activity)
4558 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4559 // in config XML to reach the sink so that is can be declared as available.
4560 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004561 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004562 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004563 // take care of dynamic routing for SwOutput selection,
4564 audio_attributes_t attributes = sourceDesc->attributes();
4565 audio_stream_type_t stream = sourceDesc->stream();
4566 audio_attributes_t resultAttr;
4567 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4568 config.sample_rate = sourceDesc->config().sample_rate;
4569 config.channel_mask = sourceDesc->config().channel_mask;
4570 config.format = sourceDesc->config().format;
4571 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4572 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4573 bool isRequestedDeviceForExclusiveUse = false;
4574 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004575 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004576 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4577 &stream, sourceDesc->uid(), &config, &flags,
4578 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004579 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004580 if (output == AUDIO_IO_HANDLE_NONE) {
4581 ALOGV("%s no output for device %s",
4582 __FUNCTION__, sinkDevice->toString().c_str());
4583 return INVALID_OPERATION;
4584 }
4585 outputDesc = mOutputs.valueFor(output);
4586 if (outputDesc->isDuplicated()) {
4587 ALOGE("%s output is duplicated", __func__);
4588 return INVALID_OPERATION;
4589 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004590 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4591 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004592 } else {
4593 // Same for "raw patches" aka created from createAudioPatch API
4594 SortedVector<audio_io_handle_t> outputs =
4595 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4596 // if the sink device is reachable via an opened output stream, request to
4597 // go via this output stream by adding a second source to the patch
4598 // description
4599 output = selectOutput(outputs);
4600 if (output == AUDIO_IO_HANDLE_NONE) {
4601 ALOGE("%s no output available for internal patch sink", __func__);
4602 return INVALID_OPERATION;
4603 }
4604 outputDesc = mOutputs.valueFor(output);
4605 if (outputDesc->isDuplicated()) {
4606 ALOGV("%s output for device %s is duplicated",
4607 __func__, sinkDevice->toString().c_str());
4608 return INVALID_OPERATION;
4609 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004610 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004611 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004612 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004613 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004614 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004615 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004616 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4617 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004618 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4619 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004620 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004621 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004622 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004623 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004624 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004625 return INVALID_OPERATION;
4626 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004627 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004628 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004629 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004630 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004631 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004632 srcMixPortConfig.ext.mix.usecase.stream =
4633 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004634 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4635 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004636 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004637 }
Eric Laurent83b88082014-06-20 18:31:16 -07004638 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004639 }
4640 // TODO: check from routing capabilities in config file and other conflicting patches
4641
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004642installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004643 status_t status = installPatch(
4644 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004645 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004646 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004647 return INVALID_OPERATION;
4648 }
4649 } else {
4650 return BAD_VALUE;
4651 }
4652 } else {
4653 return BAD_VALUE;
4654 }
4655 return NO_ERROR;
4656}
4657
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004658status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004659{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004660 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 ssize_t index = mAudioPatches.indexOfKey(handle);
4662
4663 if (index < 0) {
4664 return BAD_VALUE;
4665 }
4666 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004667 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4668 __func__, mUidCached, patchDesc->getUid(), uid);
4669 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004670 return INVALID_OPERATION;
4671 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004672 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4673 for (size_t i = 0; i < mAudioSources.size(); i++) {
4674 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4675 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4676 portId = sourceDesc->portId();
4677 break;
4678 }
4679 }
4680 return portId != AUDIO_PORT_HANDLE_NONE ?
4681 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004682}
Eric Laurent6a94d692014-05-20 11:18:06 -07004683
François Gaffieafd4cea2019-11-18 15:50:22 +01004684status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004685 uint32_t delayMs,
4686 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004687{
4688 ALOGV("%s patch %d", __func__, handle);
4689 if (mAudioPatches.indexOfKey(handle) < 0) {
4690 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4691 return BAD_VALUE;
4692 }
4693 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004695 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004697 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004699 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 return BAD_VALUE;
4701 }
4702
François Gaffie11d30102018-11-02 16:09:09 +01004703 setOutputDevices(outputDesc,
4704 getNewOutputDevices(outputDesc, true /*fromCache*/),
4705 true,
4706 0,
4707 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004708 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4709 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004710 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004711 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004712 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004713 return BAD_VALUE;
4714 }
4715 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004716 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004717 true,
4718 NULL);
4719 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004720 status_t status =
4721 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4722 ALOGV("%s patch panel returned %d patchHandle %d",
4723 __func__, status, patchDesc->getAfHandle());
4724 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004726 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004727 // SW or HW Bridge
4728 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4729 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004730 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004731 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4732 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4733 outputDesc = sourceDesc->swOutput().promote();
4734 }
4735 if (outputDesc == nullptr) {
4736 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4737 // releaseOutput has already called closeOutput in case of direct output
4738 return NO_ERROR;
4739 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004740 patchHandle = outputDesc->getPatchHandle();
4741 // When a Sw bridge is released, the mixer used by this bridge will release its
4742 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4743 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4744 // updating hal patch handle (prevent leaks).
4745 // While using a HwBridge, force reconsidering device only if not reusing an existing
4746 // output and no more activity on output (will force to close).
4747 bool force = sourceDesc->useSwBridge() ||
4748 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4749 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4750 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4751 // Reconsider device only for cases:
4752 // 1 / Active Output
4753 // 2 / Inactive Output previously hosting HwBridge
4754 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4755 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4756 sourceDesc->canCloseOutput();
4757 setOutputDevices(outputDesc,
4758 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4759 outputDesc->devices(),
4760 force,
4761 0,
4762 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 } else {
4764 return BAD_VALUE;
4765 }
4766 } else {
4767 return BAD_VALUE;
4768 }
4769 return NO_ERROR;
4770}
4771
4772status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4773 struct audio_patch *patches,
4774 unsigned int *generation)
4775{
François Gaffie53615e22015-03-19 09:24:12 +01004776 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004777 return BAD_VALUE;
4778 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004779 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004780 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004781}
4782
Eric Laurente1715a42014-05-20 11:30:42 -07004783status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004784{
Eric Laurente1715a42014-05-20 11:30:42 -07004785 ALOGV("setAudioPortConfig()");
4786
4787 if (config == NULL) {
4788 return BAD_VALUE;
4789 }
4790 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4791 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004792 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4793 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004794 }
4795
Eric Laurenta121f902014-06-03 13:32:54 -07004796 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004797 if (config->type == AUDIO_PORT_TYPE_MIX) {
4798 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004799 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004800 if (outputDesc == NULL) {
4801 return BAD_VALUE;
4802 }
Eric Laurent84c70242014-06-23 08:46:27 -07004803 ALOG_ASSERT(!outputDesc->isDuplicated(),
4804 "setAudioPortConfig() called on duplicated output %d",
4805 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004806 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004807 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004808 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004809 if (inputDesc == NULL) {
4810 return BAD_VALUE;
4811 }
Eric Laurenta121f902014-06-03 13:32:54 -07004812 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004813 } else {
4814 return BAD_VALUE;
4815 }
4816 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4817 sp<DeviceDescriptor> deviceDesc;
4818 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4819 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4820 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4821 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4822 } else {
4823 return BAD_VALUE;
4824 }
4825 if (deviceDesc == NULL) {
4826 return BAD_VALUE;
4827 }
Eric Laurenta121f902014-06-03 13:32:54 -07004828 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004829 } else {
4830 return BAD_VALUE;
4831 }
4832
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004833 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004834 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4835 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004836 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004837 audioPortConfig->toAudioPortConfig(&newConfig, config);
4838 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004839 }
Eric Laurenta121f902014-06-03 13:32:54 -07004840 if (status != NO_ERROR) {
4841 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004842 }
Eric Laurente1715a42014-05-20 11:30:42 -07004843
4844 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004845}
4846
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004847void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4848{
Eric Laurentd60560a2015-04-10 11:31:20 -07004849 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004850 clearAudioPatches(uid);
4851 clearSessionRoutes(uid);
4852}
4853
Eric Laurent6a94d692014-05-20 11:18:06 -07004854void AudioPolicyManager::clearAudioPatches(uid_t uid)
4855{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004856 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004858 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004859 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 }
4861 }
4862}
4863
François Gaffiec005e562018-11-06 15:04:49 +01004864void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004865{
François Gaffiec005e562018-11-06 15:04:49 +01004866 // Take the first attributes following the product strategy as it is used to retrieve the routed
4867 // device. All attributes wihin a strategy follows the same "routing strategy"
4868 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4869 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004870 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004871 for (size_t j = 0; j < mOutputs.size(); j++) {
4872 if (mOutputs.keyAt(j) == ouptutToSkip) {
4873 continue;
4874 }
4875 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004876 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004877 continue;
4878 }
4879 // If the default device for this strategy is on another output mix,
4880 // invalidate all tracks in this strategy to force re connection.
4881 // Otherwise select new device on the output mix.
4882 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004883 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4884 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004885 }
4886 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004887 setOutputDevices(
4888 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004889 }
4890 }
4891}
4892
4893void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4894{
4895 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004896 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004897 for (size_t i = 0; i < mOutputs.size(); i++) {
4898 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004899 for (const auto& client : outputDesc->getClientIterable()) {
4900 if (client->hasPreferredDevice() && client->uid() == uid) {
4901 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004902 auto clientStrategy = client->strategy();
4903 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4904 end(affectedStrategies)) {
4905 continue;
4906 }
4907 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004908 }
4909 }
4910 }
4911 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004912 for (const auto& strategy : affectedStrategies) {
4913 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004914 }
4915
4916 // remove input routes associated with this uid
4917 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004918 for (size_t i = 0; i < mInputs.size(); i++) {
4919 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004920 for (const auto& client : inputDesc->getClientIterable()) {
4921 if (client->hasPreferredDevice() && client->uid() == uid) {
4922 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4923 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004924 }
4925 }
4926 }
4927 // reroute inputs if necessary
4928 SortedVector<audio_io_handle_t> inputsToClose;
4929 for (size_t i = 0; i < mInputs.size(); i++) {
4930 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004931 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004932 inputsToClose.add(inputDesc->mIoHandle);
4933 }
4934 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004935 for (const auto& input : inputsToClose) {
4936 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004937 }
4938}
4939
Eric Laurentd60560a2015-04-10 11:31:20 -07004940void AudioPolicyManager::clearAudioSources(uid_t uid)
4941{
4942 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004943 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4944 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004945 stopAudioSource(mAudioSources.keyAt(i));
4946 }
4947 }
4948}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004949
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004950status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4951 audio_io_handle_t *ioHandle,
4952 audio_devices_t *device)
4953{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004954 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4955 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004956 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004957 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004958
François Gaffiedf372692015-03-19 10:43:27 +01004959 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004960}
4961
Eric Laurentd60560a2015-04-10 11:31:20 -07004962status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004963 const audio_attributes_t *attributes,
4964 audio_port_handle_t *portId,
4965 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004966{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004967 ALOGV("%s", __FUNCTION__);
4968 *portId = AUDIO_PORT_HANDLE_NONE;
4969
4970 if (source == NULL || attributes == NULL || portId == NULL) {
4971 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4972 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004973 return BAD_VALUE;
4974 }
4975
Eric Laurentd60560a2015-04-10 11:31:20 -07004976 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4977 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004978 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4979 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004980 return INVALID_OPERATION;
4981 }
4982
François Gaffie11d30102018-11-02 16:09:09 +01004983 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004984 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004985 String8(source->ext.device.address),
4986 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004987 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004988 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004989 return BAD_VALUE;
4990 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004991
jiabin4ef93452019-09-10 14:29:54 -07004992 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004993
François Gaffieaaac0fd2018-11-22 17:56:39 +01004994 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004995 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004996 mEngine->getStreamTypeForAttributes(*attributes),
4997 mEngine->getProductStrategyForAttributes(*attributes),
4998 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004999
5000 status_t status = connectAudioSource(sourceDesc);
5001 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005002 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005003 }
5004 return status;
5005}
5006
Francois Gaffie601801d2021-06-22 13:27:39 +02005007sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5008 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5009{
5010 ALOGV("%s", __FUNCTION__);
5011 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5012
5013 status_t status = startAudioSource(source, attributes, &portId, uid);
5014 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5015 return mAudioSources.valueFor(portId);
5016}
5017
5018
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005019status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005020{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005021 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005022
5023 // make sure we only have one patch per source.
5024 disconnectAudioSource(sourceDesc);
5025
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005026 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005027 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5028 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5029 sourceDesc->srcDevice()->type(),
5030 String8(sourceDesc->srcDevice()->address().c_str()),
5031 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005032 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005033 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005034 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005035 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005036 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5037 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5038 return INVALID_OPERATION;
5039 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 PatchBuilder patchBuilder;
5041 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5042 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005043
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005044 return connectAudioSourceToSink(
5045 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005046}
5047
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005048status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005049{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005050 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5051 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005052 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005053 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005054 return BAD_VALUE;
5055 }
5056 status_t status = disconnectAudioSource(sourceDesc);
5057
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005058 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005059 return status;
5060}
5061
Andy Hung2ddee192015-12-18 17:34:44 -08005062status_t AudioPolicyManager::setMasterMono(bool mono)
5063{
5064 if (mMasterMono == mono) {
5065 return NO_ERROR;
5066 }
5067 mMasterMono = mono;
5068 // if enabling mono we close all offloaded devices, which will invalidate the
5069 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5070 // for recreating the new AudioTrack as non-offloaded PCM.
5071 //
5072 // If disabling mono, we leave all tracks as is: we don't know which clients
5073 // and tracks are able to be recreated as offloaded. The next "song" should
5074 // play back offloaded.
5075 if (mMasterMono) {
5076 Vector<audio_io_handle_t> offloaded;
5077 for (size_t i = 0; i < mOutputs.size(); ++i) {
5078 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5079 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5080 offloaded.push(desc->mIoHandle);
5081 }
5082 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005083 for (const auto& handle : offloaded) {
5084 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005085 }
5086 }
5087 // update master mono for all remaining outputs
5088 for (size_t i = 0; i < mOutputs.size(); ++i) {
5089 updateMono(mOutputs.keyAt(i));
5090 }
5091 return NO_ERROR;
5092}
5093
5094status_t AudioPolicyManager::getMasterMono(bool *mono)
5095{
5096 *mono = mMasterMono;
5097 return NO_ERROR;
5098}
5099
Eric Laurentac9cef52017-06-09 15:46:26 -07005100float AudioPolicyManager::getStreamVolumeDB(
5101 audio_stream_type_t stream, int index, audio_devices_t device)
5102{
jiabin9a3361e2019-10-01 09:38:30 -07005103 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005104}
5105
jiabin81772902018-04-02 17:52:27 -07005106status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5107 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005108 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005109{
Kriti Dang6537def2021-03-02 13:46:59 +01005110 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5111 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005112 return BAD_VALUE;
5113 }
Kriti Dang6537def2021-03-02 13:46:59 +01005114 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5115 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005116
5117 size_t formatsWritten = 0;
5118 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005119
Kriti Dang6537def2021-03-02 13:46:59 +01005120 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005121 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5122 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005123 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005124 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005125 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005126 bool formatEnabled = true;
5127 switch (forceUse) {
5128 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005129 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005130 break;
5131 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5132 formatEnabled = false;
5133 break;
5134 default: // AUTO or ALWAYS => true
5135 break;
jiabin81772902018-04-02 17:52:27 -07005136 }
5137 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5138 }
jiabin81772902018-04-02 17:52:27 -07005139 }
5140 return NO_ERROR;
5141}
5142
Kriti Dang6537def2021-03-02 13:46:59 +01005143status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5144 audio_format_t *surroundFormats) {
5145 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5146 return BAD_VALUE;
5147 }
5148 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5149 __func__, *numSurroundFormats, surroundFormats);
5150
5151 size_t formatsWritten = 0;
5152 size_t formatsMax = *numSurroundFormats;
5153 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5154
5155 // Return formats from all device profiles that have already been resolved by
5156 // checkOutputsForDevice().
5157 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5158 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5159 audio_devices_t deviceType = device->type();
5160 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5161 // returns formats reported by HDMI devices.
5162 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5163 continue;
5164 }
5165 // Formats reported by sink devices
5166 std::unordered_set<audio_format_t> formatset;
5167 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5168 formatset.insert(it->second.begin(), it->second.end());
5169 }
5170
5171 // Formats hard-coded in the in policy configuration file (if any).
5172 FormatVector encodedFormats = device->encodedFormats();
5173 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5174 // Filter the formats which are supported by the vendor hardware.
5175 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5176 if (mConfig.getSurroundFormats().count(*it) != 0) {
5177 formats.insert(*it);
5178 } else {
5179 for (const auto& pair : mConfig.getSurroundFormats()) {
5180 if (pair.second.count(*it) != 0) {
5181 formats.insert(pair.first);
5182 break;
5183 }
5184 }
5185 }
5186 }
5187 }
5188 *numSurroundFormats = formats.size();
5189 for (const auto& format: formats) {
5190 if (formatsWritten < formatsMax) {
5191 surroundFormats[formatsWritten++] = format;
5192 }
5193 }
5194 return NO_ERROR;
5195}
5196
jiabin81772902018-04-02 17:52:27 -07005197status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5198{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005199 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005200 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5201 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005202 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005203 return BAD_VALUE;
5204 }
5205
Mikhail Naganov100f0122018-11-29 11:22:16 -08005206 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5207 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005208 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005209 return INVALID_OPERATION;
5210 }
5211
Mikhail Naganov100f0122018-11-29 11:22:16 -08005212 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005213 return NO_ERROR;
5214 }
5215
Mikhail Naganov100f0122018-11-29 11:22:16 -08005216 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005217 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005218 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005219 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005220 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005221 }
5222 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005223 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005224 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005225 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005226 }
5227 }
5228
5229 sp<SwAudioOutputDescriptor> outputDesc;
5230 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005231 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5232 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005233 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5234 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005235 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005236 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005237 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5238 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5239 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005240 name.c_str(),
5241 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005242 if (status != NO_ERROR) {
5243 continue;
5244 }
5245 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5246 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5247 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005248 name.c_str(),
5249 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005250 profileUpdated |= (status == NO_ERROR);
5251 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005252 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005253 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005254 AUDIO_DEVICE_IN_HDMI);
5255 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5256 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005257 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005258 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005259 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5260 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5261 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005262 name.c_str(),
5263 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005264 if (status != NO_ERROR) {
5265 continue;
5266 }
5267 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5268 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5269 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005270 name.c_str(),
5271 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005272 profileUpdated |= (status == NO_ERROR);
5273 }
5274
jiabin81772902018-04-02 17:52:27 -07005275 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005276 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005277 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005278 }
5279
5280 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5281}
5282
Eric Laurent5ada82e2019-08-29 17:53:54 -07005283void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005284{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005285 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005286 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005287 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005288 }
5289}
5290
jiabin6012f912018-11-02 17:06:30 -07005291bool AudioPolicyManager::isHapticPlaybackSupported()
5292{
5293 for (const auto& hwModule : mHwModules) {
5294 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5295 for (const auto &outProfile : outputProfiles) {
5296 struct audio_port audioPort;
5297 outProfile->toAudioPort(&audioPort);
5298 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5299 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5300 return true;
5301 }
5302 }
5303 }
5304 }
5305 return false;
5306}
5307
Carter Hsu325a8eb2022-01-19 19:56:51 +08005308bool AudioPolicyManager::isUltrasoundSupported()
5309{
5310 bool hasUltrasoundOutput = false;
5311 bool hasUltrasoundInput = false;
5312 for (const auto& hwModule : mHwModules) {
5313 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5314 if (!hasUltrasoundOutput) {
5315 for (const auto &outProfile : outputProfiles) {
5316 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5317 hasUltrasoundOutput = true;
5318 break;
5319 }
5320 }
5321 }
5322
5323 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5324 if (!hasUltrasoundInput) {
5325 for (const auto &inputProfile : inputProfiles) {
5326 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5327 hasUltrasoundInput = true;
5328 break;
5329 }
5330 }
5331 }
5332
5333 if (hasUltrasoundOutput && hasUltrasoundInput)
5334 return true;
5335 }
5336 return false;
5337}
5338
Eric Laurent8340e672019-11-06 11:01:08 -08005339bool AudioPolicyManager::isCallScreenModeSupported()
5340{
5341 return getConfig().isCallScreenModeSupported();
5342}
5343
5344
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005345status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005346{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005347 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005348 if (!sourceDesc->isConnected()) {
5349 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5350 return NO_ERROR;
5351 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005352 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5353 if (swOutput != 0) {
5354 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005355 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005356 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005357 }
jiabinbce0c1d2020-10-05 11:20:18 -07005358 if (releaseOutput(sourceDesc->portId())) {
5359 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5360 // no need to release audio patch here but just return NO_ERROR.
5361 return NO_ERROR;
5362 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005363 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005364 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005365 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005366 // close Hwoutput and remove from mHwOutputs
5367 } else {
5368 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5369 }
5370 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005371 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005372 sourceDesc->disconnect();
5373 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005374}
5375
François Gaffiec005e562018-11-06 15:04:49 +01005376sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5377 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005378{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005379 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005380 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005381 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005382 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005383 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5384 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005385 source = sourceDesc;
5386 break;
5387 }
5388 }
5389 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005390}
5391
Eric Laurentb4f42a92022-01-17 17:37:31 +01005392bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005393 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005394 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005395{
5396 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5397 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005398 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005399 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005400 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5401 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5402 return false;
5403 }
5404 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5405 return false;
5406 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005407 }
5408
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005409 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005410 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005411 if (profile == nullptr) {
5412 return false;
5413 }
5414
5415 // The caller can have the audio config criteria ignored by either passing a null ptr or
5416 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005417 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005418 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005419
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005420 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005421 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005422 return false;
5423 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005424 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005425 return true;
5426}
5427
5428void AudioPolicyManager::checkVirtualizerClientRoutes() {
5429 std::set<audio_stream_type_t> streamsToInvalidate;
5430 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005431 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5432 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005433 audio_attributes_t attr = client->attributes();
5434 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5435 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5436 audio_config_base_t clientConfig = client->config();
5437 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005438 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005439 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005440 streamsToInvalidate.insert(client->stream());
5441 }
5442 }
5443 }
5444
5445 for (audio_stream_type_t stream : streamsToInvalidate) {
5446 mpClientInterface->invalidateStream(stream);
5447 }
5448}
5449
Eric Laurente191d1b2022-04-15 11:59:25 +02005450
5451bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5452 const sp<SwAudioOutputDescriptor>& outputDesc) {
5453 if (outputDesc->isDuplicated()) {
5454 return false;
5455 }
5456 DeviceVector devices = outputDesc->supportedDevices();
5457 for (size_t i = 0; i < mOutputs.size(); i++) {
5458 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5459 if (desc == outputDesc || desc->isDuplicated()) {
5460 continue;
5461 }
5462 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5463 if (!sharedDevices.isEmpty()
5464 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5465 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5466 return false;
5467 }
5468 }
5469 return true;
5470}
5471
5472
Eric Laurentfa0f6742021-08-17 18:39:44 +02005473status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005474 const audio_attributes_t *attr,
5475 audio_io_handle_t *output) {
5476 *output = AUDIO_IO_HANDLE_NONE;
5477
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005478 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5479 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5480 audio_config_t *configPtr = nullptr;
5481 audio_config_t config;
5482 if (mixerConfig != nullptr) {
5483 config = audio_config_initializer(mixerConfig);
5484 configPtr = &config;
5485 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005486 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005487 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005488 return BAD_VALUE;
5489 }
5490
5491 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005492 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005493 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005494 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005495 return BAD_VALUE;
5496 }
5497
Eric Laurente191d1b2022-04-15 11:59:25 +02005498 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005499 for (size_t i = 0; i < mOutputs.size(); i++) {
5500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005501 if (!desc->isDuplicated()
5502 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5503 spatializerOutputs.push_back(desc);
5504 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005505 }
5506 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005507 mSpatializerOutput.clear();
5508 bool outputsChanged = false;
5509 for (const auto& desc : spatializerOutputs) {
5510 if (desc->mProfile == profile
5511 && (configPtr == nullptr
5512 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5513 mSpatializerOutput = desc;
5514 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5515 } else {
5516 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5517 " and devices %s", __func__, desc->mIoHandle,
5518 configPtr != nullptr ? configPtr->channel_mask : 0,
5519 devices.toString().c_str());
5520 closeOutput(desc->mIoHandle);
5521 outputsChanged = true;
5522 }
Eric Laurent39095982021-08-24 18:29:27 +02005523 }
5524
Eric Laurente191d1b2022-04-15 11:59:25 +02005525 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005526 sp<SwAudioOutputDescriptor> desc =
5527 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005528 if (desc != nullptr) {
5529 mSpatializerOutput = desc;
5530 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005531 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005532 }
5533
5534 checkVirtualizerClientRoutes();
5535
Eric Laurente191d1b2022-04-15 11:59:25 +02005536 if (outputsChanged) {
5537 mPreviousOutputs = mOutputs;
5538 mpClientInterface->onAudioPortListUpdate();
5539 }
5540
5541 if (mSpatializerOutput == nullptr) {
5542 ALOGV("%s could not open spatializer output with requested config", __func__);
5543 return BAD_VALUE;
5544 }
Eric Laurent39095982021-08-24 18:29:27 +02005545 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005546 ALOGV("%s returning new spatializer output %d", __func__, *output);
5547 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005548}
5549
Eric Laurentfa0f6742021-08-17 18:39:44 +02005550status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5551 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005552 return INVALID_OPERATION;
5553 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005554 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005555 return BAD_VALUE;
5556 }
Eric Laurent39095982021-08-24 18:29:27 +02005557
Eric Laurente191d1b2022-04-15 11:59:25 +02005558 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5559 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5560 closeOutput(mSpatializerOutput->mIoHandle);
5561 //from now on mSpatializerOutput is null
5562 checkVirtualizerClientRoutes();
5563 }
Eric Laurent39095982021-08-24 18:29:27 +02005564
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005565 return NO_ERROR;
5566}
5567
Eric Laurente552edb2014-03-10 17:42:56 -07005568// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005569// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005570// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005571uint32_t AudioPolicyManager::nextAudioPortGeneration()
5572{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005573 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005574}
5575
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005576static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005577 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5578 !audioPolicyXmlConfigFile.empty()) {
5579 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5580 if (ret == NO_ERROR) {
5581 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005582 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005583 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005584 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005585 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005586}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005587
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005588AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5589 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005590 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005591 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005592 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005593 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005594 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005595 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005596 mAudioPortGeneration(1),
5597 mBeaconMuteRefCount(0),
5598 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005599 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005600 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005601 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005602 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005603{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005604}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005605
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005606AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5607 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5608{
5609 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005610}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005611
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005612void AudioPolicyManager::loadConfig() {
5613 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005614 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005615 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005616 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005617}
5618
5619status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005620 {
5621 auto engLib = EngineLibrary::load(
5622 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5623 if (!engLib) {
5624 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5625 return NO_INIT;
5626 }
5627 mEngine = engLib->createEngine();
5628 if (mEngine == nullptr) {
5629 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5630 return NO_INIT;
5631 }
François Gaffie2110e042015-03-24 08:41:51 +01005632 }
5633 mEngine->setObserver(this);
5634 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005635 if (status != NO_ERROR) {
5636 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5637 return status;
5638 }
François Gaffie2110e042015-03-24 08:41:51 +01005639
Mikhail Naganove93ae282023-02-02 15:28:26 -08005640 // If microphones address is empty, set it according to device type
5641 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
5642 if (mInputDevicesAll[i]->address().empty()) {
5643 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
5644 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
5645 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
5646 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
5647 }
5648 }
5649 }
5650
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005651 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005652 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5653 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5654
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005655 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005656 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005657 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005658
Eric Laurent3a4311c2014-03-17 12:00:47 -07005659 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005660 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5661 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5662 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005663 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005664 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005665 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005666
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005667 // Silence ALOGV statements
5668 property_set("log.tag." LOG_TAG, "D");
5669
Eric Laurente552edb2014-03-10 17:42:56 -07005670 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005671 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005672}
5673
Eric Laurente0720872014-03-11 09:30:41 -07005674AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005675{
Eric Laurente552edb2014-03-10 17:42:56 -07005676 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005677 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005678 }
5679 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005680 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005681 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005682 mAvailableOutputDevices.clear();
5683 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005684 mOutputs.clear();
5685 mInputs.clear();
5686 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005687 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005688 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005689}
5690
Eric Laurente0720872014-03-11 09:30:41 -07005691status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005692{
Eric Laurent87ffa392015-05-22 10:32:38 -07005693 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005694}
5695
Eric Laurente552edb2014-03-10 17:42:56 -07005696// ---
5697
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005698void AudioPolicyManager::onNewAudioModulesAvailable()
5699{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005700 DeviceVector newDevices;
5701 onNewAudioModulesAvailableInt(&newDevices);
5702 if (!newDevices.empty()) {
5703 nextAudioPortGeneration();
5704 mpClientInterface->onAudioPortListUpdate();
5705 }
5706}
5707
5708void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5709{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005710 for (const auto& hwModule : mHwModulesAll) {
5711 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5712 continue;
5713 }
5714 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5715 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5716 ALOGW("could not open HW module %s", hwModule->getName());
5717 continue;
5718 }
5719 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005720 // open all output streams needed to access attached devices.
5721 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005722 // This also validates mAvailableOutputDevices list
5723 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5724 if (!outProfile->canOpenNewIo()) {
5725 ALOGE("Invalid Output profile max open count %u for profile %s",
5726 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5727 continue;
5728 }
5729 if (!outProfile->hasSupportedDevices()) {
5730 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5731 continue;
5732 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005733 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5734 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005735 mTtsOutputAvailable = true;
5736 }
5737
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005738 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5739 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5740 sp<DeviceDescriptor> supportedDevice = 0;
5741 if (supportedDevices.contains(mDefaultOutputDevice)) {
5742 supportedDevice = mDefaultOutputDevice;
5743 } else {
5744 // choose first device present in profile's SupportedDevices also part of
5745 // mAvailableOutputDevices.
5746 if (availProfileDevices.isEmpty()) {
5747 continue;
5748 }
5749 supportedDevice = availProfileDevices.itemAt(0);
5750 }
5751 if (!mOutputDevicesAll.contains(supportedDevice)) {
5752 continue;
5753 }
5754 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5755 mpClientInterface);
5756 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005757 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5758 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005759 AUDIO_STREAM_DEFAULT,
5760 AUDIO_OUTPUT_FLAG_NONE, &output);
5761 if (status != NO_ERROR) {
5762 ALOGW("Cannot open output stream for devices %s on hw module %s",
5763 supportedDevice->toString().c_str(), hwModule->getName());
5764 continue;
5765 }
5766 for (const auto &device : availProfileDevices) {
5767 // give a valid ID to an attached device once confirmed it is reachable
5768 if (!device->isAttached()) {
5769 device->attach(hwModule);
5770 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005771 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005772 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005773 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5774 }
5775 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005776 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005777 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5778 mPrimaryOutput = outputDesc;
5779 }
Eric Laurent39095982021-08-24 18:29:27 +02005780 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005781 outputDesc->close();
5782 } else {
5783 addOutput(output, outputDesc);
5784 setOutputDevices(outputDesc,
5785 DeviceVector(supportedDevice),
5786 true,
5787 0,
5788 NULL);
5789 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005790 }
5791 // open input streams needed to access attached devices to validate
5792 // mAvailableInputDevices list
5793 for (const auto& inProfile : hwModule->getInputProfiles()) {
5794 if (!inProfile->canOpenNewIo()) {
5795 ALOGE("Invalid Input profile max open count %u for profile %s",
5796 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5797 continue;
5798 }
5799 if (!inProfile->hasSupportedDevices()) {
5800 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5801 continue;
5802 }
5803 // chose first device present in profile's SupportedDevices also part of
5804 // available input devices
5805 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5806 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5807 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005808 ALOGV("%s: Input device list is empty! for profile %s",
5809 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005810 continue;
5811 }
5812 sp<AudioInputDescriptor> inputDesc =
5813 new AudioInputDescriptor(inProfile, mpClientInterface);
5814
5815 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5816 status_t status = inputDesc->open(nullptr,
5817 availProfileDevices.itemAt(0),
5818 AUDIO_SOURCE_MIC,
5819 AUDIO_INPUT_FLAG_NONE,
5820 &input);
5821 if (status != NO_ERROR) {
5822 ALOGW("Cannot open input stream for device %s on hw module %s",
5823 availProfileDevices.toString().c_str(),
5824 hwModule->getName());
5825 continue;
5826 }
5827 for (const auto &device : availProfileDevices) {
5828 // give a valid ID to an attached device once confirmed it is reachable
5829 if (!device->isAttached()) {
5830 device->attach(hwModule);
5831 device->importAudioPortAndPickAudioProfile(inProfile, true);
5832 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005833 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005834 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5835 }
5836 }
5837 inputDesc->close();
5838 }
5839 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005840
5841 // Check if spatializer outputs can be closed until used.
5842 // mOutputs vector never contains duplicated outputs at this point.
5843 std::vector<audio_io_handle_t> outputsClosed;
5844 for (size_t i = 0; i < mOutputs.size(); i++) {
5845 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5846 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5847 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5848 outputsClosed.push_back(desc->mIoHandle);
5849 desc->close();
5850 }
5851 }
5852 for (auto output : outputsClosed) {
5853 removeOutput(output);
5854 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005855}
5856
Eric Laurent98e38192018-02-15 18:31:53 -08005857void AudioPolicyManager::addOutput(audio_io_handle_t output,
5858 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005859{
Eric Laurent1c333e22014-05-20 10:48:17 -07005860 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005861 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005862 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005863 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005864 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005865}
5866
François Gaffie53615e22015-03-19 09:24:12 +01005867void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5868{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005869 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5870 ALOGV("%s: removing primary output", __func__);
5871 mPrimaryOutput = nullptr;
5872 }
François Gaffie53615e22015-03-19 09:24:12 +01005873 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005874 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005875}
5876
Eric Laurent98e38192018-02-15 18:31:53 -08005877void AudioPolicyManager::addInput(audio_io_handle_t input,
5878 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005879{
Eric Laurent1c333e22014-05-20 10:48:17 -07005880 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005881 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005882}
Eric Laurente552edb2014-03-10 17:42:56 -07005883
François Gaffie11d30102018-11-02 16:09:09 +01005884status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005885 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005886 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005887{
François Gaffie11d30102018-11-02 16:09:09 +01005888 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005889 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005890 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005891
François Gaffie11d30102018-11-02 16:09:09 +01005892 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005893 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005894 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005895 }
Eric Laurente552edb2014-03-10 17:42:56 -07005896
Eric Laurent3b73df72014-03-11 09:06:29 -07005897 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005898 // first call getAudioPort to get the supported attributes from the HAL
5899 struct audio_port_v7 port = {};
5900 device->toAudioPort(&port);
5901 status_t status = mpClientInterface->getAudioPort(&port);
5902 if (status == NO_ERROR) {
5903 device->importAudioPort(port);
5904 }
5905
5906 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005907 for (size_t i = 0; i < mOutputs.size(); i++) {
5908 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005909 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005910 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005911 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5912 mOutputs.keyAt(i), device->toString().c_str());
5913 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005914 }
5915 }
5916 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005917 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005918 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005919 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5920 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005921 if (profile->supportsDevice(device)) {
5922 profiles.add(profile);
5923 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5924 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005925 }
5926 }
5927 }
5928
Eric Laurent7b279bb2015-12-14 10:18:23 -08005929 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005930
Eric Laurente552edb2014-03-10 17:42:56 -07005931 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005932 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005933 return BAD_VALUE;
5934 }
5935
5936 // open outputs for matching profiles if needed. Direct outputs are also opened to
5937 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5938 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005939 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005940
5941 // nothing to do if one output is already opened for this profile
5942 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005943 for (j = 0; j < outputs.size(); j++) {
5944 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005945 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005946 // matching profile: save the sample rates, format and channel masks supported
5947 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005948 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005949 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005950 }
Eric Laurente552edb2014-03-10 17:42:56 -07005951 break;
5952 }
5953 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005954 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005955 continue;
5956 }
5957
Eric Laurent3974e3b2017-12-07 17:58:43 -08005958 if (!profile->canOpenNewIo()) {
5959 ALOGW("Max Output number %u already opened for this profile %s",
5960 profile->maxOpenCount, profile->getTagName().c_str());
5961 continue;
5962 }
5963
Eric Laurent83efe1c2017-07-09 16:51:08 -07005964 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005965 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005966 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5967 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005968 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005969 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005970 profiles.removeAt(profile_index);
5971 profile_index--;
5972 } else {
5973 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005974 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005975 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005976 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5977 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005978 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005979 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005980
François Gaffie11d30102018-11-02 16:09:09 +01005981 if (device_distinguishes_on_address(deviceType)) {
5982 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5983 device->toString().c_str());
5984 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5985 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005986 }
Eric Laurente552edb2014-03-10 17:42:56 -07005987 ALOGV("checkOutputsForDevice(): adding output %d", output);
5988 }
5989 }
5990
5991 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005992 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005993 return BAD_VALUE;
5994 }
Eric Laurentd4692962014-05-05 18:13:44 -07005995 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005996 // check if one opened output is not needed any more after disconnecting one device
5997 for (size_t i = 0; i < mOutputs.size(); i++) {
5998 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005999 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006000 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006001 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006002 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006003 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006004 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006005 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6006 mOutputs.keyAt(i));
6007 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006008 }
Eric Laurente552edb2014-03-10 17:42:56 -07006009 }
6010 }
Eric Laurentd4692962014-05-05 18:13:44 -07006011 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006012 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006013 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6014 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006015 if (!profile->supportsDevice(device)) {
6016 continue;
6017 }
6018 ALOGV("checkOutputsForDevice(): "
6019 "clearing direct output profile %zu on module %s",
6020 j, hwModule->getName());
6021 profile->clearAudioProfiles();
6022 if (!profile->hasDynamicAudioProfile()) {
6023 continue;
6024 }
6025 // When a device is disconnected, if there is an IOProfile that contains dynamic
6026 // profiles and supports the disconnected device, call getAudioPort to repopulate
6027 // the capabilities of the devices that is supported by the IOProfile.
6028 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6029 if (supportedDevice == device ||
6030 !mAvailableOutputDevices.contains(supportedDevice)) {
6031 continue;
6032 }
6033 struct audio_port_v7 port;
6034 supportedDevice->toAudioPort(&port);
6035 status_t status = mpClientInterface->getAudioPort(&port);
6036 if (status == NO_ERROR) {
6037 supportedDevice->importAudioPort(port);
6038 }
Eric Laurente552edb2014-03-10 17:42:56 -07006039 }
6040 }
6041 }
6042 }
6043 return NO_ERROR;
6044}
6045
François Gaffie11d30102018-11-02 16:09:09 +01006046status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006047 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006048{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006049 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006050
François Gaffie11d30102018-11-02 16:09:09 +01006051 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006052 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006053 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006054 }
6055
Eric Laurentd4692962014-05-05 18:13:44 -07006056 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006057 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006058 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006059 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006060 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006061 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006062 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006063 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006064
François Gaffie11d30102018-11-02 16:09:09 +01006065 if (profile->supportsDevice(device)) {
6066 profiles.add(profile);
6067 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6068 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006069 }
6070 }
6071 }
6072
Eric Laurent0dd51852019-04-19 18:18:58 -07006073 if (profiles.isEmpty()) {
6074 ALOGW("%s: No input profile available for device %s",
6075 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006076 return BAD_VALUE;
6077 }
6078
6079 // open inputs for matching profiles if needed. Direct inputs are also opened to
6080 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6081 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6082
Eric Laurent1c333e22014-05-20 10:48:17 -07006083 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006084
Eric Laurentd4692962014-05-05 18:13:44 -07006085 // nothing to do if one input is already opened for this profile
6086 size_t input_index;
6087 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6088 desc = mInputs.valueAt(input_index);
6089 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006090 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006091 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006092 }
Eric Laurentd4692962014-05-05 18:13:44 -07006093 break;
6094 }
6095 }
6096 if (input_index != mInputs.size()) {
6097 continue;
6098 }
6099
Eric Laurent3974e3b2017-12-07 17:58:43 -08006100 if (!profile->canOpenNewIo()) {
6101 ALOGW("Max Input number %u already opened for this profile %s",
6102 profile->maxOpenCount, profile->getTagName().c_str());
6103 continue;
6104 }
6105
Eric Laurentfe231122017-11-17 17:48:06 -08006106 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006107 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006108 status_t status = desc->open(nullptr,
6109 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006110 AUDIO_SOURCE_MIC,
6111 AUDIO_INPUT_FLAG_NONE,
6112 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006113
Eric Laurentcf2c0212014-07-25 16:20:43 -07006114 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006115 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006116 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006117 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006118 mpClientInterface->setParameters(input, String8(param));
6119 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006120 }
François Gaffie11d30102018-11-02 16:09:09 +01006121 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006122 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006123 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006124 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006125 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006126 }
6127
Eric Laurent0dd51852019-04-19 18:18:58 -07006128 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006129 addInput(input, desc);
6130 }
6131 } // endif input != 0
6132
Eric Laurentcf2c0212014-07-25 16:20:43 -07006133 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006134 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006135 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006136 profiles.removeAt(profile_index);
6137 profile_index--;
6138 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006139 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006140 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006141 }
Eric Laurentd4692962014-05-05 18:13:44 -07006142 ALOGV("checkInputsForDevice(): adding input %d", input);
6143 }
6144 } // end scan profiles
6145
6146 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006147 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006148 return BAD_VALUE;
6149 }
6150 } else {
6151 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006152 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006153 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006154 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006155 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006156 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006157 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006158 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006159 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6160 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006161 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006162 }
6163 }
6164 }
6165 } // end disconnect
6166
6167 return NO_ERROR;
6168}
6169
6170
Eric Laurente0720872014-03-11 09:30:41 -07006171void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006172{
6173 ALOGV("closeOutput(%d)", output);
6174
François Gaffie1c878552018-11-22 16:53:21 +01006175 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6176 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006177 ALOGW("closeOutput() unknown output %d", output);
6178 return;
6179 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006180 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006181 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006182
Eric Laurente552edb2014-03-10 17:42:56 -07006183 // look for duplicated outputs connected to the output being removed.
6184 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006185 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6186 if (dupOutput->isDuplicated() &&
6187 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6188 sp<SwAudioOutputDescriptor> remainingOutput =
6189 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006190 // As all active tracks on duplicated output will be deleted,
6191 // and as they were also referenced on the other output, the reference
6192 // count for their stream type must be adjusted accordingly on
6193 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006194 const bool wasActive = remainingOutput->isActive();
6195 // Note: no-op on the closing output where all clients has already been set inactive
6196 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006197 // stop() will be a no op if the output is still active but is needed in case all
6198 // active streams refcounts where cleared above
6199 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006200 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006201 }
Eric Laurente552edb2014-03-10 17:42:56 -07006202 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6203 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6204
6205 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006206 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006207 }
6208 }
6209
Eric Laurent05b90f82014-08-27 15:32:29 -07006210 nextAudioPortGeneration();
6211
François Gaffie1c878552018-11-22 16:53:21 +01006212 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006213 if (index >= 0) {
6214 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006215 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6216 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006217 mAudioPatches.removeItemsAt(index);
6218 mpClientInterface->onAudioPatchListUpdate();
6219 }
6220
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006221 if (closingOutputWasActive) {
6222 closingOutput->stop();
6223 }
François Gaffie1c878552018-11-22 16:53:21 +01006224 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006225
François Gaffie53615e22015-03-19 09:24:12 +01006226 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006227 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006228 if (closingOutput == mSpatializerOutput) {
6229 mSpatializerOutput.clear();
6230 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006231
6232 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6233 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006234 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006235 bool directOutputOpen = false;
6236 for (size_t i = 0; i < mOutputs.size(); i++) {
6237 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6238 directOutputOpen = true;
6239 break;
6240 }
6241 }
6242 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006243 ALOGV("no direct outputs open, reset MSD patches");
6244 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6245 // how output devices for patching are resolved. Avoid by caching and reusing the
6246 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6247 // devices to patch to. This may be complicated by the fact that devices may become
6248 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006249 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006250 }
6251 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006252}
6253
6254void AudioPolicyManager::closeInput(audio_io_handle_t input)
6255{
6256 ALOGV("closeInput(%d)", input);
6257
6258 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6259 if (inputDesc == NULL) {
6260 ALOGW("closeInput() unknown input %d", input);
6261 return;
6262 }
6263
Eric Laurent6a94d692014-05-20 11:18:06 -07006264 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006265
François Gaffie11d30102018-11-02 16:09:09 +01006266 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006267 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006268 if (index >= 0) {
6269 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006270 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6271 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006272 mAudioPatches.removeItemsAt(index);
6273 mpClientInterface->onAudioPatchListUpdate();
6274 }
6275
Eric Laurentfe231122017-11-17 17:48:06 -08006276 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006277 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006278
François Gaffie11d30102018-11-02 16:09:09 +01006279 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6280 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006281 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006282 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006283 }
Eric Laurente552edb2014-03-10 17:42:56 -07006284}
6285
François Gaffie11d30102018-11-02 16:09:09 +01006286SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6287 const DeviceVector &devices,
6288 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006289{
6290 SortedVector<audio_io_handle_t> outputs;
6291
François Gaffie11d30102018-11-02 16:09:09 +01006292 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006293 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006294 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006295 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006296 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006297 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006298 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006299 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006300 outputs.add(openOutputs.keyAt(i));
6301 }
6302 }
6303 return outputs;
6304}
6305
Mikhail Naganov37977152018-07-11 15:54:44 -07006306void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6307{
6308 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6309 // output is suspended before any tracks are moved to it
6310 checkA2dpSuspend();
6311 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006312 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006313 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006314 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006315 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006316 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6317 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6318 // configuration changes will ultimately be rerouted correctly. We can still avoid
6319 // unnecessary rerouting by caching and reusing the arguments to
6320 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6321 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006322 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006323 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006324 // an event that changed routing likely occurred, inform upper layers
6325 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006326}
6327
François Gaffiec005e562018-11-06 15:04:49 +01006328bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6329 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006330{
François Gaffiec005e562018-11-06 15:04:49 +01006331 return mEngine->getProductStrategyForAttributes(lAttr) ==
6332 mEngine->getProductStrategyForAttributes(rAttr);
6333}
6334
Francois Gaffieff1eb522020-05-06 18:37:04 +02006335void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6336{
6337 for (size_t i = 0; i < mAudioSources.size(); i++) {
6338 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6339 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006340 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006341 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006342 connectAudioSource(sourceDesc);
6343 }
6344 }
6345}
6346
6347void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6348{
6349 for (size_t i = 0; i < mAudioSources.size(); i++) {
6350 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6351 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6352 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6353 disconnectAudioSource(sourceDesc);
6354 }
6355 }
6356}
6357
François Gaffiec005e562018-11-06 15:04:49 +01006358void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6359{
6360 auto psId = mEngine->getProductStrategyForAttributes(attr);
6361
6362 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6363 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006364
François Gaffie11d30102018-11-02 16:09:09 +01006365 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6366 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006367
Eric Laurentc209fe42020-06-05 18:11:23 -07006368 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006369 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006370 // take into account dynamic audio policies related changes: if a client is now associated
6371 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006372 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006373 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6374 if (desc->isDuplicated()) {
6375 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006376 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006377 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6378 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6379 continue;
6380 }
6381 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006382 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6383 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006384 if (status != OK) {
6385 continue;
6386 }
yucliuf4de36d2020-09-14 14:57:56 -07006387 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006388 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006389 maxLatency = desc->latency();
6390 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006391 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006392 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006393 }
6394 }
6395
Eric Laurent56ed8842022-11-15 16:04:41 +01006396 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006397 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6398 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006399 for (audio_io_handle_t srcOut : srcOutputs) {
6400 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006401 if (desc == nullptr) continue;
6402
6403 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006404 maxLatency = desc->latency();
6405 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006406
Eric Laurent56ed8842022-11-15 16:04:41 +01006407 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006408 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006409 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006410 // a client on a non direct outputs has necessarily a linear PCM format
6411 // so we can call selectOutput() safely
6412 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6413 client->flags(),
6414 client->config().format,
6415 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006416 client->config().sample_rate,
6417 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006418 if (newOutput != srcOut) {
6419 invalidate = true;
6420 break;
6421 }
6422 } else {
6423 sp<IOProfile> profile = getProfileForOutput(newDevices,
6424 client->config().sample_rate,
6425 client->config().format,
6426 client->config().channel_mask,
6427 client->flags(),
6428 true /* directOnly */);
6429 if (profile != desc->mProfile) {
6430 invalidate = true;
6431 break;
6432 }
6433 }
6434 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006435 // mute strategy while moving tracks from one output to another
6436 if (invalidate) {
6437 invalidatedOutputs.push_back(desc);
6438 if (desc->isStrategyActive(psId)) {
6439 setStrategyMute(psId, true, desc);
6440 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6441 newDevices.types());
6442 }
Eric Laurente552edb2014-03-10 17:42:56 -07006443 }
François Gaffiec005e562018-11-06 15:04:49 +01006444 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006445 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006446 connectAudioSource(source);
6447 }
Eric Laurente552edb2014-03-10 17:42:56 -07006448 }
6449
Eric Laurent56ed8842022-11-15 16:04:41 +01006450 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6451 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6452 std::to_string(srcOutputs[0]).c_str(),
6453 std::to_string(dstOutputs[0]).c_str());
6454
François Gaffiec005e562018-11-06 15:04:49 +01006455 // Move effects associated to this stream from previous output to new output
6456 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006457 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006458 }
François Gaffiec005e562018-11-06 15:04:49 +01006459 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006460 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006461 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6462 mpClientInterface->invalidateStream(stream);
6463 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006464 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006465 desc->setTracksInvalidatedStatusByStrategy(psId);
6466 }
Eric Laurente552edb2014-03-10 17:42:56 -07006467 }
6468 }
6469}
6470
Eric Laurente0720872014-03-11 09:30:41 -07006471void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006472{
François Gaffiec005e562018-11-06 15:04:49 +01006473 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6474 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6475 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006476 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006477 }
Eric Laurente552edb2014-03-10 17:42:56 -07006478}
6479
Kevin Rocard153f92d2018-12-18 18:33:28 -08006480void AudioPolicyManager::checkSecondaryOutputs() {
6481 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006482 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006483 for (size_t i = 0; i < mOutputs.size(); i++) {
6484 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6485 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006486 sp<AudioPolicyMix> primaryMix;
6487 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006488 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6489 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006490 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6491 for (auto &secondaryMix : secondaryMixes) {
6492 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6493 if (outputDesc != nullptr &&
6494 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6495 secondaryDescs.push_back(outputDesc);
6496 }
6497 }
6498
jiabin10a03f12021-05-07 23:46:28 +00006499 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006500 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006501 } else if (!std::equal(
6502 client->getSecondaryOutputs().begin(),
6503 client->getSecondaryOutputs().end(),
6504 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006505 if (!audio_is_linear_pcm(client->config().format)) {
6506 // If the format is not PCM, the tracks should be invalidated to get correct
6507 // behavior when the secondary output is changed.
6508 streamsToInvalidate.insert(client->stream());
6509 } else {
6510 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6511 std::vector<audio_io_handle_t> secondaryOutputIds;
6512 for (const auto &secondaryDesc: secondaryDescs) {
6513 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6514 weakSecondaryDescs.push_back(secondaryDesc);
6515 }
6516 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6517 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006518 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006519 }
6520 }
6521 }
jiabin10a03f12021-05-07 23:46:28 +00006522 if (!trackSecondaryOutputs.empty()) {
6523 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6524 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006525 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006526 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006527 mpClientInterface->invalidateStream(stream);
6528 }
6529}
6530
Eric Laurent2517af32020-11-25 15:31:27 +01006531bool AudioPolicyManager::isScoRequestedForComm() const {
6532 AudioDeviceTypeAddrVector devices;
6533 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6534 for (const auto &device : devices) {
6535 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6536 return true;
6537 }
6538 }
6539 return false;
6540}
6541
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006542bool AudioPolicyManager::isHearingAidUsedForComm() const {
6543 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6544 true /*fromCache*/);
6545 for (const auto &device : devices) {
6546 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6547 return true;
6548 }
6549 }
6550 return false;
6551}
6552
6553
Eric Laurente0720872014-03-11 09:30:41 -07006554void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006555{
François Gaffie53615e22015-03-19 09:24:12 +01006556 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006557 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006558 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006559 return;
6560 }
6561
Eric Laurent3a4311c2014-03-17 12:00:47 -07006562 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006563 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6564 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006565 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006566
6567 // if suspended, restore A2DP output if:
6568 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006569 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006570 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006571 //
Eric Laurentf732e072016-08-03 19:30:28 -07006572 // if not suspended, suspend A2DP output if:
6573 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006574 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006575 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006576 //
6577 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006578 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006579 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006580 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006581 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006582
6583 mpClientInterface->restoreOutput(a2dpOutput);
6584 mA2dpSuspended = false;
6585 }
6586 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006587 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006588 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006589 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006590 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006591
6592 mpClientInterface->suspendOutput(a2dpOutput);
6593 mA2dpSuspended = true;
6594 }
6595 }
6596}
6597
François Gaffie11d30102018-11-02 16:09:09 +01006598DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6599 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006600{
François Gaffie11d30102018-11-02 16:09:09 +01006601 DeviceVector devices;
6602
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006603 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006604 if (index >= 0) {
6605 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006606 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006607 ALOGV("%s device %s forced by patch %d", __func__,
6608 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6609 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006610 }
6611 }
6612
Dean Wheatley514b4312020-06-17 21:45:00 +10006613 // Do not retrieve engine device for outputs through MSD
6614 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6615 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6616 return outputDesc->devices();
6617 }
6618
Eric Laurent97ac8712018-07-27 18:59:02 -07006619 // Honor explicit routing requests only if no client using default routing is active on this
6620 // input: a specific app can not force routing for other apps by setting a preferred device.
6621 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006622 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006623 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006624 if (device != nullptr) {
6625 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006626 }
6627
François Gaffiea807ef92018-11-05 10:44:33 +01006628 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6629 // of setForceUse / Default Bus device here
6630 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6631 if (device != nullptr) {
6632 return DeviceVector(device);
6633 }
6634
François Gaffiec005e562018-11-06 15:04:49 +01006635 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6636 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6637 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306638 auto hasStreamActive = [&](auto stream) {
6639 return hasStream(streams, stream) && isStreamActive(stream, 0);
6640 };
Eric Laurent484e9272018-06-07 17:29:23 -07006641
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306642 auto doGetOutputDevicesForVoice = [&]() {
6643 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006644 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306645 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006646 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6647 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306648 };
6649
6650 // With low-latency playing on speaker, music on WFD, when the first low-latency
6651 // output is stopped, getNewOutputDevices checks for a product strategy
6652 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006653 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306654 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6655 // stream is associated to the output descriptor.
6656 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6657 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6658 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6659 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006660 // Retrieval of devices for voice DL is done on primary output profile, cannot
6661 // check the route (would force modifying configuration file for this profile)
6662 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6663 break;
6664 }
Eric Laurente552edb2014-03-10 17:42:56 -07006665 }
François Gaffiec005e562018-11-06 15:04:49 +01006666 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006667 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006668}
6669
François Gaffie11d30102018-11-02 16:09:09 +01006670sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6671 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006672{
François Gaffie11d30102018-11-02 16:09:09 +01006673 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006674
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006675 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006676 if (index >= 0) {
6677 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006678 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006679 ALOGV("getNewInputDevice() device %s forced by patch %d",
6680 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6681 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006682 }
6683 }
6684
Eric Laurent97ac8712018-07-27 18:59:02 -07006685 // Honor explicit routing requests only if no client using default routing is active on this
6686 // input: a specific app can not force routing for other apps by setting a preferred device.
6687 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006688 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6689 if (device != nullptr) {
6690 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006691 }
6692
Eric Laurentdc95a252018-04-12 12:46:56 -07006693 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006694 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006695 audio_attributes_t attributes;
6696 uid_t uid;
6697 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6698 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006699 attributes = topClient->attributes();
6700 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006701 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006702 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6703 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006704 }
6705
Francois Gaffie716e1432019-01-14 16:58:59 +01006706 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6707 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006708 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006709 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006710 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006711 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006712
Eric Laurente552edb2014-03-10 17:42:56 -07006713 return device;
6714}
6715
Eric Laurent794fde22016-03-11 09:50:45 -08006716bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6717 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006718 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006719}
6720
Dorin Drimusf2196d82022-01-03 12:11:18 +01006721// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006722status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006723 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006724 if (devices == nullptr) {
6725 return BAD_VALUE;
6726 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006727
6728 // Devices are determined in the following precedence:
6729 //
6730 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6731 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6732 //
6733 // If no such dynamic policy then
6734 // 2) Devices containing an active client using setPreferredDevice
6735 // with same strategy as the attributes.
6736 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6737 //
6738 // If no corresponding active client with setPreferredDevice then
6739 // 3) Devices associated with the strategy determined by the attributes
6740 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6741 //
6742 // See related getOutputForAttrInt().
6743
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006744 // check dynamic policies but only for primary descriptors (secondary not used for audible
6745 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006746 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006747 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6748 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006749 if (status != OK) {
6750 return status;
6751 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006752
6753 DeviceVector curDevices;
6754 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6755 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6756 // as they are unaffected by device/stream volume
6757 // (per SwAudioOutputDescriptor::isFixedVolume()).
6758 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6759 ) {
6760 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6761 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6762 curDevices.add(deviceDesc);
6763 } else {
6764 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6765 // which selects setPreferredDevice if active. This means forVolume call
6766 // will take an active setPreferredDevice, if such exists.
6767
6768 curDevices = mEngine->getOutputDevicesForAttributes(
6769 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006770 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006771
6772 if (forVolume) {
6773 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6774 // for single volume control in AudioService (such relationship should exist if
6775 // SPEAKER_SAFE is present).
6776 //
6777 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6778 DeviceVector speakerSafeDevices =
6779 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6780 if (!speakerSafeDevices.isEmpty()) {
6781 curDevices.merge(
6782 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6783 curDevices.remove(speakerSafeDevices);
6784 }
6785 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006786 for (const auto& device : curDevices) {
6787 devices->push_back(device->getDeviceTypeAddr());
6788 }
6789 return NO_ERROR;
6790}
6791
Eric Laurente0720872014-03-11 09:30:41 -07006792void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006793 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006794 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006795 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006796 updateDevicesAndOutputs();
6797 break;
6798 default:
6799 break;
6800 }
6801}
6802
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006803uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006804
6805 // skip beacon mute management if a dedicated TTS output is available
6806 if (mTtsOutputAvailable) {
6807 return 0;
6808 }
6809
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006810 switch(event) {
6811 case STARTING_OUTPUT:
6812 mBeaconMuteRefCount++;
6813 break;
6814 case STOPPING_OUTPUT:
6815 if (mBeaconMuteRefCount > 0) {
6816 mBeaconMuteRefCount--;
6817 }
6818 break;
6819 case STARTING_BEACON:
6820 mBeaconPlayingRefCount++;
6821 break;
6822 case STOPPING_BEACON:
6823 if (mBeaconPlayingRefCount > 0) {
6824 mBeaconPlayingRefCount--;
6825 }
6826 break;
6827 }
6828
6829 if (mBeaconMuteRefCount > 0) {
6830 // any playback causes beacon to be muted
6831 return setBeaconMute(true);
6832 } else {
6833 // no other playback: unmute when beacon starts playing, mute when it stops
6834 return setBeaconMute(mBeaconPlayingRefCount == 0);
6835 }
6836}
6837
6838uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6839 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6840 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6841 // keep track of muted state to avoid repeating mute/unmute operations
6842 if (mBeaconMuted != mute) {
6843 // mute/unmute AUDIO_STREAM_TTS on all outputs
6844 ALOGV("\t muting %d", mute);
6845 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006846 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6847 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6848 ALOGV("\t no tts volume source available");
6849 return 0;
6850 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006851 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006852 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006853 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006854 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006855 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006856 maxLatency = latency;
6857 }
6858 }
6859 mBeaconMuted = mute;
6860 return maxLatency;
6861 }
6862 return 0;
6863}
6864
Eric Laurente0720872014-03-11 09:30:41 -07006865void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006866{
François Gaffiec005e562018-11-06 15:04:49 +01006867 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006868 mPreviousOutputs = mOutputs;
6869}
6870
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006871uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006872 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006873 uint32_t delayMs)
6874{
6875 // mute/unmute strategies using an incompatible device combination
6876 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6877 // if unmuting, unmute only after the specified delay
6878 if (outputDesc->isDuplicated()) {
6879 return 0;
6880 }
6881
6882 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006883 DeviceVector devices = outputDesc->devices();
6884 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006885
François Gaffiec005e562018-11-06 15:04:49 +01006886 auto productStrategies = mEngine->getOrderedProductStrategies();
6887 for (const auto &productStrategy : productStrategies) {
6888 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6889 DeviceVector curDevices =
6890 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6891 curDevices = curDevices.filter(outputDesc->supportedDevices());
6892 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006893 bool doMute = false;
6894
François Gaffiec005e562018-11-06 15:04:49 +01006895 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006896 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006897 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6898 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006899 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006900 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006901 }
Eric Laurent99401132014-05-07 19:48:15 -07006902 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006903 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006904 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006905 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006906 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006907 continue;
6908 }
François Gaffiec005e562018-11-06 15:04:49 +01006909 ALOGVV("%s() %s (curDevice %s)", __func__,
6910 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6911 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6912 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006913 if (mute) {
6914 // FIXME: should not need to double latency if volume could be applied
6915 // immediately by the audioflinger mixer. We must account for the delay
6916 // between now and the next time the audioflinger thread for this output
6917 // will process a buffer (which corresponds to one buffer size,
6918 // usually 1/2 or 1/4 of the latency).
6919 if (muteWaitMs < desc->latency() * 2) {
6920 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006921 }
6922 }
6923 }
6924 }
6925 }
6926 }
6927
Eric Laurent99401132014-05-07 19:48:15 -07006928 // temporary mute output if device selection changes to avoid volume bursts due to
6929 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006930 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006931 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006932
Eric Laurentdc462862016-07-19 12:29:53 -07006933 if (muteWaitMs < tempMuteWaitMs) {
6934 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006935 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006936
6937 // If recommended duration is defined, replace temporary mute duration to avoid
6938 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6939 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6940 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6941 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6942 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6943
François Gaffieaaac0fd2018-11-22 17:56:39 +01006944 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6945 // make sure that we do not start the temporary mute period too early in case of
6946 // delayed device change
6947 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6948 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006949 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006950 }
6951 }
6952
Eric Laurente552edb2014-03-10 17:42:56 -07006953 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6954 if (muteWaitMs > delayMs) {
6955 muteWaitMs -= delayMs;
6956 usleep(muteWaitMs * 1000);
6957 return muteWaitMs;
6958 }
6959 return 0;
6960}
6961
François Gaffie11d30102018-11-02 16:09:09 +01006962uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6963 const DeviceVector &devices,
6964 bool force,
6965 int delayMs,
6966 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006967 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006968{
François Gaffie11d30102018-11-02 16:09:09 +01006969 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006970 uint32_t muteWaitMs;
6971
6972 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006973 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6974 nullptr /* patchHandle */, requiresMuteCheck);
6975 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6976 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006977 return muteWaitMs;
6978 }
Eric Laurente552edb2014-03-10 17:42:56 -07006979
6980 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006981 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006982 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006983 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006984
François Gaffie11d30102018-11-02 16:09:09 +01006985 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6986
6987 if (!filteredDevices.isEmpty()) {
6988 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006989 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006990
6991 // if the outputs are not materially active, there is no need to mute.
6992 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006993 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006994 } else {
6995 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6996 muteWaitMs = 0;
6997 }
Eric Laurente552edb2014-03-10 17:42:56 -07006998
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006999 bool outputRouted = outputDesc->isRouted();
7000
Eric Laurent79ea9582020-06-11 18:49:24 -07007001 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7002 // output profile or if new device is not supported AND previous device(s) is(are) still
7003 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007004 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007005 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7006 // restore previous device after evaluating strategy mute state
7007 outputDesc->setDevices(prevDevices);
7008 return muteWaitMs;
7009 }
7010
Eric Laurente552edb2014-03-10 17:42:56 -07007011 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007012 // the requested device is AUDIO_DEVICE_NONE
7013 // OR the requested device is the same as current device
7014 // AND force is not specified
7015 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007016 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007017 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007018 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7019 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007020 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7021 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7022 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7023 }
Eric Laurente552edb2014-03-10 17:42:56 -07007024 return muteWaitMs;
7025 }
7026
François Gaffie11d30102018-11-02 16:09:09 +01007027 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007028
Eric Laurente552edb2014-03-10 17:42:56 -07007029 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007030 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007031 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007032 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007033 PatchBuilder patchBuilder;
7034 patchBuilder.addSource(outputDesc);
7035 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7036 for (const auto &filteredDevice : filteredDevices) {
7037 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007038 }
7039
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007040 // Add half reported latency to delayMs when muteWaitMs is null in order
7041 // to avoid disordered sequence of muting volume and changing devices.
7042 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7043 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007044 }
Eric Laurente552edb2014-03-10 17:42:56 -07007045
7046 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007047 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007048
7049 return muteWaitMs;
7050}
7051
Eric Laurentc75307b2015-03-17 15:29:32 -07007052status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007053 int delayMs,
7054 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007055{
Eric Laurent6a94d692014-05-20 11:18:06 -07007056 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007057 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7058 return INVALID_OPERATION;
7059 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007060 if (patchHandle) {
7061 index = mAudioPatches.indexOfKey(*patchHandle);
7062 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007063 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007064 }
7065 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007066 return INVALID_OPERATION;
7067 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007068 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007069 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007070 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007071 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007072 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007073 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007074 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007075 return status;
7076}
7077
7078status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007079 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007080 bool force,
7081 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007082{
7083 status_t status = NO_ERROR;
7084
Eric Laurent1f2f2232014-06-02 12:01:23 -07007085 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007086 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7087 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007088
François Gaffie11d30102018-11-02 16:09:09 +01007089 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007090 PatchBuilder patchBuilder;
7091 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007092 // AUDIO_SOURCE_HOTWORD is for internal use only:
7093 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007094 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7095 auto result = usecase;
7096 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7097 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7098 }
7099 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007100 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007101 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007102 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007103 }
7104 }
7105 return status;
7106}
7107
Eric Laurent6a94d692014-05-20 11:18:06 -07007108status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7109 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007110{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007111 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007112 ssize_t index;
7113 if (patchHandle) {
7114 index = mAudioPatches.indexOfKey(*patchHandle);
7115 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007116 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007117 }
7118 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007119 return INVALID_OPERATION;
7120 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007121 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007122 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007123 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007124 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007125 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007126 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007127 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007128 return status;
7129}
7130
François Gaffie11d30102018-11-02 16:09:09 +01007131sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007132 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007133 audio_format_t& format,
7134 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007135 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007136{
7137 // Choose an input profile based on the requested capture parameters: select the first available
7138 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007139 //
7140 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7141 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007142
Glenn Kasten730b9262018-03-29 15:01:26 -07007143 sp<IOProfile> firstInexact;
7144 uint32_t updatedSamplingRate = 0;
7145 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7146 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007147 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007148 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007149 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007150 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007151 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007152 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007153 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007154 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007155 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007156 &channelMask /*updatedChannelMask*/,
7157 // FIXME ugly cast
7158 (audio_output_flags_t) flags,
7159 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007160 return profile;
7161 }
François Gaffie11d30102018-11-02 16:09:09 +01007162 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007163 samplingRate,
7164 &updatedSamplingRate,
7165 format,
7166 &updatedFormat,
7167 channelMask,
7168 &updatedChannelMask,
7169 // FIXME ugly cast
7170 (audio_output_flags_t) flags,
7171 false /*exactMatchRequiredForInputFlags*/)) {
7172 firstInexact = profile;
7173 }
7174
Eric Laurente552edb2014-03-10 17:42:56 -07007175 }
7176 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007177 if (firstInexact != nullptr) {
7178 samplingRate = updatedSamplingRate;
7179 format = updatedFormat;
7180 channelMask = updatedChannelMask;
7181 return firstInexact;
7182 }
Eric Laurente552edb2014-03-10 17:42:56 -07007183 return NULL;
7184}
7185
François Gaffieaaac0fd2018-11-22 17:56:39 +01007186float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7187 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007188 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007189 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007190{
jiabin9a3361e2019-10-01 09:38:30 -07007191 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007192
7193 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7194 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7195 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7196 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007197 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7198 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7199 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7200 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7201 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007202
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007203 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007204 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7205 mOutputs.isActive(ringVolumeSrc, 0)) {
7206 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007207 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007208 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007209 }
7210
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007211 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007212 if ((volumeSource != callVolumeSrc && (isInCall() ||
7213 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007214 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007215 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7216 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007217 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7218 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7219 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007220 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007221 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007222 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007223 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007224 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007225 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007226 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7227 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7228 // programmatically muted.
7229 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7230 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7231 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007232 bool exemptFromCapping =
7233 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7234 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007235 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7236 volumeSource, volumeDb);
7237 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007238 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7239 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7240 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007241 }
7242 }
Eric Laurente552edb2014-03-10 17:42:56 -07007243 // if a headset is connected, apply the following rules to ring tones and notifications
7244 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007245 // - always attenuate notifications volume by 6dB
7246 // - attenuate ring tones volume by 6dB unless music is not playing and
7247 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007248 // - if music is playing, always limit the volume to current music volume,
7249 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007250 if (!Intersection(deviceTypes,
7251 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7252 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007253 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7254 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007255 ((volumeSource == alarmVolumeSrc ||
7256 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007257 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7258 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7259 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007260 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7261 curves.canBeMuted()) {
7262
Eric Laurente552edb2014-03-10 17:42:56 -07007263 // when the phone is ringing we must consider that music could have been paused just before
7264 // by the music application and behave as if music was active if the last music track was
7265 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007266 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007267 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007268 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007269 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007270 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7271 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007272 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007273 float musicVolDb = computeVolume(musicCurves,
7274 musicVolumeSrc,
7275 musicCurves.getVolumeIndex(musicDevice),
7276 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007277 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7278 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7279 if (volumeDb > minVolDb) {
7280 volumeDb = minVolDb;
7281 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007282 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007283 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7284 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7285 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007286 // on A2DP, also ensure notification volume is not too low compared to media when
7287 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007288 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007289 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007290 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7291 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007292 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7293 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007294 }
7295 }
jiabin9a3361e2019-10-01 09:38:30 -07007296 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007297 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007298 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007299 }
7300 }
7301
François Gaffie43c73442018-11-08 08:21:55 +01007302 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007303}
7304
Eric Laurent3839bc02018-07-10 18:33:34 -07007305int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007306 VolumeSource fromVolumeSource,
7307 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007308{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007309 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007310 return srcIndex;
7311 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007312 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7313 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007314 float minSrc = (float)srcCurves.getVolumeIndexMin();
7315 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7316 float minDst = (float)dstCurves.getVolumeIndexMin();
7317 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007318
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007319 // preserve mute request or correct range
7320 if (srcIndex < minSrc) {
7321 if (srcIndex == 0) {
7322 return 0;
7323 }
7324 srcIndex = minSrc;
7325 } else if (srcIndex > maxSrc) {
7326 srcIndex = maxSrc;
7327 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007328 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7329}
7330
François Gaffieaaac0fd2018-11-22 17:56:39 +01007331status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7332 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007333 int index,
7334 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007335 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007336 int delayMs,
7337 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007338{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007339 // do not change actual attributes volume if the attributes is muted
7340 if (outputDesc->isMuted(volumeSource)) {
7341 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7342 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007343 return NO_ERROR;
7344 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007345 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7346 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7347 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7348 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007349
Eric Laurent2517af32020-11-25 15:31:27 +01007350 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007351 bool isHAUsed = isHearingAidUsedForComm();
7352
Eric Laurente552edb2014-03-10 17:42:56 -07007353 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007354 // if sco and call follow same curves, bypass forceUseForComm
7355 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007356 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007357 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7358 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007359 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007360 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007361 // Do not return an error here as AudioService will always set both voice call
7362 // and bluetooth SCO volumes due to stream aliasing.
7363 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007364 }
jiabin9a3361e2019-10-01 09:38:30 -07007365 if (deviceTypes.empty()) {
7366 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007367 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007368
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007369 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7370 ALOGE("invalid volume index range");
7371 return BAD_VALUE;
7372 }
7373
jiabin9a3361e2019-10-01 09:38:30 -07007374 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7375 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007376 // Force VoIP volume to max for bluetooth SCO device except if muted
7377 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007378 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007379 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007380 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007381 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007382 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007383 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007384
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007385 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007386 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007387 // 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 +01007388 if (isVoiceVolSrc) {
7389 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007390 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007391 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007392 }
Eric Laurent18fba842016-03-31 14:41:26 -07007393 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007394 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7395 mLastVoiceVolume = voiceVolume;
7396 }
7397 }
Eric Laurente552edb2014-03-10 17:42:56 -07007398 return NO_ERROR;
7399}
7400
Eric Laurentc75307b2015-03-17 15:29:32 -07007401void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007402 const DeviceTypeSet& deviceTypes,
7403 int delayMs,
7404 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007405{
jiabincd510522020-01-22 09:40:55 -08007406 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007407 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7408 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7409 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007410 curves.getVolumeIndex(deviceTypes),
7411 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007412 }
7413}
7414
François Gaffiec005e562018-11-06 15:04:49 +01007415void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7416 bool on,
7417 const sp<AudioOutputDescriptor>& outputDesc,
7418 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007419 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007420{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007421 std::vector<VolumeSource> sourcesToMute;
7422 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7423 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7424 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007425 VolumeSource source = toVolumeSource(attributes, false);
7426 if ((source != VOLUME_SOURCE_NONE) &&
7427 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7428 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007429 sourcesToMute.push_back(source);
7430 }
Eric Laurente552edb2014-03-10 17:42:56 -07007431 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007432 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007433 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007434 }
7435
Eric Laurente552edb2014-03-10 17:42:56 -07007436}
7437
François Gaffieaaac0fd2018-11-22 17:56:39 +01007438void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7439 bool on,
7440 const sp<AudioOutputDescriptor>& outputDesc,
7441 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007442 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007443{
jiabin9a3361e2019-10-01 09:38:30 -07007444 if (deviceTypes.empty()) {
7445 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007446 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007447 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007448 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007449 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007450 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007451 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007452 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7453 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007454 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007455 }
7456 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007457 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7458 // ignored
7459 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007460 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007461 if (!outputDesc->isMuted(volumeSource)) {
7462 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007463 return;
7464 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007465 if (outputDesc->decMuteCount(volumeSource) == 0) {
7466 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007467 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007468 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007469 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007470 delayMs);
7471 }
7472 }
7473}
7474
François Gaffie53615e22015-03-19 09:24:12 +01007475bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7476{
François Gaffiec005e562018-11-06 15:04:49 +01007477 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007478 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7479 return true;
7480 }
7481
7482 // has known usage?
7483 switch (paa->usage) {
7484 case AUDIO_USAGE_UNKNOWN:
7485 case AUDIO_USAGE_MEDIA:
7486 case AUDIO_USAGE_VOICE_COMMUNICATION:
7487 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7488 case AUDIO_USAGE_ALARM:
7489 case AUDIO_USAGE_NOTIFICATION:
7490 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7491 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7492 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7493 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7494 case AUDIO_USAGE_NOTIFICATION_EVENT:
7495 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7496 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7497 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7498 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007499 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007500 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007501 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007502 case AUDIO_USAGE_EMERGENCY:
7503 case AUDIO_USAGE_SAFETY:
7504 case AUDIO_USAGE_VEHICLE_STATUS:
7505 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007506 break;
7507 default:
7508 return false;
7509 }
7510 return true;
7511}
7512
François Gaffie2110e042015-03-24 08:41:51 +01007513audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7514{
7515 return mEngine->getForceUse(usage);
7516}
7517
Eric Laurent96d1dda2022-03-14 17:14:19 +01007518bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007519 return isStateInCall(mEngine->getPhoneState());
7520}
7521
Eric Laurent96d1dda2022-03-14 17:14:19 +01007522bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007523 return is_state_in_call(state);
7524}
7525
Eric Laurentf9cccec2022-11-16 19:12:00 +01007526bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007527 audio_mode_t mode = mEngine->getPhoneState();
7528 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007529 || (mode == AUDIO_MODE_CALL_SCREEN)
7530 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007531}
7532
Eric Laurentf9cccec2022-11-16 19:12:00 +01007533bool AudioPolicyManager::isInCallOrScreening() const {
7534 audio_mode_t mode = mEngine->getPhoneState();
7535 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7536}
7537
Eric Laurentd60560a2015-04-10 11:31:20 -07007538void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7539{
7540 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007541 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007542 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007543 sourceDesc->sinkDevice()->equals(deviceDesc))
7544 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007545 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007546 }
7547 }
7548
7549 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7550 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7551 bool release = false;
7552 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7553 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7554 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7555 source->ext.device.type == deviceDesc->type()) {
7556 release = true;
7557 }
7558 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007559 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007560 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7561 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7562 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007563 sink->ext.device.type == deviceDesc->type() &&
7564 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7565 || strncmp(sink->ext.device.address, address,
7566 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007567 release = true;
7568 }
7569 }
7570 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007571 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7572 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007573 }
7574 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007575
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007576 mInputs.clearSessionRoutesForDevice(deviceDesc);
7577
Francois Gaffie716e1432019-01-14 16:58:59 +01007578 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007579}
7580
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007581void AudioPolicyManager::modifySurroundFormats(
7582 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007583 std::unordered_set<audio_format_t> enforcedSurround(
7584 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007585 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7586 for (const auto& pair : mConfig.getSurroundFormats()) {
7587 allSurround.insert(pair.first);
7588 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7589 }
Phil Burk09bc4612016-02-24 15:58:15 -08007590
7591 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7592 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007593 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007594 // This is the resulting set of formats depending on the surround mode:
7595 // 'all surround' = allSurround
7596 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7597 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7598 // 'manual surround' = mManualSurroundFormats
7599 // AUTO: formats v 'enforced surround'
7600 // ALWAYS: formats v 'all surround' v 'enforced surround'
7601 // NEVER: formats ^ 'non-surround'
7602 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007603
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007604 std::unordered_set<audio_format_t> formatSet;
7605 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7606 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007608 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007609 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007610 formatSet.insert(*formatIter);
7611 }
7612 }
7613 } else {
7614 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7615 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007616 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007617
jiabin81772902018-04-02 17:52:27 -07007618 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007619 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007620 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7621 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7622 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007623 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007624 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7625 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7626 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007627 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007628 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007629 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007630 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007631 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007632 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007633}
7634
jiabin06e4bab2019-07-29 10:13:34 -07007635void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7636 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007637 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7638 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7639
7640 // If NEVER, then remove support for channelMasks > stereo.
7641 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007642 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7643 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007644 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007645 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007646 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007647 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007648 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007649 }
7650 }
jiabin81772902018-04-02 17:52:27 -07007651 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7652 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7653 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007654 bool supports5dot1 = false;
7655 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007656 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007657 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7658 supports5dot1 = true;
7659 break;
7660 }
7661 }
7662 // If not then add 5.1 support.
7663 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007664 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007665 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007666 }
Phil Burk09bc4612016-02-24 15:58:15 -08007667 }
7668}
7669
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007670void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007671 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007672 AudioProfileVector &profiles)
7673{
7674 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007675 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007676
François Gaffie112b0af2015-11-19 16:13:25 +01007677 // Format MUST be checked first to update the list of AudioProfile
7678 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007679 reply = mpClientInterface->getParameters(
7680 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007681 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007682 AudioParameter repliedParameters(reply);
7683 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007684 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007685 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7686 return;
7687 }
Phil Burk09bc4612016-02-24 15:58:15 -08007688 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007689 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007690 if (device == AUDIO_DEVICE_OUT_HDMI
7691 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007692 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007693 }
jiabin3e277cc2019-09-10 14:27:34 -07007694 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007695 }
François Gaffie112b0af2015-11-19 16:13:25 +01007696
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007697 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007698 ChannelMaskSet channelMasks;
7699 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007700 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007701 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007702
7703 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007704 reply = mpClientInterface->getParameters(
7705 ioHandle,
7706 requestedParameters.toString() + ";" +
7707 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007708 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007709 AudioParameter repliedParameters(reply);
7710 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007711 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007712 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007713 }
7714 }
7715 if (profiles.hasDynamicChannelsFor(format)) {
7716 reply = mpClientInterface->getParameters(ioHandle,
7717 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007718 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007719 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007720 AudioParameter repliedParameters(reply);
7721 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007722 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007723 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007724 if (device == AUDIO_DEVICE_OUT_HDMI
7725 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007726 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007727 }
François Gaffie112b0af2015-11-19 16:13:25 +01007728 }
7729 }
jiabin3e277cc2019-09-10 14:27:34 -07007730 addDynamicAudioProfileAndSort(
7731 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007732 }
7733}
Eric Laurentd60560a2015-04-10 11:31:20 -07007734
Mikhail Naganovdc769682018-05-04 15:34:08 -07007735status_t AudioPolicyManager::installPatch(const char *caller,
7736 audio_patch_handle_t *patchHandle,
7737 AudioIODescriptorInterface *ioDescriptor,
7738 const struct audio_patch *patch,
7739 int delayMs)
7740{
7741 ssize_t index = mAudioPatches.indexOfKey(
7742 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7743 *patchHandle : ioDescriptor->getPatchHandle());
7744 sp<AudioPatch> patchDesc;
7745 status_t status = installPatch(
7746 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7747 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007748 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007749 }
7750 return status;
7751}
7752
7753status_t AudioPolicyManager::installPatch(const char *caller,
7754 ssize_t index,
7755 audio_patch_handle_t *patchHandle,
7756 const struct audio_patch *patch,
7757 int delayMs,
7758 uid_t uid,
7759 sp<AudioPatch> *patchDescPtr)
7760{
7761 sp<AudioPatch> patchDesc;
7762 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7763 if (index >= 0) {
7764 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007765 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007766 }
7767
7768 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7769 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7770 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7771 if (status == NO_ERROR) {
7772 if (index < 0) {
7773 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007774 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007775 } else {
7776 patchDesc->mPatch = *patch;
7777 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007778 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007779 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007780 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007781 }
7782 nextAudioPortGeneration();
7783 mpClientInterface->onAudioPatchListUpdate();
7784 }
7785 if (patchDescPtr) *patchDescPtr = patchDesc;
7786 return status;
7787}
7788
jiabinbce0c1d2020-10-05 11:20:18 -07007789bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7790{
7791 const TrackClientVector activeClients = output->getActiveClients();
7792 if (activeClients.empty()) {
7793 return true;
7794 }
7795 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7796 if (index < 0) {
7797 ALOGE("%s, no audio patch found while there are active clients on output %d",
7798 __func__, output->getId());
7799 return false;
7800 }
7801 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7802 DeviceVector routedDevices;
7803 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7804 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7805 patchDesc->mPatch.sinks[i].id);
7806 if (device == nullptr) {
7807 ALOGE("%s, no audio device found with id(%d)",
7808 __func__, patchDesc->mPatch.sinks[i].id);
7809 return false;
7810 }
7811 routedDevices.add(device);
7812 }
7813 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007814 if (client->isInvalid()) {
7815 // No need to take care about invalidated clients.
7816 continue;
7817 }
jiabinbce0c1d2020-10-05 11:20:18 -07007818 sp<DeviceDescriptor> preferredDevice =
7819 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7820 if (mEngine->getOutputDevicesForAttributes(
7821 client->attributes(), preferredDevice, false) == routedDevices) {
7822 return false;
7823 }
7824 }
7825 return true;
7826}
7827
7828sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007829 const sp<IOProfile>& profile, const DeviceVector& devices,
7830 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007831{
7832 for (const auto& device : devices) {
7833 // TODO: This should be checking if the profile supports the device combo.
7834 if (!profile->supportsDevice(device)) {
7835 return nullptr;
7836 }
7837 }
7838 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7839 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007840 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007841 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7842 if (status != NO_ERROR) {
7843 return nullptr;
7844 }
7845
7846 // Here is where the out_set_parameters() for card & device gets called
7847 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7848 const audio_devices_t deviceType = device->type();
7849 const String8 &address = String8(device->address().c_str());
7850 if (!address.isEmpty()) {
7851 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7852 mpClientInterface->setParameters(output, String8(param));
7853 free(param);
7854 }
7855 updateAudioProfiles(device, output, profile->getAudioProfiles());
7856 if (!profile->hasValidAudioProfile()) {
7857 ALOGW("%s() missing param", __func__);
7858 desc->close();
7859 return nullptr;
7860 } else if (profile->hasDynamicAudioProfile()) {
7861 desc->close();
7862 output = AUDIO_IO_HANDLE_NONE;
7863 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7864 profile->pickAudioProfile(
7865 config.sample_rate, config.channel_mask, config.format);
7866 config.offload_info.sample_rate = config.sample_rate;
7867 config.offload_info.channel_mask = config.channel_mask;
7868 config.offload_info.format = config.format;
7869
Eric Laurentb4f42a92022-01-17 17:37:31 +01007870 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007871 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7872 if (status != NO_ERROR) {
7873 return nullptr;
7874 }
7875 }
7876
7877 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007878
baek.kim -61c20122022-07-27 10:05:32 +00007879 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7880 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7881
jiabinbce0c1d2020-10-05 11:20:18 -07007882 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7883 sp<AudioPolicyMix> policyMix;
7884 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7885 policyMix->setOutput(desc);
7886 desc->mPolicyMix = policyMix;
7887 } else {
7888 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7889 address.string());
7890 }
7891
baek.kim -61c20122022-07-27 10:05:32 +00007892 } else if (hasPrimaryOutput() && speaker != nullptr
7893 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007894 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7895 // no duplicated output for:
7896 // - direct outputs
7897 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007898 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007899 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7900
7901 //TODO: configure audio effect output stage here
7902
7903 // open a duplicating output thread for the new output and the primary output
7904 sp<SwAudioOutputDescriptor> dupOutputDesc =
7905 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7906 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7907 if (status == NO_ERROR) {
7908 // add duplicated output descriptor
7909 addOutput(duplicatedOutput, dupOutputDesc);
7910 } else {
7911 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7912 mPrimaryOutput->mIoHandle, output);
7913 desc->close();
7914 removeOutput(output);
7915 nextAudioPortGeneration();
7916 return nullptr;
7917 }
7918 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007919 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7920 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7921 mPrimaryOutput = desc;
7922 }
jiabinbce0c1d2020-10-05 11:20:18 -07007923 return desc;
7924}
7925
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007926} // namespace android