blob: c854044300eadf087f4e15b559ff7e976dc773a0 [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) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001275 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001276 *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 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001534 // A request for Tuner cannot fallback to a mixed output
1535 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1536 return AUDIO_IO_HANDLE_NONE;
1537 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001538
Eric Laurente552edb2014-03-10 17:42:56 -07001539 // ignoring channel mask due to downmix capability in mixer
1540
1541 // open a non direct output
1542
1543 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001544 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001545 // get which output is suitable for the specified stream. The actual
1546 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001547 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001548
Eric Laurent8838a382014-09-08 16:44:28 -07001549 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001550 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001551 output = selectOutput(
1552 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001553 }
François Gaffie11d30102018-11-02 16:09:09 +01001554 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001555 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001556 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001557
Eric Laurente552edb2014-03-10 17:42:56 -07001558 return output;
1559}
1560
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001561sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001562 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1563 mAvailableInputDevices);
1564 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1565}
1566
1567DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1568 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1569 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001570}
1571
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001572const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001573 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001574 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1575 if (msdModule != 0) {
1576 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1577 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1578 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1579 const struct audio_port_config *source = &patch->mPatch.sources[j];
1580 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1581 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001582 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001583 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001584 }
1585 }
1586 }
1587 return msdPatches;
1588}
1589
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001590bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1591 ssize_t index = mAudioPatches.indexOfKey(handle);
1592 if (index < 0) {
1593 return false;
1594 }
1595 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1596 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1597 if (msdModule == nullptr) {
1598 return false;
1599 }
1600 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1601 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1602 return true;
1603 }
1604 index = getMsdOutputPatches().indexOfKey(handle);
1605 if (index < 0) {
1606 return false;
1607 }
1608 return true;
1609}
1610
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001611status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1612 const InputProfileCollection &inputProfiles,
1613 const OutputProfileCollection &outputProfiles,
1614 const sp<DeviceDescriptor> &sourceDevice,
1615 const sp<DeviceDescriptor> &sinkDevice,
1616 AudioProfileVector& sourceProfiles,
1617 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001618 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001619 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001620 return NO_INIT;
1621 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 return NO_INIT;
1625 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001627 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1628 inProfile->supportsDevice(sourceDevice)) {
1629 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 }
1631 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001633 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001634 outProfile->supportsDevice(sinkDevice)) {
1635 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 }
1637 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001638 return NO_ERROR;
1639}
1640
1641status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1642 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1643 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1644{
Dean Wheatley16809da2022-12-09 14:55:46 +11001645 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1646 static const std::vector<audio_format_t> formatsOrder = {{
1647 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1648 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1649 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1650 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1651 // preferred).
1652 std::vector<audio_channel_mask_t> masks = {{
1653 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1654 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1655 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1656 // insert index masks (higher counts most preferred) as preferred over position masks
1657 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1658 masks.insert(
1659 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1660 }
1661 return masks;
1662 }();
1663
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001664 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001665 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1666 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001667 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001668 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1669 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001670 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001671 }
1672 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1673 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1674 sinkConfig->format = bestSinkConfig.format;
1675 // For encoded streams force direct flag to prevent downstream mixing.
1676 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1677 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001678 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1679 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001681 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1682 // raw and IEC61937 framed streams.
1683 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1684 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1685 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001686 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1687 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001688 sourceConfig->channel_mask =
1689 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1690 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1691 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 sourceConfig->format = bestSinkConfig.format;
1693 // Copy input stream directly without any processing (e.g. resampling).
1694 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1695 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1696 if (hwAvSync) {
1697 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1698 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1699 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1700 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1701 }
1702 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1703 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1704 sinkConfig->config_mask |= config_mask;
1705 sourceConfig->config_mask |= config_mask;
1706 return NO_ERROR;
1707}
1708
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001709PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1710 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711{
1712 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1714 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1715 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1716 if (deviceModule == nullptr) {
1717 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1718 return patchBuilder;
1719 }
1720 const InputProfileCollection inputProfiles = msdIsSource ?
1721 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1722 const OutputProfileCollection outputProfiles = msdIsSource ?
1723 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1724
1725 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1726 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1727 device : getMsdAudioOutDevices().itemAt(0);
1728 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1729
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1731 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001732 AudioProfileVector sourceProfiles;
1733 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1735 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001736 for (auto hwAvSync : { true, false }) {
1737 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1738 sourceProfiles, sinkProfiles) != NO_ERROR) {
1739 continue;
1740 }
1741 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1742 &sinkConfig) == NO_ERROR) {
1743 // Found a matching config. Re-create PatchBuilder with this config.
1744 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1745 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001747 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748 " supporting PCM format conversion.", __func__);
1749 return patchBuilder;
1750}
1751
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001752status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001753 DeviceVector devices;
1754 if (outputDevices != nullptr && outputDevices->size() > 0) {
1755 devices.add(*outputDevices);
1756 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001757 // Use media strategy for unspecified output device. This should only
1758 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1759 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001760 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001761 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001762 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001763 }
Michael Chan6fb34492020-12-08 15:44:49 +11001764 std::vector<PatchBuilder> patchesToCreate;
1765 for (auto i = 0u; i < devices.size(); ++i) {
1766 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001767 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001768 }
1769 // Retain only the MSD patches associated with outputDevices request.
1770 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001771 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001772 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1773 auto retainedPatch = false;
1774 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1775 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1776 patchesToRemove.removeItemsAt(i);
1777 retainedPatch = true;
1778 break;
1779 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 }
Michael Chan6fb34492020-12-08 15:44:49 +11001781 if (retainedPatch) {
1782 it = patchesToCreate.erase(it);
1783 continue;
1784 }
1785 ++it;
1786 }
1787 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1788 return NO_ERROR;
1789 }
1790 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1791 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001792 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001793 }
Michael Chan6fb34492020-12-08 15:44:49 +11001794 status_t status = NO_ERROR;
1795 for (const auto &p : patchesToCreate) {
1796 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1797 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1798 char message[256];
1799 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1800 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1801 currStatus == NO_ERROR ? "Success" : "Error",
1802 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1803 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1804 if (currStatus == NO_ERROR) {
1805 ALOGD("%s", message);
1806 } else {
1807 ALOGE("%s", message);
1808 if (status == NO_ERROR) {
1809 status = currStatus;
1810 }
1811 }
1812 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001813 return status;
1814}
1815
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001816void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1817 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001818 for (size_t i = 0; i < msdPatches.size(); i++) {
1819 const auto& patch = msdPatches[i];
1820 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1821 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1822 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1823 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1824 releaseAudioPatch(patch->getHandle(), mUidCached);
1825 break;
1826 }
1827 }
1828 }
1829}
1830
Dorin Drimus94d94412022-02-02 09:05:02 +01001831bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07001832 DeviceVector devicesToCheck =
1833 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001834 AudioPatchCollection msdPatches = getMsdOutputPatches();
1835 for (size_t i = 0; i < msdPatches.size(); i++) {
1836 const auto& patch = msdPatches[i];
1837 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1838 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1839 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1840 const auto& foundDevice = devicesToCheck.getDevice(
1841 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1842 if (foundDevice != nullptr) {
1843 devicesToCheck.remove(foundDevice);
1844 if (devicesToCheck.isEmpty()) {
1845 return true;
1846 }
1847 }
1848 }
1849 }
1850 }
1851 return false;
1852}
1853
Eric Laurente0720872014-03-11 09:30:41 -07001854audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001855 audio_output_flags_t flags,
1856 audio_format_t format,
1857 audio_channel_mask_t channelMask,
1858 uint32_t samplingRate,
1859 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001860{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001861 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1862 "%s called with format %#x", __func__, format);
1863
jiabinebb6af42020-06-09 17:31:17 -07001864 // Return the output that haptic-generating attached to when 1) session id is specified,
1865 // 2) haptic-generating effect exists for given session id and 3) the output that
1866 // haptic-generating effect attached to is in given outputs.
1867 if (sessionId != AUDIO_SESSION_NONE) {
1868 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1869 sessionId, FX_IID_HAPTICGENERATOR);
1870 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1871 return hapticGeneratingOutput;
1872 }
1873 }
1874
Eric Laurent16c66dd2019-05-01 17:54:10 -07001875 // Flags disqualifying an output: the match must happen before calling selectOutput()
1876 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1877 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1878
1879 // Flags expressing a functional request: must be honored in priority over
1880 // other criteria
1881 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1882 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001883 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1884 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001885 // Flags expressing a performance request: have lower priority than serving
1886 // requested sampling rate or channel mask
1887 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1888 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1889 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1890
1891 const audio_output_flags_t functionalFlags =
1892 (audio_output_flags_t)(flags & kFunctionalFlags);
1893 const audio_output_flags_t performanceFlags =
1894 (audio_output_flags_t)(flags & kPerformanceFlags);
1895
1896 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1897
Eric Laurente552edb2014-03-10 17:42:56 -07001898 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001899 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001900 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001901 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001902 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001903 // with tiebreak preferring the minimum number of extra functional flags
1904 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001905 // 3: the output supporting the exact channel mask
1906 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001907 // 5: the output with the highest sampling rate if the requested sample rate is
1908 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001909 // 6: the output with the highest number of requested performance flags
1910 // 7: the output with the bit depth the closest to the requested one
1911 // 8: the primary output
1912 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001913
Eric Laurent16c66dd2019-05-01 17:54:10 -07001914 // matching criteria values in priority order for best matching output so far
1915 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001916
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1918 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1919 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001920
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001921 for (audio_io_handle_t output : outputs) {
1922 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001923 // matching criteria values in priority order for current output
1924 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001925
Eric Laurent16c66dd2019-05-01 17:54:10 -07001926 if (outputDesc->isDuplicated()) {
1927 continue;
1928 }
1929 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1930 continue;
1931 }
Eric Laurent8838a382014-09-08 16:44:28 -07001932
Eric Laurent16c66dd2019-05-01 17:54:10 -07001933 // If haptic channel is specified, use the haptic output if present.
1934 // When using haptic output, same audio format and sample rate are required.
1935 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001936 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001937 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1938 continue;
1939 }
1940 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001941 && format == outputDesc->getFormat()
1942 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001943 currentMatchCriteria[0] = outputHapticChannelCount;
1944 }
1945
1946 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001947 const int matchingFunctionalFlags =
1948 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1949 const int totalFunctionalFlags =
1950 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1951 // Prefer matching functional flags, but subtract unnecessary functional flags.
1952 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953
1954 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001955 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1956 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001957 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1958 channelCount <= outputChannelCount) {
1959 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001960 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1961 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001962 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001963 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001964 currentMatchCriteria[3] = outputChannelCount;
1965 }
1966
1967 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001968 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001969 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001970 }
1971
1972 // performance flags match
1973 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1974
1975 // format match
1976 if (format != AUDIO_FORMAT_INVALID) {
1977 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001978 PolicyAudioPort::kFormatDistanceMax -
1979 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001980 }
1981
1982 // primary output match
1983 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1984
1985 // compare match criteria by priority then value
1986 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1987 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1988 bestMatchCriteria = currentMatchCriteria;
1989 bestOutput = output;
1990
1991 std::stringstream result;
1992 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1993 std::ostream_iterator<int>(result, " "));
1994 ALOGV("%s new bestOutput %d criteria %s",
1995 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001996 }
1997 }
1998
Eric Laurent16c66dd2019-05-01 17:54:10 -07001999 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002000}
2001
Eric Laurent8fc147b2018-07-22 19:13:55 -07002002status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002003{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002004 ALOGV("%s portId %d", __FUNCTION__, portId);
2005
2006 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2007 if (outputDesc == 0) {
2008 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002009 return BAD_VALUE;
2010 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002011 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002012
Eric Laurent8fc147b2018-07-22 19:13:55 -07002013 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002014 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002015
Eric Laurent733ce942017-12-07 12:18:25 -08002016 status_t status = outputDesc->start();
2017 if (status != NO_ERROR) {
2018 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002019 }
2020
Eric Laurent97ac8712018-07-27 18:59:02 -07002021 uint32_t delayMs;
2022 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002023
2024 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002025 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002026 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002027 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002028 if (delayMs != 0) {
2029 usleep(delayMs * 1000);
2030 }
2031
2032 return status;
2033}
2034
Eric Laurent96d1dda2022-03-14 17:14:19 +01002035bool AudioPolicyManager::isLeUnicastActive() const {
2036 if (isInCall()) {
2037 return true;
2038 }
2039 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2040}
2041
2042bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2043 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2044 return false;
2045 }
2046 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2047 ALOGV("%s active %d", __func__, active);
2048 return active;
2049}
2050
Eric Laurent97ac8712018-07-27 18:59:02 -07002051status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2052 const sp<TrackClientDescriptor>& client,
2053 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002054{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002055 // cannot start playback of STREAM_TTS if any other output is being used
2056 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002057
2058 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002059 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002060 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002061 auto clientStrategy = client->strategy();
2062 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002063 if (stream == AUDIO_STREAM_TTS) {
2064 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002065 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002066 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002067 return INVALID_OPERATION;
2068 } else {
2069 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2070 }
2071 } else {
2072 // some playback other than beacon starts
2073 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2074 }
2075
Eric Laurent77305a62016-07-25 16:39:22 -07002076 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002077 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002078 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002079
François Gaffie11d30102018-11-02 16:09:09 +01002080 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002081 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002082 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002083 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002084 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002085 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002086 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002087 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002088 } else {
2089 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002090 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002091 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2092 AUDIO_FORMAT_DEFAULT);
2093 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2094 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002095 }
2096
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002097 // requiresMuteCheck is false when we can bypass mute strategy.
2098 // It covers a common case when there is no materially active audio
2099 // and muting would result in unnecessary delay and dropped audio.
2100 const uint32_t outputLatencyMs = outputDesc->latency();
2101 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002102 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002103
Eric Laurente552edb2014-03-10 17:42:56 -07002104 // increment usage count for this stream on the requested output:
2105 // NOTE that the usage count is the same for duplicated output and hardware output which is
2106 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002107 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002108
2109 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002110 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2111 client->isPreferredDeviceForExclusiveUse()) {
2112 // Preferred device may be exclusive, use only if no other active clients on this output
2113 devices = DeviceVector(
2114 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2115 } else {
2116 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2117 }
François Gaffie11d30102018-11-02 16:09:09 +01002118 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002119 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002120 }
2121 }
Eric Laurente552edb2014-03-10 17:42:56 -07002122
François Gaffiec005e562018-11-06 15:04:49 +01002123 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002124 selectOutputForMusicEffects();
2125 }
2126
François Gaffie1c878552018-11-22 16:53:21 +01002127 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002128 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002129 if (devices.isEmpty()) {
2130 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002131 }
François Gaffiec005e562018-11-06 15:04:49 +01002132 bool shouldWait =
2133 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2134 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2135 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002136 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002137 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002138 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002139 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002140 // An output has a shared device if
2141 // - managed by the same hw module
2142 // - supports the currently selected device
2143 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002144 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002145
Eric Laurent77305a62016-07-25 16:39:22 -07002146 // force a device change if any other output is:
2147 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002148 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002149 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002150 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002151 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002152 // change the device currently selected by the other output.
2153 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002154 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002155 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002156 force = true;
2157 }
2158 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002159 // a notification so that audio focus effect can propagate, or that a mute/unmute
2160 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002161 const uint32_t latencyMs = desc->latency();
2162 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2163
2164 if (shouldWait && isActive && (waitMs < latencyMs)) {
2165 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002166 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002167
2168 // Require mute check if another output is on a shared device
2169 // and currently active to have proper drain and avoid pops.
2170 // Note restoring AudioTracks onto this output needs to invoke
2171 // a volume ramp if there is no mute.
2172 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002173 }
2174 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002175
2176 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002177 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002178
Eric Laurente552edb2014-03-10 17:42:56 -07002179 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002180 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002181 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002182 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002183 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002184 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002185 outputDesc->useHwGain() /*force*/)) {
2186 // request AudioService to reinitialize the volume curves asynchronously
2187 ALOGE("checkAndSetVolume failed, requesting volume range init");
2188 mpClientInterface->onVolumeRangeInitRequest();
2189 };
Eric Laurente552edb2014-03-10 17:42:56 -07002190
2191 // update the outputs if starting an output with a stream that can affect notification
2192 // routing
2193 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002194
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002195 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002196 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002197 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2198 }
Eric Laurentdc462862016-07-19 12:29:53 -07002199
2200 if (waitMs > muteWaitMs) {
2201 *delayMs = waitMs - muteWaitMs;
2202 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002203
2204 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2205 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2206 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2207 // change occurs after the MixerThread starts and causes a stream volume
2208 // glitch.
2209 //
2210 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002211 }
Eric Laurentdc462862016-07-19 12:29:53 -07002212
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002213 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002214 mEngine->getForceUse(
2215 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002216 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002217 }
2218
Eric Laurent97ac8712018-07-27 18:59:02 -07002219 // Automatically enable the remote submix input when output is started on a re routing mix
2220 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002221 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2222 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002223 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2224 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2225 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002226 "remote-submix",
2227 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002228 }
2229
Eric Laurent96d1dda2022-03-14 17:14:19 +01002230 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2231
Eric Laurente552edb2014-03-10 17:42:56 -07002232 return NO_ERROR;
2233}
2234
Eric Laurent96d1dda2022-03-14 17:14:19 +01002235void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2236 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2237 bool isUnicastActive = isLeUnicastActive();
2238
2239 if (wasUnicastActive != isUnicastActive) {
2240 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2241 for (size_t i = 0; i < mOutputs.size(); i++) {
2242 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2243 if (desc != ignoredOutput && desc->isActive()
2244 && ((isUnicastActive &&
2245 !desc->devices().
2246 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2247 || (wasUnicastActive &&
2248 !desc->devices().getDevicesFromTypes(
2249 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2250 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2251 bool force = desc->devices() != newDevices;
2252 setOutputDevices(desc, newDevices, force, delayMs);
2253 // re-apply device specific volume if not done by setOutputDevice()
2254 if (!force) {
2255 applyStreamVolumes(desc, newDevices.types(), delayMs);
2256 }
2257 }
2258 }
2259 }
2260}
2261
Eric Laurent8fc147b2018-07-22 19:13:55 -07002262status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002263{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002264 ALOGV("%s portId %d", __FUNCTION__, portId);
2265
2266 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2267 if (outputDesc == 0) {
2268 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002269 return BAD_VALUE;
2270 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002271 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002272
Eric Laurent97ac8712018-07-27 18:59:02 -07002273 ALOGV("stopOutput() output %d, stream %d, session %d",
2274 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002275
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002277
Eric Laurent733ce942017-12-07 12:18:25 -08002278 if (status == NO_ERROR ) {
2279 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002280 }
2281 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002282}
2283
Eric Laurent97ac8712018-07-27 18:59:02 -07002284status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2285 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002286{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002287 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002289 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002290 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002291
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002292 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2293
François Gaffie1c878552018-11-22 16:53:21 +01002294 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2295 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002296 // Automatically disable the remote submix input when output is stopped on a
2297 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002298 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002299 if (isSingleDeviceType(
2300 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002301 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002302 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2304 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002305 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002306 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002307 }
2308 }
2309 bool forceDeviceUpdate = false;
2310 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002311 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002312 forceDeviceUpdate = true;
2313 }
2314
Eric Laurente552edb2014-03-10 17:42:56 -07002315 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002316 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002317
Eric Laurente552edb2014-03-10 17:42:56 -07002318 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002319 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002320 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002321 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002322
2323 // If the routing does not change, if an output is routed on a device using HwGain
2324 // (aka setAudioPortConfig) and there are still active clients following different
2325 // volume group(s), force reapply volume
2326 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2327 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2328
Eric Laurente552edb2014-03-10 17:42:56 -07002329 // delay the device switch by twice the latency because stopOutput() is executed when
2330 // the track stop() command is received and at that time the audio track buffer can
2331 // still contain data that needs to be drained. The latency only covers the audio HAL
2332 // and kernel buffers. Also the latency does not always include additional delay in the
2333 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002334 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2335 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002336
2337 // force restoring the device selection on other active outputs if it differs from the
2338 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002339 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002340 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002342 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002343 desc->isActive() &&
2344 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002345 (newDevices != desc->devices())) {
2346 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2347 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002348
François Gaffie11d30102018-11-02 16:09:09 +01002349 setOutputDevices(desc, newDevices2, force, delayMs);
2350
Eric Laurent57de36c2016-09-28 16:59:11 -07002351 // re-apply device specific volume if not done by setOutputDevice()
2352 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002353 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002354 }
Eric Laurente552edb2014-03-10 17:42:56 -07002355 }
2356 }
2357 // update the outputs if stopping one with a stream that can affect notification routing
2358 handleNotificationRoutingForStream(stream);
2359 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002360
2361 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2362 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002363 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002364 }
2365
François Gaffiec005e562018-11-06 15:04:49 +01002366 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002367 selectOutputForMusicEffects();
2368 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002369
2370 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2371
Eric Laurente552edb2014-03-10 17:42:56 -07002372 return NO_ERROR;
2373 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002374 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002375 return INVALID_OPERATION;
2376 }
2377}
2378
jiabinbce0c1d2020-10-05 11:20:18 -07002379bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002380{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002381 ALOGV("%s portId %d", __FUNCTION__, portId);
2382
2383 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2384 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002385 // If an output descriptor is closed due to a device routing change,
2386 // then there are race conditions with releaseOutput from tracks
2387 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2388 // destroyed shortly thereafter.
2389 //
2390 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002391 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002392 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002393 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002394
2395 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002396
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302397 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2398 if (outputDesc->isClientActive(client)) {
2399 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2400 stopOutput(portId);
2401 }
2402
Eric Laurent8fc147b2018-07-22 19:13:55 -07002403 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2404 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002405 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002406 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002407 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002408 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002409 if (--outputDesc->mDirectOpenCount == 0) {
2410 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002411 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002412 }
2413 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302414
Andy Hung39efb7a2018-09-26 15:39:28 -07002415 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002416 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2417 // The output is pending reopened to query dynamic profiles and
2418 // there is no active clients
2419 closeOutput(outputDesc->mIoHandle);
2420 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2421 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2422 if (newOutputDesc == nullptr) {
2423 ALOGE("%s failed to open output", __func__);
2424 }
2425 return true;
2426 }
2427 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002428}
2429
Eric Laurentcaf7f482014-11-25 17:50:47 -08002430status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2431 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002432 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002433 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002434 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002435 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002436 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002437 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002438 input_type_t *inputType,
2439 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002440{
François Gaffiec005e562018-11-06 15:04:49 +01002441 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002442 "flags %#x attributes=%s requested device ID %d",
2443 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2444 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002445
Eric Laurentad2e7b92017-09-14 20:06:42 -07002446 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002447 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002448 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002449 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002450 sp<AudioInputDescriptor> inputDesc;
2451 sp<RecordClientDescriptor> clientDesc;
2452 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002453 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002454 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002455
2456 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2457 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2458 return INVALID_OPERATION;
2459 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002460
Francois Gaffie716e1432019-01-14 16:58:59 +01002461 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2462 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002463 }
2464
Paul McLean466dc8e2015-04-17 13:15:36 -06002465 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002466 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002467 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002468
Eric Laurentad2e7b92017-09-14 20:06:42 -07002469 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2470 // possible
2471 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2472 *input != AUDIO_IO_HANDLE_NONE) {
2473 ssize_t index = mInputs.indexOfKey(*input);
2474 if (index < 0) {
2475 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2476 status = BAD_VALUE;
2477 goto error;
2478 }
2479 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002480 RecordClientVector clients = inputDesc->getClientsForSession(session);
2481 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002482 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2483 status = BAD_VALUE;
2484 goto error;
2485 }
2486 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2487 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002488 // corresponds to a new client and is only permitted from the same UID.
2489 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002490 if (clients.size() > 1) {
2491 for (const auto& client : clients) {
2492 // The client map is ordered by key values (portId) and portIds are allocated
2493 // incrementaly. So the first client in this list is the one opened by audio flinger
2494 // when the mmap stream is created and should be ignored as it does not correspond
2495 // to an actual client
2496 if (client == *clients.cbegin()) {
2497 continue;
2498 }
2499 if (uid != client->uid() && !client->isSilenced()) {
2500 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2501 uid, client->portId(), client->uid());
2502 status = INVALID_OPERATION;
2503 goto error;
2504 }
Eric Laurent331679c2018-04-16 17:03:16 -07002505 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002506 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002507 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002508 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002509
Eric Laurentfecbceb2021-02-09 14:46:43 +01002510 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002511 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002512 }
2513
2514 *input = AUDIO_IO_HANDLE_NONE;
2515 *inputType = API_INPUT_INVALID;
2516
Francois Gaffie716e1432019-01-14 16:58:59 +01002517 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2518 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2519 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002520 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002521 ALOGW("%s could not find input mix for attr %s",
2522 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002523 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002524 }
jiabinc1de2df2019-05-07 14:26:40 -07002525 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2526 String8(attr->tags + strlen("addr=")),
2527 AUDIO_FORMAT_DEFAULT);
2528 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002529 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002530 __func__, attributes.source, attributes.tags);
2531 status = BAD_VALUE;
2532 goto error;
2533 }
2534
Kevin Rocard25f9b052019-02-27 15:08:54 -08002535 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2536 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2537 } else {
2538 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2539 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002540 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002541 if (explicitRoutingDevice != nullptr) {
2542 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002544 // Prevent from storing invalid requested device id in clients
2545 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002546 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002547 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2548 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002549 }
François Gaffie11d30102018-11-02 16:09:09 +01002550 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002551 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002552 status = BAD_VALUE;
2553 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002554 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002555 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2556 *inputType = API_INPUT_MIX_CAPTURE;
2557 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002558 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2559 // there is an external policy, but this input is attached to a mix of recorders,
2560 // meaning it receives audio injected into the framework, so the recorder doesn't
2561 // know about it and is therefore considered "legacy"
2562 *inputType = API_INPUT_LEGACY;
2563 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002564 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002565 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002566 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002567 } else {
2568 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002569 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002570
Eric Laurent599c7582015-12-07 18:05:55 -08002571 }
2572
François Gaffiec005e562018-11-06 15:04:49 +01002573 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002574 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002575 status = INVALID_OPERATION;
2576 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002577 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002578
Eric Laurent8f42ea12018-08-08 09:08:25 -07002579exit:
2580
François Gaffiec005e562018-11-06 15:04:49 +01002581 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2582 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002583
Francois Gaffie716e1432019-01-14 16:58:59 +01002584 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002585 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002586 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002587
Mikhail Naganov2996f672019-04-18 12:29:59 -07002588 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002589 requestedDeviceId, attributes.source, flags,
2590 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002591 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002592 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593
2594 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2595 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002596
Eric Laurent599c7582015-12-07 18:05:55 -08002597 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002598
2599error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002600 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002601}
2602
2603
François Gaffie11d30102018-11-02 16:09:09 +01002604audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002605 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002606 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002607 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002608 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002609 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002610{
2611 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002612 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002613 bool isSoundTrigger = false;
2614
François Gaffiec005e562018-11-06 15:04:49 +01002615 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002616 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2617 if (index >= 0) {
2618 input = mSoundTriggerSessions.valueFor(session);
2619 isSoundTrigger = true;
2620 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2621 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2622 } else {
2623 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002624 }
François Gaffiec005e562018-11-06 15:04:49 +01002625 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002626 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002627 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002628 }
2629
Carter Hsua3abb402021-10-26 11:11:20 +08002630 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2631 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2632 }
2633
Andy Hungf129b032015-04-07 13:45:50 -07002634 // find a compatible input profile (not necessarily identical in parameters)
2635 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002636 // sampling rate and flags may be updated by getInputProfile
2637 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2638 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002639 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002640 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002641 audio_input_flags_t profileFlags = flags;
2642 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002643 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002644 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002645 profileFlags);
2646 if (profile != 0) {
2647 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002648 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2649 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002650 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002651 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2652 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002653 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002654 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002655 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002656 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002657 }
Eric Laurente552edb2014-03-10 17:42:56 -07002658 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002659 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002660 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002661 if (samplingRate == 0) {
2662 samplingRate = profileSamplingRate;
2663 }
Eric Laurente552edb2014-03-10 17:42:56 -07002664
Eric Laurent322b4d22015-04-03 15:57:54 -07002665 if (profile->getModuleHandle() == 0) {
2666 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002667 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002668 }
2669
Eric Laurentec376dc2021-04-08 20:41:22 +02002670 // Reuse an already opened input if a client with the same session ID already exists
2671 // on that input
2672 for (size_t i = 0; i < mInputs.size(); i++) {
2673 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2674 if (desc->mProfile != profile) {
2675 continue;
2676 }
2677 RecordClientVector clients = desc->clientsList();
2678 for (const auto &client : clients) {
2679 if (session == client->session()) {
2680 return desc->mIoHandle;
2681 }
2682 }
2683 }
2684
Eric Laurent3974e3b2017-12-07 17:58:43 -08002685 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002686 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002687 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002688 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002689 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002690 continue;
2691 }
2692 // if sound trigger, reuse input if used by other sound trigger on same session
2693 // else
2694 // reuse input if active client app is not in IDLE state
2695 //
2696 RecordClientVector clients = desc->clientsList();
2697 bool doClose = false;
2698 for (const auto& client : clients) {
2699 if (isSoundTrigger != client->isSoundTrigger()) {
2700 continue;
2701 }
2702 if (client->isSoundTrigger()) {
2703 if (session == client->session()) {
2704 return desc->mIoHandle;
2705 }
2706 continue;
2707 }
2708 if (client->active() && client->appState() != APP_STATE_IDLE) {
2709 return desc->mIoHandle;
2710 }
2711 doClose = true;
2712 }
2713 if (doClose) {
2714 closeInput(desc->mIoHandle);
2715 } else {
2716 i++;
2717 }
2718 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002719 }
2720
Eric Laurentfe231122017-11-17 17:48:06 -08002721 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002722
Eric Laurentfe231122017-11-17 17:48:06 -08002723 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2724 lConfig.sample_rate = profileSamplingRate;
2725 lConfig.channel_mask = profileChannelMask;
2726 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002727
François Gaffie11d30102018-11-02 16:09:09 +01002728 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002729
2730 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002731 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002732 (profileSamplingRate != lConfig.sample_rate) ||
2733 !audio_formats_match(profileFormat, lConfig.format) ||
2734 (profileChannelMask != lConfig.channel_mask)) {
2735 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002736 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002737 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002738 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002739 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002740 }
Eric Laurent599c7582015-12-07 18:05:55 -08002741 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002742 }
2743
Eric Laurentc722f302014-12-10 11:21:49 -08002744 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002745
Eric Laurent599c7582015-12-07 18:05:55 -08002746 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002747 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002748
Eric Laurent599c7582015-12-07 18:05:55 -08002749 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002750}
2751
Eric Laurent4eb58f12018-12-07 16:41:02 -08002752status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002753{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002754 ALOGV("%s portId %d", __FUNCTION__, portId);
2755
2756 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2757 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002759 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002760 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002761 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002762 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763 if (client->active()) {
2764 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2765 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002766 }
2767
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 audio_session_t session = client->session();
2769
Eric Laurent4eb58f12018-12-07 16:41:02 -08002770 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002771
Eric Laurent4eb58f12018-12-07 16:41:02 -08002772 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002773
Eric Laurent4eb58f12018-12-07 16:41:02 -08002774 status_t status = inputDesc->start();
2775 if (status != NO_ERROR) {
2776 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002777 }
Eric Laurente552edb2014-03-10 17:42:56 -07002778
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002779 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002780 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002781 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002782
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783 // indicate active capture to sound trigger service if starting capture from a mic on
2784 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002785 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002786 if (device != nullptr) {
2787 status = setInputDevice(input, device, true /* force */);
2788 } else {
2789 ALOGW("%s no new input device can be found for descriptor %d",
2790 __FUNCTION__, inputDesc->getId());
2791 status = BAD_VALUE;
2792 }
Eric Laurente552edb2014-03-10 17:42:56 -07002793
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002794 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002795 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002796 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002797 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002798 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2799 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002800 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002801 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002802
François Gaffie11d30102018-11-02 16:09:09 +01002803 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2804 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002805 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002806 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002808
Eric Laurent8f42ea12018-08-08 09:08:25 -07002809 // automatically enable the remote submix output when input is started if not
2810 // used by a policy mix of type MIX_TYPE_RECORDERS
2811 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002812 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002813 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002814 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002815 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002816 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2817 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002818 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002819 if (address != "") {
2820 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2821 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002822 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002823 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002824 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002825 } else if (status != NO_ERROR) {
2826 // Restore client activity state.
2827 inputDesc->setClientActive(client, false);
2828 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002829 }
2830
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002831 ALOGV("%s input %d source = %d status = %d exit",
2832 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002833
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002834 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002835}
2836
Eric Laurent8fc147b2018-07-22 19:13:55 -07002837status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002838{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002839 ALOGV("%s portId %d", __FUNCTION__, portId);
2840
2841 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2842 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002843 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002844 return BAD_VALUE;
2845 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002846 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002847 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002848 if (!client->active()) {
2849 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002850 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002851 }
Carter Hsue6139d52021-07-08 10:30:20 +08002852 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002853 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002854
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 inputDesc->stop();
2856 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002857 auto current_source = inputDesc->source();
2858 setInputDevice(input, getNewInputDevice(inputDesc),
2859 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002861 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002862 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002863 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002864 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2865 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002866 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002867 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002868
2869 // automatically disable the remote submix output when input is stopped if not
2870 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002871 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002873 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002874 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002875 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2876 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002877 }
2878 if (address != "") {
2879 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2880 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002881 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002882 }
2883 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 resetInputDevice(input);
2885
2886 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2887 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002888 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2889 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002890 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002891 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002892 }
2893 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002894 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002895 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002896}
2897
Eric Laurent8fc147b2018-07-22 19:13:55 -07002898void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002899{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002900 ALOGV("%s portId %d", __FUNCTION__, portId);
2901
2902 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2903 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002905 return;
2906 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002907 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002908 audio_io_handle_t input = inputDesc->mIoHandle;
2909
Eric Laurent8f42ea12018-08-08 09:08:25 -07002910 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002911
Andy Hung39efb7a2018-09-26 15:39:28 -07002912 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002913
Andy Hung39efb7a2018-09-26 15:39:28 -07002914 if (inputDesc->getClientCount() > 0) {
2915 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002916 return;
2917 }
2918
Eric Laurent05b90f82014-08-27 15:32:29 -07002919 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002920 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002921 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002922}
2923
Eric Laurent8f42ea12018-08-08 09:08:25 -07002924void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002925{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002926 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002927
2928 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002930 }
2931}
2932
Eric Laurent8f42ea12018-08-08 09:08:25 -07002933void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2934{
2935 stopInput(portId);
2936 releaseInput(portId);
2937}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002938
Eric Laurent0dd51852019-04-19 18:18:58 -07002939void AudioPolicyManager::checkCloseInputs() {
2940 // After connecting or disconnecting an input device, close input if:
2941 // - it has no client (was just opened to check profile) OR
2942 // - none of its supported devices are connected anymore OR
2943 // - one of its clients cannot be routed to one of its supported
2944 // devices anymore. Otherwise update device selection
2945 std::vector<audio_io_handle_t> inputsToClose;
2946 for (size_t i = 0; i < mInputs.size(); i++) {
2947 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2948 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002949 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002950 inputsToClose.push_back(mInputs.keyAt(i));
2951 } else {
2952 bool close = false;
2953 for (const auto& client : input->clientsList()) {
2954 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002955 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002956 if (!input->supportedDevices().contains(device)) {
2957 close = true;
2958 break;
2959 }
2960 }
2961 if (close) {
2962 inputsToClose.push_back(mInputs.keyAt(i));
2963 } else {
2964 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2965 }
2966 }
2967 }
2968
2969 for (const audio_io_handle_t handle : inputsToClose) {
2970 ALOGV("%s closing input %d", __func__, handle);
2971 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002972 }
Eric Laurentd4692962014-05-05 18:13:44 -07002973}
2974
François Gaffie251c7f02018-11-07 10:41:08 +01002975void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002976{
2977 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002978 if (indexMin < 0 || indexMax < 0) {
2979 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2980 return;
2981 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002982 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002983
2984 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002985 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2986 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002987 continue;
2988 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002989 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002990 }
Eric Laurente552edb2014-03-10 17:42:56 -07002991}
2992
Eric Laurente0720872014-03-11 09:30:41 -07002993status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002994 int index,
2995 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002996{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002998 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2999 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3000 return NO_ERROR;
3001 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003002 ALOGV("%s: stream %s attributes=%s", __func__,
3003 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003004 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003005}
3006
Eric Laurente0720872014-03-11 09:30:41 -07003007status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003008 int *index,
3009 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003010{
François Gaffiec005e562018-11-06 15:04:49 +01003011 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3012 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003013 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003014 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003015 deviceTypes = mEngine->getOutputDevicesForStream(
3016 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003017 }
jiabin9a3361e2019-10-01 09:38:30 -07003018 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003019}
3020
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003021status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003022 int index,
3023 audio_devices_t device)
3024{
3025 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003026 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3027 if (group == VOLUME_GROUP_NONE) {
3028 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003029 return BAD_VALUE;
3030 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003031 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003032 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003033 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003034 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003035 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3036 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3037 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3038 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003039 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3040
3041 status = setVolumeCurveIndex(index, device, curves);
3042 if (status != NO_ERROR) {
3043 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3044 return status;
3045 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003046
jiabin9a3361e2019-10-01 09:38:30 -07003047 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003048 auto curCurvAttrs = curves.getAttributes();
3049 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3050 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003051 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003052 } else if (!curves.getStreamTypes().empty()) {
3053 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003054 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003055 } else {
3056 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3057 return BAD_VALUE;
3058 }
jiabin9a3361e2019-10-01 09:38:30 -07003059 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3060 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003061
François Gaffiecfe17322018-11-07 13:41:29 +01003062 // update volume on all outputs and streams matching the following:
3063 // - The requested stream (or a stream matching for volume control) is active on the output
3064 // - The device (or devices) selected by the engine for this stream includes
3065 // the requested device
3066 // - For non default requested device, currently selected device on the output is either the
3067 // requested device or one of the devices selected by the engine for this stream
3068 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3069 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003070 for (size_t i = 0; i < mOutputs.size(); i++) {
3071 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003072 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003073
jiabin9a3361e2019-10-01 09:38:30 -07003074 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3075 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003076 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003077
3078 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003079 continue;
3080 }
3081 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3082 curDevices.find(device) == curDevices.end()) {
3083 continue;
3084 }
3085 bool applyVolume = false;
3086 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3087 curSrcDevices.insert(device);
3088 applyVolume = (curSrcDevices.find(
3089 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3090 } else {
3091 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3092 }
3093 if (!applyVolume) {
3094 continue; // next output
3095 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003096 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3097 // If a higher priority strategy is active, and the output is routed to a device with a
3098 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003099 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003100 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003101 // If the volume source is active with higher priority source, ensure at least Sw Muted
3102 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003103 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3104 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3105 false /*preferredDevice*/);
3106 if (activeClients.empty()) {
3107 continue;
3108 }
3109 bool isPreempted = false;
3110 bool isHigherPriority = productStrategy < strategy;
3111 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003112 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003113 ALOGV("%s: Strategy=%d (\nrequester:\n"
3114 " group %d, volumeGroup=%d attributes=%s)\n"
3115 " higher priority source active:\n"
3116 " volumeGroup=%d attributes=%s) \n"
3117 " on output %zu, bailing out", __func__, productStrategy,
3118 group, group, toString(attributes).c_str(),
3119 client->volumeSource(), toString(client->attributes()).c_str(), i);
3120 applyVolume = false;
3121 isPreempted = true;
3122 break;
3123 }
3124 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003125 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003126 applyVolume = true;
3127 }
3128 }
3129 if (isPreempted || applyVolume) {
3130 break;
3131 }
3132 }
3133 if (!applyVolume) {
3134 continue; // next output
3135 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003136 }
François Gaffieed91f582020-01-31 10:35:37 +01003137 //FIXME: workaround for truncated touch sounds
3138 // delayed volume change for system stream to be removed when the problem is
3139 // handled by system UI
3140 status_t volStatus = checkAndSetVolume(
3141 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003142 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003143 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3144 if (volStatus != NO_ERROR) {
3145 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003146 }
3147 }
François Gaffiecfe17322018-11-07 13:41:29 +01003148 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3149 return status;
3150}
3151
François Gaffieaaac0fd2018-11-22 17:56:39 +01003152status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003153 audio_devices_t device,
3154 IVolumeCurves &volumeCurves)
3155{
3156 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3157 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003158 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3159 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003160 (index > volumeCurves.getVolumeIndexMax())) {
3161 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3162 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3163 return BAD_VALUE;
3164 }
3165 if (!audio_is_output_device(device)) {
3166 return BAD_VALUE;
3167 }
3168
3169 // Force max volume if stream cannot be muted
3170 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3171
François Gaffieaaac0fd2018-11-22 17:56:39 +01003172 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003173 volumeCurves.addCurrentVolumeIndex(device, index);
3174 return NO_ERROR;
3175}
3176
3177status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3178 int &index,
3179 audio_devices_t device)
3180{
3181 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3182 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003183 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003184 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003185 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003186 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003187 }
jiabin9a3361e2019-10-01 09:38:30 -07003188 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003189}
3190
3191status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3192 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003193 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003194{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003195 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003196 return BAD_VALUE;
3197 }
jiabin9a3361e2019-10-01 09:38:30 -07003198 index = curves.getVolumeIndex(deviceTypes);
3199 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003200 return NO_ERROR;
3201}
3202
3203status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3204 int &index)
3205{
3206 index = getVolumeCurves(attr).getVolumeIndexMin();
3207 return NO_ERROR;
3208}
3209
3210status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3211 int &index)
3212{
3213 index = getVolumeCurves(attr).getVolumeIndexMax();
3214 return NO_ERROR;
3215}
3216
Eric Laurent36829f92017-04-07 19:04:42 -07003217audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003218{
3219 // select one output among several suitable for global effects.
3220 // The priority is as follows:
3221 // 1: An offloaded output. If the effect ends up not being offloadable,
3222 // AudioFlinger will invalidate the track and the offloaded output
3223 // will be closed causing the effect to be moved to a PCM output.
3224 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003225 // 3: The primary output
3226 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003227
François Gaffiec005e562018-11-06 15:04:49 +01003228 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3229 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003230 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003231
Eric Laurent36829f92017-04-07 19:04:42 -07003232 if (outputs.size() == 0) {
3233 return AUDIO_IO_HANDLE_NONE;
3234 }
Eric Laurente552edb2014-03-10 17:42:56 -07003235
Eric Laurent36829f92017-04-07 19:04:42 -07003236 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3237 bool activeOnly = true;
3238
3239 while (output == AUDIO_IO_HANDLE_NONE) {
3240 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3241 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3242 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3243
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003244 for (audio_io_handle_t output : outputs) {
3245 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003246 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003247 continue;
3248 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003249 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3250 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003251 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003252 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003253 }
3254 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003255 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003256 }
3257 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003258 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003259 }
3260 }
3261 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3262 output = outputOffloaded;
3263 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3264 output = outputDeepBuffer;
3265 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3266 output = outputPrimary;
3267 } else {
3268 output = outputs[0];
3269 }
3270 activeOnly = false;
3271 }
3272
3273 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003274 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003275 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3276 mMusicEffectOutput = output;
3277 }
3278
3279 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003280 return output;
3281}
3282
Eric Laurent36829f92017-04-07 19:04:42 -07003283audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3284{
3285 return selectOutputForMusicEffects();
3286}
3287
Eric Laurente0720872014-03-11 09:30:41 -07003288status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003289 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003290 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003291 int session,
3292 int id)
3293{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003294 if (session != AUDIO_SESSION_DEVICE) {
3295 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003296 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003297 index = mInputs.indexOfKey(io);
3298 if (index < 0) {
3299 ALOGW("registerEffect() unknown io %d", io);
3300 return INVALID_OPERATION;
3301 }
Eric Laurente552edb2014-03-10 17:42:56 -07003302 }
3303 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003304 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3305 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3306 || strategy == PRODUCT_STRATEGY_NONE));
3307 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003308}
3309
Eric Laurentc241b0d2018-11-28 09:08:49 -08003310status_t AudioPolicyManager::unregisterEffect(int id)
3311{
3312 if (mEffects.getEffect(id) == nullptr) {
3313 return INVALID_OPERATION;
3314 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003315 if (mEffects.isEffectEnabled(id)) {
3316 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3317 setEffectEnabled(id, false);
3318 }
3319 return mEffects.unregisterEffect(id);
3320}
3321
3322status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3323{
3324 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3325 if (effect == nullptr) {
3326 return INVALID_OPERATION;
3327 }
3328
3329 status_t status = mEffects.setEffectEnabled(id, enabled);
3330 if (status == NO_ERROR) {
3331 mInputs.trackEffectEnabled(effect, enabled);
3332 }
3333 return status;
3334}
3335
Eric Laurent6c796322019-04-09 14:13:17 -07003336
3337status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3338{
3339 mEffects.moveEffects(ids, io);
3340 return NO_ERROR;
3341}
3342
Eric Laurentc75307b2015-03-17 15:29:32 -07003343bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3344{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003345 auto vs = toVolumeSource(stream, false);
3346 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003347}
3348
3349bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3350{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003351 auto vs = toVolumeSource(stream, false);
3352 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003353}
3354
Eric Laurente0720872014-03-11 09:30:41 -07003355bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003356{
3357 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003358 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003359 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003360 return true;
3361 }
3362 }
3363 return false;
3364}
3365
Eric Laurent275e8e92014-11-30 15:14:47 -08003366// Register a list of custom mixes with their attributes and format.
3367// When a mix is registered, corresponding input and output profiles are
3368// added to the remote submix hw module. The profile contains only the
3369// parameters (sampling rate, format...) specified by the mix.
3370// The corresponding input remote submix device is also connected.
3371//
3372// When a remote submix device is connected, the address is checked to select the
3373// appropriate profile and the corresponding input or output stream is opened.
3374//
3375// When capture starts, getInputForAttr() will:
3376// - 1 look for a mix matching the address passed in attribtutes tags if any
3377// - 2 if none found, getDeviceForInputSource() will:
3378// - 2.1 look for a mix matching the attributes source
3379// - 2.2 if none found, default to device selection by policy rules
3380// At this time, the corresponding output remote submix device is also connected
3381// and active playback use cases can be transferred to this mix if needed when reconnecting
3382// after AudioTracks are invalidated
3383//
3384// When playback starts, getOutputForAttr() will:
3385// - 1 look for a mix matching the address passed in attribtutes tags if any
3386// - 2 if none found, look for a mix matching the attributes usage
3387// - 3 if none found, default to device and output selection by policy rules.
3388
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003389status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003390{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003391 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3392 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003393 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003394 sp<HwModule> rSubmixModule;
3395 // examine each mix's route type
3396 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003397 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003398 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3399 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3400 ALOGE("Unsupported Policy Mix %zu of %zu: "
3401 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3402 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003403 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003404 break;
3405 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003406 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3407 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003408 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003409 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3410 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003411 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003412 rSubmixModule = mHwModules.getModuleFromName(
3413 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3414 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003415 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003416 i);
3417 res = INVALID_OPERATION;
3418 break;
3419 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003420 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003421
Eric Laurent97ac8712018-07-27 18:59:02 -07003422 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003423 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003424 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003425 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003426 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3427 } else {
3428 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3429 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003430 }
François Gaffie036e1e92015-03-19 10:16:24 +01003431
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003432 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003433 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003434 res = INVALID_OPERATION;
3435 break;
3436 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003437 audio_config_t outputConfig = mix.mFormat;
3438 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003439 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3440 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003441 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3442 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003443 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003444 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003445 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003446 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003447
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003448 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003449 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3450 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3451 ALOGE("Failed to set remote submix device available, type %u, address %s",
3452 mix.mDeviceType, address.string());
3453 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003454 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003455 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3456 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003457 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003458 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003459 i, mixes.size(), type, address.string());
3460
3461 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3462 mix.mDeviceType, mix.mDeviceAddress,
3463 String8(), AUDIO_FORMAT_DEFAULT);
3464 if (device == nullptr) {
3465 res = INVALID_OPERATION;
3466 break;
3467 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003468
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003469 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003470 // First try to find an already opened output supporting the device
3471 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003472 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003473
Eric Laurentc529cf62020-04-17 18:19:10 -07003474 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003475 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003476 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3477 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003478 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003479 } else {
3480 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003481 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003482 }
3483 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003484 // If no output found, try to find a direct output profile supporting the device
3485 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3486 sp<HwModule> module = mHwModules[i];
3487 for (size_t j = 0;
3488 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3489 j++) {
3490 sp<IOProfile> profile = module->getOutputProfiles()[j];
3491 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3492 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3493 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3494 address.string());
3495 res = INVALID_OPERATION;
3496 } else {
3497 foundOutput = true;
3498 }
3499 }
3500 }
3501 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003502 if (res != NO_ERROR) {
3503 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003504 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003505 res = INVALID_OPERATION;
3506 break;
3507 } else if (!foundOutput) {
3508 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003509 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003510 res = INVALID_OPERATION;
3511 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003512 } else {
3513 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003514 }
Eric Laurentc722f302014-12-10 11:21:49 -08003515 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003516 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003517 if (res != NO_ERROR) {
3518 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003519 } else if (checkOutputs) {
3520 checkForDeviceAndOutputChanges();
3521 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003522 }
3523 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003524}
3525
3526status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3527{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003528 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003529 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003530 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003531 sp<HwModule> rSubmixModule;
3532 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003533 for (const auto& mix : mixes) {
3534 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003535
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003536 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003537 rSubmixModule = mHwModules.getModuleFromName(
3538 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3539 if (rSubmixModule == 0) {
3540 res = INVALID_OPERATION;
3541 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003542 }
3543 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003544
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003545 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003546
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003547 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003548 res = INVALID_OPERATION;
3549 continue;
3550 }
3551
Kevin Rocard04ed0462019-05-02 17:53:24 -07003552 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3553 if (getDeviceConnectionState(device, address.string()) ==
3554 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3555 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3556 address.string(), "remote-submix",
3557 AUDIO_FORMAT_DEFAULT);
3558 if (res != OK) {
3559 ALOGE("Error making RemoteSubmix device unavailable for mix "
3560 "with type %d, address %s", device, address.string());
3561 }
3562 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003563 }
jiabin5740f082019-08-19 15:08:30 -07003564 rSubmixModule->removeOutputProfile(address.c_str());
3565 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003566
Kevin Rocard153f92d2018-12-18 18:33:28 -08003567 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003568 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003569 res = INVALID_OPERATION;
3570 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003571 } else {
3572 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003573 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003574 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003575 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003576 if (res == NO_ERROR && checkOutputs) {
3577 checkForDeviceAndOutputChanges();
3578 updateCallAndOutputRouting();
3579 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003580 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003581}
3582
Mikhail Naganov100f0122018-11-29 11:22:16 -08003583void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3584{
3585 size_t i = 0;
3586 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3587 for (const auto& fmt : mManualSurroundFormats) {
3588 if (i++ != 0) dst->append(", ");
3589 std::string sfmt;
3590 FormatConverter::toString(fmt, sfmt);
3591 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3592 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3593 }
3594}
3595
Eric Laurentc529cf62020-04-17 18:19:10 -07003596// Returns true if all devices types match the predicate and are supported by one HW module
3597bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003598 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003599 std::function<bool(audio_devices_t)> predicate,
3600 const char *context) {
3601 for (size_t i = 0; i < devices.size(); i++) {
3602 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003603 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003604 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003605 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003606 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003607 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003608 return false;
3609 }
3610 }
3611 return true;
3612}
3613
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003614status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003615 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003616 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003617 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3618 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003619 }
3620 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003621 if (res != NO_ERROR) {
3622 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3623 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003624 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003625
3626 checkForDeviceAndOutputChanges();
3627 updateCallAndOutputRouting();
3628
3629 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003630}
3631
3632status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3633 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003634 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3635 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003636 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003637 __FUNCTION__, uid);
3638 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003639 }
3640
Eric Laurentc529cf62020-04-17 18:19:10 -07003641 checkForDeviceAndOutputChanges();
3642 updateCallAndOutputRouting();
3643
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003644 return res;
3645}
3646
Eric Laurent2517af32020-11-25 15:31:27 +01003647
jiabin0a488932020-08-07 17:32:40 -07003648status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3649 device_role_t role,
3650 const AudioDeviceTypeAddrVector &devices) {
3651 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3652 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003653
Eric Laurentc529cf62020-04-17 18:19:10 -07003654 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003655 return BAD_VALUE;
3656 }
jiabin0a488932020-08-07 17:32:40 -07003657 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003658 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003659 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3660 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003661 return status;
3662 }
3663
3664 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003665
3666 bool forceVolumeReeval = false;
3667 // FIXME: workaround for truncated touch sounds
3668 // to be removed when the problem is handled by system UI
3669 uint32_t delayMs = 0;
3670 if (strategy == mCommunnicationStrategy) {
3671 forceVolumeReeval = true;
3672 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3673 updateInputRouting();
3674 }
3675 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003676
3677 return NO_ERROR;
3678}
3679
3680void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3681{
3682 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003683 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003684 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003685 // Only apply special touch sound delay once
3686 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003687 }
3688 for (size_t i = 0; i < mOutputs.size(); i++) {
3689 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3690 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003691 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3692 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003693 // As done in setDeviceConnectionState, we could also fix default device issue by
3694 // preventing the force re-routing in case of default dev that distinguishes on address.
3695 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003696 bool forceRouting = !newDevices.isEmpty();
3697 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3698 true /*requiresMuteCheck*/,
3699 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003700 // Only apply special touch sound delay once
3701 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003702 }
3703 if (forceVolumeReeval && !newDevices.isEmpty()) {
3704 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3705 }
3706 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003707 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003708}
3709
Eric Laurent2517af32020-11-25 15:31:27 +01003710void AudioPolicyManager::updateInputRouting() {
3711 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303712 // Skip for hotword recording as the input device switch
3713 // is handled within sound trigger HAL
3714 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3715 continue;
3716 }
Eric Laurent2517af32020-11-25 15:31:27 +01003717 auto newDevice = getNewInputDevice(activeDesc);
3718 // Force new input selection if the new device can not be reached via current input
3719 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3720 setInputDevice(activeDesc->mIoHandle, newDevice);
3721 } else {
3722 closeInput(activeDesc->mIoHandle);
3723 }
3724 }
3725}
3726
jiabin0a488932020-08-07 17:32:40 -07003727status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3728 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003729{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003730 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003731
jiabin0a488932020-08-07 17:32:40 -07003732 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003733 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003734 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3735 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003736 return status;
3737 }
3738
3739 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003740
3741 bool forceVolumeReeval = false;
3742 // FIXME: workaround for truncated touch sounds
3743 // to be removed when the problem is handled by system UI
3744 uint32_t delayMs = 0;
3745 if (strategy == mCommunnicationStrategy) {
3746 forceVolumeReeval = true;
3747 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3748 updateInputRouting();
3749 }
3750 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003751
3752 return NO_ERROR;
3753}
3754
jiabin0a488932020-08-07 17:32:40 -07003755status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3756 device_role_t role,
3757 AudioDeviceTypeAddrVector &devices) {
3758 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003759}
3760
Jiabin Huang3b98d322020-09-03 17:54:16 +00003761status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3762 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3763 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3764 dumpAudioDeviceTypeAddrVector(devices).c_str());
3765
Mikhail Naganov55773032020-10-01 15:08:13 -07003766 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003767 return BAD_VALUE;
3768 }
3769 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3770 ALOGW_IF(status != NO_ERROR,
3771 "Engine could not set preferred devices %s for audio source %d role %d",
3772 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3773
3774 return status;
3775}
3776
3777status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3778 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3779 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3780 dumpAudioDeviceTypeAddrVector(devices).c_str());
3781
Mikhail Naganov55773032020-10-01 15:08:13 -07003782 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003783 return BAD_VALUE;
3784 }
3785 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3786 ALOGW_IF(status != NO_ERROR,
3787 "Engine could not add preferred devices %s for audio source %d role %d",
3788 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3789
Eric Laurent2517af32020-11-25 15:31:27 +01003790 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003791 return status;
3792}
3793
3794status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3795 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3796{
3797 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3798 dumpAudioDeviceTypeAddrVector(devices).c_str());
3799
Mikhail Naganov55773032020-10-01 15:08:13 -07003800 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003801 return BAD_VALUE;
3802 }
3803
3804 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3805 audioSource, role, devices);
3806 ALOGW_IF(status != NO_ERROR,
3807 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3808
Eric Laurent2517af32020-11-25 15:31:27 +01003809 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003810 return status;
3811}
3812
3813status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3814 device_role_t role) {
3815 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3816
3817 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3818 ALOGW_IF(status != NO_ERROR,
3819 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3820
Eric Laurent2517af32020-11-25 15:31:27 +01003821 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003822 return status;
3823}
3824
3825status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3826 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3827 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3828}
3829
Oscar Azucena90e77632019-11-27 17:12:28 -08003830status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003831 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003832 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003833 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3834 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003835 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003836 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3837 if (status != NO_ERROR) {
3838 ALOGE("%s() could not set device affinity for userId %d",
3839 __FUNCTION__, userId);
3840 return status;
3841 }
3842
3843 // reevaluate outputs for all devices
3844 checkForDeviceAndOutputChanges();
3845 updateCallAndOutputRouting();
3846
3847 return NO_ERROR;
3848}
3849
3850status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003851 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003852 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3853 if (status != NO_ERROR) {
3854 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3855 __FUNCTION__, userId);
3856 return status;
3857 }
3858
3859 // reevaluate outputs for all devices
3860 checkForDeviceAndOutputChanges();
3861 updateCallAndOutputRouting();
3862
3863 return NO_ERROR;
3864}
3865
Andy Hungc29d82b2018-10-05 12:23:17 -07003866void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003867{
Andy Hungc29d82b2018-10-05 12:23:17 -07003868 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003869 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003870 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003871 std::string stateLiteral;
3872 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003873 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003874 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3875 "communications", "media", "record", "dock", "system",
3876 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3877 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3878 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003879 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3880 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3881 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3882 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3883 dst->append(" (MANUAL: ");
3884 dumpManualSurroundFormats(dst);
3885 dst->append(")");
3886 }
3887 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003888 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003889 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3890 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003891 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003892 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01003893
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003894 dst->append("\n");
3895 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3896 dst->append("\n");
3897 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07003898 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003899 mOutputs.dump(dst);
3900 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003901 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003902 mAudioPatches.dump(dst);
3903 mPolicyMixes.dump(dst);
3904 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003905
Kevin Rocardb99cc752019-03-21 20:52:24 -07003906 dst->appendFormat(" AllowedCapturePolicies:\n");
3907 for (auto& policy : mAllowedCapturePolicies) {
3908 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3909 }
3910
François Gaffiec005e562018-11-06 15:04:49 +01003911 dst->appendFormat("\nPolicy Engine dump:\n");
3912 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003913}
3914
3915status_t AudioPolicyManager::dump(int fd)
3916{
3917 String8 result;
3918 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003919 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003920 return NO_ERROR;
3921}
3922
Kevin Rocardb99cc752019-03-21 20:52:24 -07003923status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3924{
3925 mAllowedCapturePolicies[uid] = capturePolicy;
3926 return NO_ERROR;
3927}
3928
Eric Laurente552edb2014-03-10 17:42:56 -07003929// This function checks for the parameters which can be offloaded.
3930// This can be enhanced depending on the capability of the DSP and policy
3931// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003932audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003933{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003934 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003935 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003936 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003937 offloadInfo.format,
3938 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3939 offloadInfo.has_video);
3940
jiabin2b9d5a12021-12-10 01:06:29 +00003941 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003942 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003943 }
3944
3945 // See if there is a profile to support this.
3946 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003947 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003948 offloadInfo.sample_rate,
3949 offloadInfo.format,
3950 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003951 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3952 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003953 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3954 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3955 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003956 if (profile == nullptr) {
3957 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3958 }
3959 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3960 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3961 }
3962 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003963}
3964
Michael Chana94fbb22018-04-24 14:31:19 +10003965bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3966 const audio_attributes_t& attributes) {
3967 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003968 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003969 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3970 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003971 config.sample_rate,
3972 config.format,
3973 config.channel_mask,
3974 output_flags,
3975 true /* directOnly */);
3976 ALOGV("%s() profile %sfound with name: %s, "
3977 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3978 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003979 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003980 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003981
3982 // also try the MSD module if compatible profile not found
3983 if (profile == nullptr) {
3984 profile = getMsdProfileForOutput(outputDevices,
3985 config.sample_rate,
3986 config.format,
3987 config.channel_mask,
3988 output_flags,
3989 true /* directOnly */);
3990 ALOGV("%s() MSD profile %sfound with name: %s, "
3991 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3992 __FUNCTION__, profile != 0 ? "" : "NOT ",
3993 (profile != 0 ? profile->getTagName().c_str() : "null"),
3994 config.sample_rate, config.format, config.channel_mask, output_flags);
3995 }
3996 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003997}
3998
jiabin2b9d5a12021-12-10 01:06:29 +00003999bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4000 bool durationIgnored) {
4001 if (mMasterMono) {
4002 return false; // no offloading if mono is set.
4003 }
4004
4005 // Check if offload has been disabled
4006 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4007 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4008 return false;
4009 }
4010
4011 // Check if stream type is music, then only allow offload as of now.
4012 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4013 {
4014 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4015 return false;
4016 }
4017
4018 //TODO: enable audio offloading with video when ready
4019 const bool allowOffloadWithVideo =
4020 property_get_bool("audio.offload.video", false /* default_value */);
4021 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4022 ALOGV("%s: has_video == true, returning false", __func__);
4023 return false;
4024 }
4025
4026 //If duration is less than minimum value defined in property, return false
4027 const int min_duration_secs = property_get_int32(
4028 "audio.offload.min.duration.secs", -1 /* default_value */);
4029 if (!durationIgnored) {
4030 if (min_duration_secs >= 0) {
4031 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4032 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4033 __func__, min_duration_secs);
4034 return false;
4035 }
4036 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4037 ALOGV("%s: Offload denied by duration < default min(=%u)",
4038 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4039 return false;
4040 }
4041 }
4042
4043 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4044 // creating an offloaded track and tearing it down immediately after start when audioflinger
4045 // detects there is an active non offloadable effect.
4046 // FIXME: We should check the audio session here but we do not have it in this context.
4047 // This may prevent offloading in rare situations where effects are left active by apps
4048 // in the background.
4049 if (mEffects.isNonOffloadableEffectEnabled()) {
4050 return false;
4051 }
4052
4053 return true;
4054}
4055
4056audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4057 const audio_config_t *config) {
4058 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4059 offloadInfo.format = config->format;
4060 offloadInfo.sample_rate = config->sample_rate;
4061 offloadInfo.channel_mask = config->channel_mask;
4062 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4063 offloadInfo.has_video = false;
4064 offloadInfo.is_streaming = false;
4065 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4066
4067 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4068 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4069 audio_flags_to_audio_output_flags(attr->flags, &flags);
4070 // only retain flags that will drive compressed offload or passthrough
4071 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4072 if (offloadPossible) {
4073 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4074 }
4075 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4076
Dorin Drimusfae3c642022-03-17 18:36:30 +01004077 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004078 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004079 DeviceVector outputDevices = engineOutputDevices;
4080 // the MSD module checks for different conditions and output devices
4081 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4082 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4083 continue;
4084 }
4085 outputDevices = getMsdAudioOutDevices();
4086 }
jiabin2b9d5a12021-12-10 01:06:29 +00004087 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004088 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004089 config->sample_rate, nullptr /*updatedSamplingRate*/,
4090 config->format, nullptr /*updatedFormat*/,
4091 config->channel_mask, nullptr /*updatedChannelMask*/,
4092 flags)) {
4093 continue;
4094 }
4095 // reject profiles not corresponding to a device currently available
4096 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4097 continue;
4098 }
4099 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4100 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004101 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004102 != AUDIO_DIRECT_NOT_SUPPORTED) {
4103 // Already reports offload gapless supported. No need to report offload support.
4104 continue;
4105 }
4106 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4107 != AUDIO_OUTPUT_FLAG_NONE) {
4108 // If offload gapless is reported, no need to report offload support.
4109 directMode = (audio_direct_mode_t) ((directMode &
4110 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4111 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4112 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004113 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004114 }
4115 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004116 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004117 }
4118 }
4119 }
4120 return directMode;
4121}
4122
Dorin Drimusf2196d82022-01-03 12:11:18 +01004123status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4124 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004125 if (mEffects.isNonOffloadableEffectEnabled()) {
4126 return OK;
4127 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004128 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004129 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004130 if (status != OK) {
4131 return status;
4132 }
4133 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4134 if (devices.empty()) {
4135 return OK; // no output devices for the attributes
4136 }
4137
4138 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004139 // the MSD module checks for different conditions
4140 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4141 continue;
4142 }
4143 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4144 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004145 continue;
4146 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004147 // allow only profiles that support all the available and routed devices
4148 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004149 != devices.size()) {
4150 continue;
4151 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004152 audioProfilesVector.addAllValidProfiles(
4153 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004154 }
4155 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004156
4157 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4158 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4159 if (msdModule != nullptr) {
4160 if (msdHasPatchesToAllDevices(devices)) {
4161 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4162 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4163 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4164 continue;
4165 }
4166 audioProfilesVector.addAllValidProfiles(
4167 outputProfile->asAudioPort()->getAudioProfiles());
4168 }
4169 } else {
4170 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4171 }
4172 }
4173
Dorin Drimusf2196d82022-01-03 12:11:18 +01004174 return NO_ERROR;
4175}
4176
Eric Laurent6a94d692014-05-20 11:18:06 -07004177status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4178 audio_port_type_t type,
4179 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004180 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004181 unsigned int *generation)
4182{
jiabin19cdba52020-11-24 11:28:58 -08004183 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4184 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 return BAD_VALUE;
4186 }
4187 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004188 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 *num_ports = 0;
4190 }
4191
4192 size_t portsWritten = 0;
4193 size_t portsMax = *num_ports;
4194 *num_ports = 0;
4195 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004196 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4197 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004198 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004199 for (const auto& dev : mAvailableOutputDevices) {
4200 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004201 continue;
4202 }
4203 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004204 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004205 }
4206 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004208 }
4209 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004210 for (const auto& dev : mAvailableInputDevices) {
4211 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004212 continue;
4213 }
4214 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004215 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004216 }
4217 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 }
4220 }
4221 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4222 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4223 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4224 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4225 }
4226 *num_ports += mInputs.size();
4227 }
4228 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004229 size_t numOutputs = 0;
4230 for (size_t i = 0; i < mOutputs.size(); i++) {
4231 if (!mOutputs[i]->isDuplicated()) {
4232 numOutputs++;
4233 if (portsWritten < portsMax) {
4234 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4235 }
4236 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004237 }
Eric Laurent84c70242014-06-23 08:46:27 -07004238 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004239 }
4240 }
4241 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004242 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004243 return NO_ERROR;
4244}
4245
Mikhail Naganov15f46712023-03-23 14:52:15 -07004246status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4247 std::vector<media::AudioPortFw>* _aidl_return) {
4248 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4249 audio_port_v7 port;
4250 dev->toAudioPort(&port);
4251 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4252 _aidl_return->push_back(std::move(aidlPort));
4253 return OK;
4254 };
4255
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07004256 for (const auto& module : mHwModules) {
Mikhail Naganov15f46712023-03-23 14:52:15 -07004257 for (const auto& dev : module->getDeclaredDevices()) {
4258 if (role == media::AudioPortRole::NONE ||
4259 ((role == media::AudioPortRole::SOURCE)
4260 == audio_is_input_device(dev->type()))) {
4261 RETURN_STATUS_IF_ERROR(pushPort(dev));
4262 }
4263 }
4264 }
4265 return OK;
4266}
4267
jiabin19cdba52020-11-24 11:28:58 -08004268status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004269{
Eric Laurent99fcae42018-05-17 16:59:18 -07004270 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4271 return BAD_VALUE;
4272 }
4273 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4274 if (dev != 0) {
4275 dev->toAudioPort(port);
4276 return NO_ERROR;
4277 }
4278 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4279 if (dev != 0) {
4280 dev->toAudioPort(port);
4281 return NO_ERROR;
4282 }
4283 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4284 if (out != 0) {
4285 out->toAudioPort(port);
4286 return NO_ERROR;
4287 }
4288 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4289 if (in != 0) {
4290 in->toAudioPort(port);
4291 return NO_ERROR;
4292 }
4293 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004294}
4295
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004296status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4297 audio_patch_handle_t *handle,
4298 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004299{
François Gaffieafd4cea2019-11-18 15:50:22 +01004300 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004301 if (handle == NULL || patch == NULL) {
4302 return BAD_VALUE;
4303 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004304 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004305 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004306 return BAD_VALUE;
4307 }
4308 // only one source per audio patch supported for now
4309 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004310 return INVALID_OPERATION;
4311 }
Eric Laurent874c42872014-08-08 15:13:39 -07004312 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004313 return INVALID_OPERATION;
4314 }
Eric Laurent874c42872014-08-08 15:13:39 -07004315 for (size_t i = 0; i < patch->num_sinks; i++) {
4316 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4317 return INVALID_OPERATION;
4318 }
4319 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004320
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004321 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4322 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4323 if (srcDevice == nullptr || sinkDevice == nullptr) {
4324 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4325 return BAD_VALUE;
4326 }
4327 ALOGV("%s between source %s and sink %s", __func__,
4328 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4329 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4330 // Default attributes, default volume priority, not to infer with non raw audio patches.
4331 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4332 const struct audio_port_config *source = &patch->sources[0];
4333 sp<SourceClientDescriptor> sourceDesc =
4334 new InternalSourceClientDescriptor(
4335 portId, uid, attributes, *source, srcDevice, sinkDevice,
4336 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4337
4338 status_t status =
4339 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4340
4341 if (status != NO_ERROR) {
4342 return INVALID_OPERATION;
4343 }
4344 mAudioSources.add(portId, sourceDesc);
4345 return NO_ERROR;
4346}
4347
4348status_t AudioPolicyManager::connectAudioSourceToSink(
4349 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4350 const struct audio_patch *patch,
4351 audio_patch_handle_t &handle,
4352 uid_t uid, uint32_t delayMs)
4353{
4354 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4355 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4356 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4357 return INVALID_OPERATION;
4358 }
4359 sourceDesc->connect(handle, sinkDevice);
4360 if (isMsdPatch(handle)) {
4361 return NO_ERROR;
4362 }
4363 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4364 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4365 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4366 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4367 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4368 goto FailurePatchAdded;
4369 }
4370 status = swOutput->start();
4371 if (status != NO_ERROR) {
4372 goto FailureSourceAdded;
4373 }
4374 swOutput->addClient(sourceDesc);
4375 status = startSource(swOutput, sourceDesc, &delayMs);
4376 if (status != NO_ERROR) {
4377 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4378 goto FailureSourceActive;
4379 }
4380 if (delayMs != 0) {
4381 usleep(delayMs * 1000);
4382 }
4383 return NO_ERROR;
4384
4385FailureSourceActive:
4386 swOutput->stop();
4387 releaseOutput(sourceDesc->portId());
4388FailureSourceAdded:
4389 sourceDesc->setSwOutput(nullptr);
4390FailurePatchAdded:
4391 releaseAudioPatchInternal(handle);
4392 return INVALID_OPERATION;
4393}
4394
4395status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4396 audio_patch_handle_t *handle,
4397 uid_t uid, uint32_t delayMs,
4398 const sp<SourceClientDescriptor>& sourceDesc)
4399{
4400 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 sp<AudioPatch> patchDesc;
4402 ssize_t index = mAudioPatches.indexOfKey(*handle);
4403
François Gaffieafd4cea2019-11-18 15:50:22 +01004404 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4405 patch->sources[0].role,
4406 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004407#if LOG_NDEBUG == 0
4408 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004409 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4410 patch->sinks[i].role,
4411 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004412 }
4413#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004414
4415 if (index >= 0) {
4416 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004417 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4418 __func__, mUidCached, patchDesc->getUid(), uid);
4419 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004420 return INVALID_OPERATION;
4421 }
4422 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004423 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004424 }
4425
4426 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004427 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004428 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004429 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004430 return BAD_VALUE;
4431 }
Eric Laurent84c70242014-06-23 08:46:27 -07004432 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4433 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 if (patchDesc != 0) {
4435 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004436 ALOGV("%s source id differs for patch current id %d new id %d",
4437 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004438 return BAD_VALUE;
4439 }
4440 }
Eric Laurent874c42872014-08-08 15:13:39 -07004441 DeviceVector devices;
4442 for (size_t i = 0; i < patch->num_sinks; i++) {
4443 // Only support mix to devices connection
4444 // TODO add support for mix to mix connection
4445 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004446 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004447 return INVALID_OPERATION;
4448 }
4449 sp<DeviceDescriptor> devDesc =
4450 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4451 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004452 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004453 return BAD_VALUE;
4454 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004455
François Gaffie11d30102018-11-02 16:09:09 +01004456 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004457 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004458 NULL, // updatedSamplingRate
4459 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004460 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004461 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004462 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004463 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004464 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004465 return INVALID_OPERATION;
4466 }
4467 devices.add(devDesc);
4468 }
4469 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 return INVALID_OPERATION;
4471 }
Eric Laurent874c42872014-08-08 15:13:39 -07004472
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004474 ALOGV("%s setting device %s on output %d",
4475 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004476 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 index = mAudioPatches.indexOfKey(*handle);
4478 if (index >= 0) {
4479 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004480 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004481 }
4482 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004483 patchDesc->setUid(uid);
4484 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004485 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 return INVALID_OPERATION;
4488 }
4489 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4490 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4491 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004492 // only one sink supported when connecting an input device to a mix
4493 if (patch->num_sinks > 1) {
4494 return INVALID_OPERATION;
4495 }
François Gaffie53615e22015-03-19 09:24:12 +01004496 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004497 if (inputDesc == NULL) {
4498 return BAD_VALUE;
4499 }
4500 if (patchDesc != 0) {
4501 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4502 return BAD_VALUE;
4503 }
4504 }
François Gaffie11d30102018-11-02 16:09:09 +01004505 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004507 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004508 return BAD_VALUE;
4509 }
4510
François Gaffie11d30102018-11-02 16:09:09 +01004511 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004512 patch->sinks[0].sample_rate,
4513 NULL, /*updatedSampleRate*/
4514 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004515 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004516 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004517 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004518 // FIXME for the parameter type,
4519 // and the NONE
4520 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004521 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004522 return INVALID_OPERATION;
4523 }
4524 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004525 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004526 device->toString().c_str(), inputDesc->mIoHandle);
4527 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 index = mAudioPatches.indexOfKey(*handle);
4529 if (index >= 0) {
4530 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004531 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004532 }
4533 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004534 patchDesc->setUid(uid);
4535 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004536 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004537 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004538 return INVALID_OPERATION;
4539 }
4540 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4541 // device to device connection
4542 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004543 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 return BAD_VALUE;
4545 }
4546 }
François Gaffie11d30102018-11-02 16:09:09 +01004547 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004548 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004549 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004550 return BAD_VALUE;
4551 }
Eric Laurent874c42872014-08-08 15:13:39 -07004552
Eric Laurent6a94d692014-05-20 11:18:06 -07004553 //update source and sink with our own data as the data passed in the patch may
4554 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004555 PatchBuilder patchBuilder;
4556 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004557
4558 // if first sink is to MSD, establish single MSD patch
4559 if (getMsdAudioOutDevices().contains(
4560 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4561 ALOGV("%s patching to MSD", __FUNCTION__);
4562 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4563 goto installPatch;
4564 }
4565
François Gaffieafd4cea2019-11-18 15:50:22 +01004566 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4567 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004568
Eric Laurent874c42872014-08-08 15:13:39 -07004569 for (size_t i = 0; i < patch->num_sinks; i++) {
4570 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004571 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004572 return INVALID_OPERATION;
4573 }
François Gaffie11d30102018-11-02 16:09:09 +01004574 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004575 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004576 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004577 return BAD_VALUE;
4578 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004579 audio_port_config sinkPortConfig = {};
4580 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4581 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004582
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004583 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4584 // volume management purpose (tracking activity)
4585 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4586 // in config XML to reach the sink so that is can be declared as available.
4587 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004588 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004589 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004590 // take care of dynamic routing for SwOutput selection,
4591 audio_attributes_t attributes = sourceDesc->attributes();
4592 audio_stream_type_t stream = sourceDesc->stream();
4593 audio_attributes_t resultAttr;
4594 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4595 config.sample_rate = sourceDesc->config().sample_rate;
4596 config.channel_mask = sourceDesc->config().channel_mask;
4597 config.format = sourceDesc->config().format;
4598 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4599 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4600 bool isRequestedDeviceForExclusiveUse = false;
4601 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004602 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004603 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4604 &stream, sourceDesc->uid(), &config, &flags,
4605 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004606 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004607 if (output == AUDIO_IO_HANDLE_NONE) {
4608 ALOGV("%s no output for device %s",
4609 __FUNCTION__, sinkDevice->toString().c_str());
4610 return INVALID_OPERATION;
4611 }
4612 outputDesc = mOutputs.valueFor(output);
4613 if (outputDesc->isDuplicated()) {
4614 ALOGE("%s output is duplicated", __func__);
4615 return INVALID_OPERATION;
4616 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004617 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4618 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004619 } else {
4620 // Same for "raw patches" aka created from createAudioPatch API
4621 SortedVector<audio_io_handle_t> outputs =
4622 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4623 // if the sink device is reachable via an opened output stream, request to
4624 // go via this output stream by adding a second source to the patch
4625 // description
4626 output = selectOutput(outputs);
4627 if (output == AUDIO_IO_HANDLE_NONE) {
4628 ALOGE("%s no output available for internal patch sink", __func__);
4629 return INVALID_OPERATION;
4630 }
4631 outputDesc = mOutputs.valueFor(output);
4632 if (outputDesc->isDuplicated()) {
4633 ALOGV("%s output for device %s is duplicated",
4634 __func__, sinkDevice->toString().c_str());
4635 return INVALID_OPERATION;
4636 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004637 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004638 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004639 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004640 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004641 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004642 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004643 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4644 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004645 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4646 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004647 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004648 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004649 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004650 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004651 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004652 return INVALID_OPERATION;
4653 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004654 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004655 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004656 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004657 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004658 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004659 srcMixPortConfig.ext.mix.usecase.stream =
4660 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004661 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4662 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004663 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004664 }
Eric Laurent83b88082014-06-20 18:31:16 -07004665 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 }
4667 // TODO: check from routing capabilities in config file and other conflicting patches
4668
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004669installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 status_t status = installPatch(
4671 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004672 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004673 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 return INVALID_OPERATION;
4675 }
4676 } else {
4677 return BAD_VALUE;
4678 }
4679 } else {
4680 return BAD_VALUE;
4681 }
4682 return NO_ERROR;
4683}
4684
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004685status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004686{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004687 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 ssize_t index = mAudioPatches.indexOfKey(handle);
4689
4690 if (index < 0) {
4691 return BAD_VALUE;
4692 }
4693 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004694 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4695 __func__, mUidCached, patchDesc->getUid(), uid);
4696 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004697 return INVALID_OPERATION;
4698 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004699 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4700 for (size_t i = 0; i < mAudioSources.size(); i++) {
4701 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4702 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4703 portId = sourceDesc->portId();
4704 break;
4705 }
4706 }
4707 return portId != AUDIO_PORT_HANDLE_NONE ?
4708 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004709}
Eric Laurent6a94d692014-05-20 11:18:06 -07004710
François Gaffieafd4cea2019-11-18 15:50:22 +01004711status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004712 uint32_t delayMs,
4713 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004714{
4715 ALOGV("%s patch %d", __func__, handle);
4716 if (mAudioPatches.indexOfKey(handle) < 0) {
4717 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4718 return BAD_VALUE;
4719 }
4720 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004721 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004722 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004724 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004726 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004727 return BAD_VALUE;
4728 }
4729
François Gaffie11d30102018-11-02 16:09:09 +01004730 setOutputDevices(outputDesc,
4731 getNewOutputDevices(outputDesc, true /*fromCache*/),
4732 true,
4733 0,
4734 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4736 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004737 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004739 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 return BAD_VALUE;
4741 }
4742 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004743 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 true,
4745 NULL);
4746 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004747 status_t status =
4748 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4749 ALOGV("%s patch panel returned %d patchHandle %d",
4750 __func__, status, patchDesc->getAfHandle());
4751 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004753 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004754 // SW or HW Bridge
4755 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4756 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004757 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004758 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4759 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4760 outputDesc = sourceDesc->swOutput().promote();
4761 }
4762 if (outputDesc == nullptr) {
4763 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4764 // releaseOutput has already called closeOutput in case of direct output
4765 return NO_ERROR;
4766 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004767 patchHandle = outputDesc->getPatchHandle();
4768 // When a Sw bridge is released, the mixer used by this bridge will release its
4769 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4770 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4771 // updating hal patch handle (prevent leaks).
4772 // While using a HwBridge, force reconsidering device only if not reusing an existing
4773 // output and no more activity on output (will force to close).
4774 bool force = sourceDesc->useSwBridge() ||
4775 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4776 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4777 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4778 // Reconsider device only for cases:
4779 // 1 / Active Output
4780 // 2 / Inactive Output previously hosting HwBridge
4781 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4782 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4783 sourceDesc->canCloseOutput();
4784 setOutputDevices(outputDesc,
4785 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4786 outputDesc->devices(),
4787 force,
4788 0,
4789 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 } else {
4791 return BAD_VALUE;
4792 }
4793 } else {
4794 return BAD_VALUE;
4795 }
4796 return NO_ERROR;
4797}
4798
4799status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4800 struct audio_patch *patches,
4801 unsigned int *generation)
4802{
François Gaffie53615e22015-03-19 09:24:12 +01004803 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004804 return BAD_VALUE;
4805 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004806 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004807 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004808}
4809
Eric Laurente1715a42014-05-20 11:30:42 -07004810status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004811{
Eric Laurente1715a42014-05-20 11:30:42 -07004812 ALOGV("setAudioPortConfig()");
4813
4814 if (config == NULL) {
4815 return BAD_VALUE;
4816 }
4817 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4818 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004819 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4820 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004821 }
4822
Eric Laurenta121f902014-06-03 13:32:54 -07004823 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004824 if (config->type == AUDIO_PORT_TYPE_MIX) {
4825 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004826 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004827 if (outputDesc == NULL) {
4828 return BAD_VALUE;
4829 }
Eric Laurent84c70242014-06-23 08:46:27 -07004830 ALOG_ASSERT(!outputDesc->isDuplicated(),
4831 "setAudioPortConfig() called on duplicated output %d",
4832 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004833 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004834 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004835 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004836 if (inputDesc == NULL) {
4837 return BAD_VALUE;
4838 }
Eric Laurenta121f902014-06-03 13:32:54 -07004839 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004840 } else {
4841 return BAD_VALUE;
4842 }
4843 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4844 sp<DeviceDescriptor> deviceDesc;
4845 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4846 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4847 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4848 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4849 } else {
4850 return BAD_VALUE;
4851 }
4852 if (deviceDesc == NULL) {
4853 return BAD_VALUE;
4854 }
Eric Laurenta121f902014-06-03 13:32:54 -07004855 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004856 } else {
4857 return BAD_VALUE;
4858 }
4859
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004860 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004861 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4862 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004863 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004864 audioPortConfig->toAudioPortConfig(&newConfig, config);
4865 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004866 }
Eric Laurenta121f902014-06-03 13:32:54 -07004867 if (status != NO_ERROR) {
4868 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004869 }
Eric Laurente1715a42014-05-20 11:30:42 -07004870
4871 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004872}
4873
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004874void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4875{
Eric Laurentd60560a2015-04-10 11:31:20 -07004876 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004877 clearAudioPatches(uid);
4878 clearSessionRoutes(uid);
4879}
4880
Eric Laurent6a94d692014-05-20 11:18:06 -07004881void AudioPolicyManager::clearAudioPatches(uid_t uid)
4882{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004883 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004885 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004886 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004887 }
4888 }
4889}
4890
François Gaffiec005e562018-11-06 15:04:49 +01004891void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004892{
François Gaffiec005e562018-11-06 15:04:49 +01004893 // Take the first attributes following the product strategy as it is used to retrieve the routed
4894 // device. All attributes wihin a strategy follows the same "routing strategy"
4895 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4896 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004897 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004898 for (size_t j = 0; j < mOutputs.size(); j++) {
4899 if (mOutputs.keyAt(j) == ouptutToSkip) {
4900 continue;
4901 }
4902 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004903 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004904 continue;
4905 }
4906 // If the default device for this strategy is on another output mix,
4907 // invalidate all tracks in this strategy to force re connection.
4908 // Otherwise select new device on the output mix.
4909 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004910 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4911 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004912 }
4913 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004914 setOutputDevices(
4915 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004916 }
4917 }
4918}
4919
4920void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4921{
4922 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004923 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004924 for (size_t i = 0; i < mOutputs.size(); i++) {
4925 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004926 for (const auto& client : outputDesc->getClientIterable()) {
4927 if (client->hasPreferredDevice() && client->uid() == uid) {
4928 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004929 auto clientStrategy = client->strategy();
4930 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4931 end(affectedStrategies)) {
4932 continue;
4933 }
4934 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004935 }
4936 }
4937 }
4938 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004939 for (const auto& strategy : affectedStrategies) {
4940 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004941 }
4942
4943 // remove input routes associated with this uid
4944 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004945 for (size_t i = 0; i < mInputs.size(); i++) {
4946 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004947 for (const auto& client : inputDesc->getClientIterable()) {
4948 if (client->hasPreferredDevice() && client->uid() == uid) {
4949 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4950 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004951 }
4952 }
4953 }
4954 // reroute inputs if necessary
4955 SortedVector<audio_io_handle_t> inputsToClose;
4956 for (size_t i = 0; i < mInputs.size(); i++) {
4957 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004958 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004959 inputsToClose.add(inputDesc->mIoHandle);
4960 }
4961 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004962 for (const auto& input : inputsToClose) {
4963 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004964 }
4965}
4966
Eric Laurentd60560a2015-04-10 11:31:20 -07004967void AudioPolicyManager::clearAudioSources(uid_t uid)
4968{
4969 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004970 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4971 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004972 stopAudioSource(mAudioSources.keyAt(i));
4973 }
4974 }
4975}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004976
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004977status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4978 audio_io_handle_t *ioHandle,
4979 audio_devices_t *device)
4980{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004981 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4982 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004983 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004984 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004985
François Gaffiedf372692015-03-19 10:43:27 +01004986 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004987}
4988
Eric Laurentd60560a2015-04-10 11:31:20 -07004989status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004990 const audio_attributes_t *attributes,
4991 audio_port_handle_t *portId,
4992 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004993{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004994 ALOGV("%s", __FUNCTION__);
4995 *portId = AUDIO_PORT_HANDLE_NONE;
4996
4997 if (source == NULL || attributes == NULL || portId == NULL) {
4998 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4999 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005000 return BAD_VALUE;
5001 }
5002
Eric Laurentd60560a2015-04-10 11:31:20 -07005003 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5004 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005005 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5006 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005007 return INVALID_OPERATION;
5008 }
5009
François Gaffie11d30102018-11-02 16:09:09 +01005010 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005011 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005012 String8(source->ext.device.address),
5013 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005014 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005015 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005016 return BAD_VALUE;
5017 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005018
jiabin4ef93452019-09-10 14:29:54 -07005019 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005020
François Gaffieaaac0fd2018-11-22 17:56:39 +01005021 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005023 mEngine->getStreamTypeForAttributes(*attributes),
5024 mEngine->getProductStrategyForAttributes(*attributes),
5025 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005026
5027 status_t status = connectAudioSource(sourceDesc);
5028 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005029 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005030 }
5031 return status;
5032}
5033
Francois Gaffie601801d2021-06-22 13:27:39 +02005034sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5035 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5036{
5037 ALOGV("%s", __FUNCTION__);
5038 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5039
5040 status_t status = startAudioSource(source, attributes, &portId, uid);
5041 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5042 return mAudioSources.valueFor(portId);
5043}
5044
5045
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005046status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005047{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005048 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005049
5050 // make sure we only have one patch per source.
5051 disconnectAudioSource(sourceDesc);
5052
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005053 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005054 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5055 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5056 sourceDesc->srcDevice()->type(),
5057 String8(sourceDesc->srcDevice()->address().c_str()),
5058 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005059 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005060 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005061 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005062 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005063 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5064 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5065 return INVALID_OPERATION;
5066 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 PatchBuilder patchBuilder;
5068 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5069 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005070
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005071 return connectAudioSourceToSink(
5072 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005073}
5074
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005075status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005076{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005077 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5078 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005079 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005080 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005081 return BAD_VALUE;
5082 }
5083 status_t status = disconnectAudioSource(sourceDesc);
5084
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005085 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005086 return status;
5087}
5088
Andy Hung2ddee192015-12-18 17:34:44 -08005089status_t AudioPolicyManager::setMasterMono(bool mono)
5090{
5091 if (mMasterMono == mono) {
5092 return NO_ERROR;
5093 }
5094 mMasterMono = mono;
5095 // if enabling mono we close all offloaded devices, which will invalidate the
5096 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5097 // for recreating the new AudioTrack as non-offloaded PCM.
5098 //
5099 // If disabling mono, we leave all tracks as is: we don't know which clients
5100 // and tracks are able to be recreated as offloaded. The next "song" should
5101 // play back offloaded.
5102 if (mMasterMono) {
5103 Vector<audio_io_handle_t> offloaded;
5104 for (size_t i = 0; i < mOutputs.size(); ++i) {
5105 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5106 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5107 offloaded.push(desc->mIoHandle);
5108 }
5109 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005110 for (const auto& handle : offloaded) {
5111 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005112 }
5113 }
5114 // update master mono for all remaining outputs
5115 for (size_t i = 0; i < mOutputs.size(); ++i) {
5116 updateMono(mOutputs.keyAt(i));
5117 }
5118 return NO_ERROR;
5119}
5120
5121status_t AudioPolicyManager::getMasterMono(bool *mono)
5122{
5123 *mono = mMasterMono;
5124 return NO_ERROR;
5125}
5126
Eric Laurentac9cef52017-06-09 15:46:26 -07005127float AudioPolicyManager::getStreamVolumeDB(
5128 audio_stream_type_t stream, int index, audio_devices_t device)
5129{
jiabin9a3361e2019-10-01 09:38:30 -07005130 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005131}
5132
jiabin81772902018-04-02 17:52:27 -07005133status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5134 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005135 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005136{
Kriti Dang6537def2021-03-02 13:46:59 +01005137 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5138 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005139 return BAD_VALUE;
5140 }
Kriti Dang6537def2021-03-02 13:46:59 +01005141 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5142 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005143
5144 size_t formatsWritten = 0;
5145 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005146
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005147 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005148 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5149 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005150 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005151 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005152 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005153 bool formatEnabled = true;
5154 switch (forceUse) {
5155 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005156 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005157 break;
5158 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5159 formatEnabled = false;
5160 break;
5161 default: // AUTO or ALWAYS => true
5162 break;
jiabin81772902018-04-02 17:52:27 -07005163 }
5164 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5165 }
jiabin81772902018-04-02 17:52:27 -07005166 }
5167 return NO_ERROR;
5168}
5169
Kriti Dang6537def2021-03-02 13:46:59 +01005170status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5171 audio_format_t *surroundFormats) {
5172 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5173 return BAD_VALUE;
5174 }
5175 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5176 __func__, *numSurroundFormats, surroundFormats);
5177
5178 size_t formatsWritten = 0;
5179 size_t formatsMax = *numSurroundFormats;
5180 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5181
5182 // Return formats from all device profiles that have already been resolved by
5183 // checkOutputsForDevice().
5184 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5185 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5186 audio_devices_t deviceType = device->type();
5187 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5188 // returns formats reported by HDMI devices.
5189 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5190 continue;
5191 }
5192 // Formats reported by sink devices
5193 std::unordered_set<audio_format_t> formatset;
5194 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5195 formatset.insert(it->second.begin(), it->second.end());
5196 }
5197
5198 // Formats hard-coded in the in policy configuration file (if any).
5199 FormatVector encodedFormats = device->encodedFormats();
5200 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5201 // Filter the formats which are supported by the vendor hardware.
5202 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005203 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005204 formats.insert(*it);
5205 } else {
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005206 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005207 if (pair.second.count(*it) != 0) {
5208 formats.insert(pair.first);
5209 break;
5210 }
5211 }
5212 }
5213 }
5214 }
5215 *numSurroundFormats = formats.size();
5216 for (const auto& format: formats) {
5217 if (formatsWritten < formatsMax) {
5218 surroundFormats[formatsWritten++] = format;
5219 }
5220 }
5221 return NO_ERROR;
5222}
5223
jiabin81772902018-04-02 17:52:27 -07005224status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5225{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005226 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005227 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5228 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005229 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005230 return BAD_VALUE;
5231 }
5232
Mikhail Naganov100f0122018-11-29 11:22:16 -08005233 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5234 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005235 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005236 return INVALID_OPERATION;
5237 }
5238
Mikhail Naganov100f0122018-11-29 11:22:16 -08005239 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005240 return NO_ERROR;
5241 }
5242
Mikhail Naganov100f0122018-11-29 11:22:16 -08005243 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005244 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005245 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005246 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005247 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005248 }
5249 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005250 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005251 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005252 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005253 }
5254 }
5255
5256 sp<SwAudioOutputDescriptor> outputDesc;
5257 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005258 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5259 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005260 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5261 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005262 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005263 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005264 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5265 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5266 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005267 name.c_str(),
5268 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005269 if (status != NO_ERROR) {
5270 continue;
5271 }
5272 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5273 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5274 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005275 name.c_str(),
5276 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005277 profileUpdated |= (status == NO_ERROR);
5278 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005279 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005280 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005281 AUDIO_DEVICE_IN_HDMI);
5282 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5283 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005284 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005285 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005286 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5287 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5288 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005289 name.c_str(),
5290 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005291 if (status != NO_ERROR) {
5292 continue;
5293 }
5294 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5295 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5296 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005297 name.c_str(),
5298 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005299 profileUpdated |= (status == NO_ERROR);
5300 }
5301
jiabin81772902018-04-02 17:52:27 -07005302 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005303 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005304 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005305 }
5306
5307 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5308}
5309
Eric Laurent5ada82e2019-08-29 17:53:54 -07005310void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005311{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005312 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005313 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005314 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005315 }
5316}
5317
jiabin6012f912018-11-02 17:06:30 -07005318bool AudioPolicyManager::isHapticPlaybackSupported()
5319{
5320 for (const auto& hwModule : mHwModules) {
5321 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5322 for (const auto &outProfile : outputProfiles) {
5323 struct audio_port audioPort;
5324 outProfile->toAudioPort(&audioPort);
5325 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5326 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5327 return true;
5328 }
5329 }
5330 }
5331 }
5332 return false;
5333}
5334
Carter Hsu325a8eb2022-01-19 19:56:51 +08005335bool AudioPolicyManager::isUltrasoundSupported()
5336{
5337 bool hasUltrasoundOutput = false;
5338 bool hasUltrasoundInput = false;
5339 for (const auto& hwModule : mHwModules) {
5340 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5341 if (!hasUltrasoundOutput) {
5342 for (const auto &outProfile : outputProfiles) {
5343 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5344 hasUltrasoundOutput = true;
5345 break;
5346 }
5347 }
5348 }
5349
5350 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5351 if (!hasUltrasoundInput) {
5352 for (const auto &inputProfile : inputProfiles) {
5353 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5354 hasUltrasoundInput = true;
5355 break;
5356 }
5357 }
5358 }
5359
5360 if (hasUltrasoundOutput && hasUltrasoundInput)
5361 return true;
5362 }
5363 return false;
5364}
5365
Eric Laurent8340e672019-11-06 11:01:08 -08005366bool AudioPolicyManager::isCallScreenModeSupported()
5367{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005368 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005369}
5370
5371
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005372status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005373{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005374 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005375 if (!sourceDesc->isConnected()) {
5376 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5377 return NO_ERROR;
5378 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5380 if (swOutput != 0) {
5381 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005382 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005383 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005384 }
jiabinbce0c1d2020-10-05 11:20:18 -07005385 if (releaseOutput(sourceDesc->portId())) {
5386 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5387 // no need to release audio patch here but just return NO_ERROR.
5388 return NO_ERROR;
5389 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005390 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005391 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005392 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005393 // close Hwoutput and remove from mHwOutputs
5394 } else {
5395 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5396 }
5397 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005398 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005399 sourceDesc->disconnect();
5400 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005401}
5402
François Gaffiec005e562018-11-06 15:04:49 +01005403sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5404 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005405{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005406 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005407 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005408 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005409 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005410 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5411 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005412 source = sourceDesc;
5413 break;
5414 }
5415 }
5416 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005417}
5418
Eric Laurentb4f42a92022-01-17 17:37:31 +01005419bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005420 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005421 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005422{
5423 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5424 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005425 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005426 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005427 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5428 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5429 return false;
5430 }
5431 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5432 return false;
5433 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005434 }
5435
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005436 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005437 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005438 if (profile == nullptr) {
5439 return false;
5440 }
5441
5442 // The caller can have the audio config criteria ignored by either passing a null ptr or
5443 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005444 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005445 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005446
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005447 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005448 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005449 return false;
5450 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005451 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005452 return true;
5453}
5454
5455void AudioPolicyManager::checkVirtualizerClientRoutes() {
5456 std::set<audio_stream_type_t> streamsToInvalidate;
5457 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005458 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5459 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005460 audio_attributes_t attr = client->attributes();
5461 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5462 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5463 audio_config_base_t clientConfig = client->config();
5464 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005465 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005466 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005467 streamsToInvalidate.insert(client->stream());
5468 }
5469 }
5470 }
5471
5472 for (audio_stream_type_t stream : streamsToInvalidate) {
5473 mpClientInterface->invalidateStream(stream);
5474 }
5475}
5476
Eric Laurente191d1b2022-04-15 11:59:25 +02005477
5478bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5479 const sp<SwAudioOutputDescriptor>& outputDesc) {
5480 if (outputDesc->isDuplicated()) {
5481 return false;
5482 }
5483 DeviceVector devices = outputDesc->supportedDevices();
5484 for (size_t i = 0; i < mOutputs.size(); i++) {
5485 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5486 if (desc == outputDesc || desc->isDuplicated()) {
5487 continue;
5488 }
5489 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5490 if (!sharedDevices.isEmpty()
5491 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5492 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5493 return false;
5494 }
5495 }
5496 return true;
5497}
5498
5499
Eric Laurentfa0f6742021-08-17 18:39:44 +02005500status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005501 const audio_attributes_t *attr,
5502 audio_io_handle_t *output) {
5503 *output = AUDIO_IO_HANDLE_NONE;
5504
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005505 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5506 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5507 audio_config_t *configPtr = nullptr;
5508 audio_config_t config;
5509 if (mixerConfig != nullptr) {
5510 config = audio_config_initializer(mixerConfig);
5511 configPtr = &config;
5512 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005513 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005514 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005515 return BAD_VALUE;
5516 }
5517
5518 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005519 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005520 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005521 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005522 return BAD_VALUE;
5523 }
5524
Eric Laurente191d1b2022-04-15 11:59:25 +02005525 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005526 for (size_t i = 0; i < mOutputs.size(); i++) {
5527 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005528 if (!desc->isDuplicated()
5529 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5530 spatializerOutputs.push_back(desc);
5531 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005532 }
5533 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005534 mSpatializerOutput.clear();
5535 bool outputsChanged = false;
5536 for (const auto& desc : spatializerOutputs) {
5537 if (desc->mProfile == profile
5538 && (configPtr == nullptr
5539 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5540 mSpatializerOutput = desc;
5541 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5542 } else {
5543 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5544 " and devices %s", __func__, desc->mIoHandle,
5545 configPtr != nullptr ? configPtr->channel_mask : 0,
5546 devices.toString().c_str());
5547 closeOutput(desc->mIoHandle);
5548 outputsChanged = true;
5549 }
Eric Laurent39095982021-08-24 18:29:27 +02005550 }
5551
Eric Laurente191d1b2022-04-15 11:59:25 +02005552 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005553 sp<SwAudioOutputDescriptor> desc =
5554 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005555 if (desc != nullptr) {
5556 mSpatializerOutput = desc;
5557 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005558 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005559 }
5560
5561 checkVirtualizerClientRoutes();
5562
Eric Laurente191d1b2022-04-15 11:59:25 +02005563 if (outputsChanged) {
5564 mPreviousOutputs = mOutputs;
5565 mpClientInterface->onAudioPortListUpdate();
5566 }
5567
5568 if (mSpatializerOutput == nullptr) {
5569 ALOGV("%s could not open spatializer output with requested config", __func__);
5570 return BAD_VALUE;
5571 }
Eric Laurent39095982021-08-24 18:29:27 +02005572 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005573 ALOGV("%s returning new spatializer output %d", __func__, *output);
5574 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005575}
5576
Eric Laurentfa0f6742021-08-17 18:39:44 +02005577status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5578 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005579 return INVALID_OPERATION;
5580 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005581 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005582 return BAD_VALUE;
5583 }
Eric Laurent39095982021-08-24 18:29:27 +02005584
Eric Laurente191d1b2022-04-15 11:59:25 +02005585 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5586 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5587 closeOutput(mSpatializerOutput->mIoHandle);
5588 //from now on mSpatializerOutput is null
5589 checkVirtualizerClientRoutes();
5590 }
Eric Laurent39095982021-08-24 18:29:27 +02005591
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005592 return NO_ERROR;
5593}
5594
Eric Laurente552edb2014-03-10 17:42:56 -07005595// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005596// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005597// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005598uint32_t AudioPolicyManager::nextAudioPortGeneration()
5599{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005600 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005601}
5602
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005603AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovabb04782023-05-02 13:56:01 -07005604 EngineInstance&& engine,
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005605 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07005606 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005607 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005608 mConfig(config),
Mikhail Naganovabb04782023-05-02 13:56:01 -07005609 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005610 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005611 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005612 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005613 mAudioPortGeneration(1),
5614 mBeaconMuteRefCount(0),
5615 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005616 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005617 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005618 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005619 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005620{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005621}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005622
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005623status_t AudioPolicyManager::initialize() {
Mikhail Naganovabb04782023-05-02 13:56:01 -07005624 if (mEngine == nullptr) {
5625 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01005626 }
5627 mEngine->setObserver(this);
5628 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005629 if (status != NO_ERROR) {
5630 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5631 return status;
5632 }
François Gaffie2110e042015-03-24 08:41:51 +01005633
jiabin76e829d2023-04-04 21:02:36 +00005634 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
5635 // at the end of this function.
5636 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005637 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5638 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5639
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005640 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005641 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005642 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005643
Eric Laurent3a4311c2014-03-17 12:00:47 -07005644 // make sure default device is reachable
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005645 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
5646 defaultOutputDevice == nullptr ||
5647 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
5648 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
5649 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005650 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005651 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005652 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005653
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005654 // Silence ALOGV statements
5655 property_set("log.tag." LOG_TAG, "D");
5656
Eric Laurente552edb2014-03-10 17:42:56 -07005657 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005658 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005659}
5660
Eric Laurente0720872014-03-11 09:30:41 -07005661AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005662{
Eric Laurente552edb2014-03-10 17:42:56 -07005663 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005664 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005665 }
5666 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005667 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005668 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005669 mAvailableOutputDevices.clear();
5670 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005671 mOutputs.clear();
5672 mInputs.clear();
5673 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005674 mManualSurroundFormats.clear();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005675 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005676}
5677
Eric Laurente0720872014-03-11 09:30:41 -07005678status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005679{
Eric Laurent87ffa392015-05-22 10:32:38 -07005680 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005681}
5682
Eric Laurente552edb2014-03-10 17:42:56 -07005683// ---
5684
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005685void AudioPolicyManager::onNewAudioModulesAvailable()
5686{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005687 DeviceVector newDevices;
5688 onNewAudioModulesAvailableInt(&newDevices);
5689 if (!newDevices.empty()) {
5690 nextAudioPortGeneration();
5691 mpClientInterface->onAudioPortListUpdate();
5692 }
5693}
5694
5695void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5696{
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005697 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005698 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5699 continue;
5700 }
5701 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5702 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5703 ALOGW("could not open HW module %s", hwModule->getName());
5704 continue;
5705 }
5706 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005707 // open all output streams needed to access attached devices.
5708 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005709 // This also validates mAvailableOutputDevices list
5710 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5711 if (!outProfile->canOpenNewIo()) {
5712 ALOGE("Invalid Output profile max open count %u for profile %s",
5713 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5714 continue;
5715 }
5716 if (!outProfile->hasSupportedDevices()) {
5717 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5718 continue;
5719 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005720 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5721 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005722 mTtsOutputAvailable = true;
5723 }
5724
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005725 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005726 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005727 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005728 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
5729 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005730 } else {
5731 // choose first device present in profile's SupportedDevices also part of
5732 // mAvailableOutputDevices.
5733 if (availProfileDevices.isEmpty()) {
5734 continue;
5735 }
5736 supportedDevice = availProfileDevices.itemAt(0);
5737 }
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005738 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005739 continue;
5740 }
5741 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5742 mpClientInterface);
5743 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005744 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5745 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005746 AUDIO_STREAM_DEFAULT,
5747 AUDIO_OUTPUT_FLAG_NONE, &output);
5748 if (status != NO_ERROR) {
5749 ALOGW("Cannot open output stream for devices %s on hw module %s",
5750 supportedDevice->toString().c_str(), hwModule->getName());
5751 continue;
5752 }
5753 for (const auto &device : availProfileDevices) {
5754 // give a valid ID to an attached device once confirmed it is reachable
5755 if (!device->isAttached()) {
5756 device->attach(hwModule);
5757 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005758 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005759 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005760 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5761 }
5762 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005763 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005764 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5765 mPrimaryOutput = outputDesc;
5766 }
Eric Laurent39095982021-08-24 18:29:27 +02005767 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005768 outputDesc->close();
5769 } else {
5770 addOutput(output, outputDesc);
5771 setOutputDevices(outputDesc,
5772 DeviceVector(supportedDevice),
5773 true,
5774 0,
5775 NULL);
5776 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005777 }
5778 // open input streams needed to access attached devices to validate
5779 // mAvailableInputDevices list
5780 for (const auto& inProfile : hwModule->getInputProfiles()) {
5781 if (!inProfile->canOpenNewIo()) {
5782 ALOGE("Invalid Input profile max open count %u for profile %s",
5783 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5784 continue;
5785 }
5786 if (!inProfile->hasSupportedDevices()) {
5787 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5788 continue;
5789 }
5790 // chose first device present in profile's SupportedDevices also part of
5791 // available input devices
5792 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07005793 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005794 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005795 ALOGV("%s: Input device list is empty! for profile %s",
5796 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005797 continue;
5798 }
5799 sp<AudioInputDescriptor> inputDesc =
5800 new AudioInputDescriptor(inProfile, mpClientInterface);
5801
5802 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5803 status_t status = inputDesc->open(nullptr,
5804 availProfileDevices.itemAt(0),
5805 AUDIO_SOURCE_MIC,
5806 AUDIO_INPUT_FLAG_NONE,
5807 &input);
5808 if (status != NO_ERROR) {
5809 ALOGW("Cannot open input stream for device %s on hw module %s",
5810 availProfileDevices.toString().c_str(),
5811 hwModule->getName());
5812 continue;
5813 }
5814 for (const auto &device : availProfileDevices) {
5815 // give a valid ID to an attached device once confirmed it is reachable
5816 if (!device->isAttached()) {
5817 device->attach(hwModule);
5818 device->importAudioPortAndPickAudioProfile(inProfile, true);
5819 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005820 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005821 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5822 }
5823 }
5824 inputDesc->close();
5825 }
5826 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005827
5828 // Check if spatializer outputs can be closed until used.
5829 // mOutputs vector never contains duplicated outputs at this point.
5830 std::vector<audio_io_handle_t> outputsClosed;
5831 for (size_t i = 0; i < mOutputs.size(); i++) {
5832 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5833 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5834 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5835 outputsClosed.push_back(desc->mIoHandle);
5836 desc->close();
5837 }
5838 }
5839 for (auto output : outputsClosed) {
5840 removeOutput(output);
5841 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005842}
5843
Eric Laurent98e38192018-02-15 18:31:53 -08005844void AudioPolicyManager::addOutput(audio_io_handle_t output,
5845 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005846{
Eric Laurent1c333e22014-05-20 10:48:17 -07005847 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005848 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005849 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005850 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005851 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005852}
5853
François Gaffie53615e22015-03-19 09:24:12 +01005854void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5855{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005856 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5857 ALOGV("%s: removing primary output", __func__);
5858 mPrimaryOutput = nullptr;
5859 }
François Gaffie53615e22015-03-19 09:24:12 +01005860 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005861 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005862}
5863
Eric Laurent98e38192018-02-15 18:31:53 -08005864void AudioPolicyManager::addInput(audio_io_handle_t input,
5865 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005866{
Eric Laurent1c333e22014-05-20 10:48:17 -07005867 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005868 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005869}
Eric Laurente552edb2014-03-10 17:42:56 -07005870
François Gaffie11d30102018-11-02 16:09:09 +01005871status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005872 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005873 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005874{
François Gaffie11d30102018-11-02 16:09:09 +01005875 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005876 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005877 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005878
François Gaffie11d30102018-11-02 16:09:09 +01005879 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005880 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005881 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005882 }
Eric Laurente552edb2014-03-10 17:42:56 -07005883
Eric Laurent3b73df72014-03-11 09:06:29 -07005884 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005885 // first call getAudioPort to get the supported attributes from the HAL
5886 struct audio_port_v7 port = {};
5887 device->toAudioPort(&port);
5888 status_t status = mpClientInterface->getAudioPort(&port);
5889 if (status == NO_ERROR) {
5890 device->importAudioPort(port);
5891 }
5892
5893 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005894 for (size_t i = 0; i < mOutputs.size(); i++) {
5895 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005896 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005897 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005898 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5899 mOutputs.keyAt(i), device->toString().c_str());
5900 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005901 }
5902 }
5903 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005904 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005905 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005906 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5907 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005908 if (profile->supportsDevice(device)) {
5909 profiles.add(profile);
5910 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5911 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005912 }
5913 }
5914 }
5915
Eric Laurent7b279bb2015-12-14 10:18:23 -08005916 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005917
Eric Laurente552edb2014-03-10 17:42:56 -07005918 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005919 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005920 return BAD_VALUE;
5921 }
5922
5923 // open outputs for matching profiles if needed. Direct outputs are also opened to
5924 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5925 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005926 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005927
5928 // nothing to do if one output is already opened for this profile
5929 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005930 for (j = 0; j < outputs.size(); j++) {
5931 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005932 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005933 // matching profile: save the sample rates, format and channel masks supported
5934 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005935 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005936 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005937 }
Eric Laurente552edb2014-03-10 17:42:56 -07005938 break;
5939 }
5940 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005941 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005942 continue;
5943 }
5944
Eric Laurent3974e3b2017-12-07 17:58:43 -08005945 if (!profile->canOpenNewIo()) {
5946 ALOGW("Max Output number %u already opened for this profile %s",
5947 profile->maxOpenCount, profile->getTagName().c_str());
5948 continue;
5949 }
5950
Eric Laurent83efe1c2017-07-09 16:51:08 -07005951 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005952 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005953 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5954 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005955 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005956 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005957 profiles.removeAt(profile_index);
5958 profile_index--;
5959 } else {
5960 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005961 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005962 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005963 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5964 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005965 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005966 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005967
François Gaffie11d30102018-11-02 16:09:09 +01005968 if (device_distinguishes_on_address(deviceType)) {
5969 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5970 device->toString().c_str());
5971 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5972 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005973 }
Eric Laurente552edb2014-03-10 17:42:56 -07005974 ALOGV("checkOutputsForDevice(): adding output %d", output);
5975 }
5976 }
5977
5978 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005979 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005980 return BAD_VALUE;
5981 }
Eric Laurentd4692962014-05-05 18:13:44 -07005982 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005983 // check if one opened output is not needed any more after disconnecting one device
5984 for (size_t i = 0; i < mOutputs.size(); i++) {
5985 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005986 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005987 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005988 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005989 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005990 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005991 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005992 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5993 mOutputs.keyAt(i));
5994 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005995 }
Eric Laurente552edb2014-03-10 17:42:56 -07005996 }
5997 }
Eric Laurentd4692962014-05-05 18:13:44 -07005998 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005999 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006000 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6001 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006002 if (!profile->supportsDevice(device)) {
6003 continue;
6004 }
6005 ALOGV("checkOutputsForDevice(): "
6006 "clearing direct output profile %zu on module %s",
6007 j, hwModule->getName());
6008 profile->clearAudioProfiles();
6009 if (!profile->hasDynamicAudioProfile()) {
6010 continue;
6011 }
6012 // When a device is disconnected, if there is an IOProfile that contains dynamic
6013 // profiles and supports the disconnected device, call getAudioPort to repopulate
6014 // the capabilities of the devices that is supported by the IOProfile.
6015 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6016 if (supportedDevice == device ||
6017 !mAvailableOutputDevices.contains(supportedDevice)) {
6018 continue;
6019 }
6020 struct audio_port_v7 port;
6021 supportedDevice->toAudioPort(&port);
6022 status_t status = mpClientInterface->getAudioPort(&port);
6023 if (status == NO_ERROR) {
6024 supportedDevice->importAudioPort(port);
6025 }
Eric Laurente552edb2014-03-10 17:42:56 -07006026 }
6027 }
6028 }
6029 }
6030 return NO_ERROR;
6031}
6032
François Gaffie11d30102018-11-02 16:09:09 +01006033status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006034 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006035{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006036 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006037
François Gaffie11d30102018-11-02 16:09:09 +01006038 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006039 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006040 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006041 }
6042
Eric Laurentd4692962014-05-05 18:13:44 -07006043 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006044 // first call getAudioPort to get the supported attributes from the HAL
6045 struct audio_port_v7 port = {};
6046 device->toAudioPort(&port);
6047 status_t status = mpClientInterface->getAudioPort(&port);
6048 if (status == NO_ERROR) {
6049 device->importAudioPort(port);
6050 }
6051
Eric Laurent0dd51852019-04-19 18:18:58 -07006052 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006053 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006054 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006055 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006056 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006057 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006058 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006059
François Gaffie11d30102018-11-02 16:09:09 +01006060 if (profile->supportsDevice(device)) {
6061 profiles.add(profile);
6062 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6063 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006064 }
6065 }
6066 }
6067
Eric Laurent0dd51852019-04-19 18:18:58 -07006068 if (profiles.isEmpty()) {
6069 ALOGW("%s: No input profile available for device %s",
6070 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006071 return BAD_VALUE;
6072 }
6073
6074 // open inputs for matching profiles if needed. Direct inputs are also opened to
6075 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6076 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6077
Eric Laurent1c333e22014-05-20 10:48:17 -07006078 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006079
Eric Laurentd4692962014-05-05 18:13:44 -07006080 // nothing to do if one input is already opened for this profile
6081 size_t input_index;
6082 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6083 desc = mInputs.valueAt(input_index);
6084 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006085 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006086 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006087 }
Eric Laurentd4692962014-05-05 18:13:44 -07006088 break;
6089 }
6090 }
6091 if (input_index != mInputs.size()) {
6092 continue;
6093 }
6094
Eric Laurent3974e3b2017-12-07 17:58:43 -08006095 if (!profile->canOpenNewIo()) {
6096 ALOGW("Max Input number %u already opened for this profile %s",
6097 profile->maxOpenCount, profile->getTagName().c_str());
6098 continue;
6099 }
6100
Eric Laurentfe231122017-11-17 17:48:06 -08006101 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006102 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006103 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006104
Eric Laurentcf2c0212014-07-25 16:20:43 -07006105 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006106 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006107 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006108 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006109 mpClientInterface->setParameters(input, String8(param));
6110 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006111 }
François Gaffie11d30102018-11-02 16:09:09 +01006112 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006113 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006114 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006115 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006116 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006117 }
6118
Eric Laurent0dd51852019-04-19 18:18:58 -07006119 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006120 addInput(input, desc);
6121 }
6122 } // endif input != 0
6123
Eric Laurentcf2c0212014-07-25 16:20:43 -07006124 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006125 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006126 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006127 profiles.removeAt(profile_index);
6128 profile_index--;
6129 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006130 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006131 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006132 }
Eric Laurentd4692962014-05-05 18:13:44 -07006133 ALOGV("checkInputsForDevice(): adding input %d", input);
6134 }
6135 } // end scan profiles
6136
6137 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006138 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006139 return BAD_VALUE;
6140 }
6141 } else {
6142 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006143 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006144 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006145 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006146 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006147 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006148 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006149 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006150 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6151 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006152 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006153 }
6154 }
6155 }
6156 } // end disconnect
6157
6158 return NO_ERROR;
6159}
6160
6161
Eric Laurente0720872014-03-11 09:30:41 -07006162void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006163{
6164 ALOGV("closeOutput(%d)", output);
6165
François Gaffie1c878552018-11-22 16:53:21 +01006166 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6167 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006168 ALOGW("closeOutput() unknown output %d", output);
6169 return;
6170 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006171 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006172 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006173
Eric Laurente552edb2014-03-10 17:42:56 -07006174 // look for duplicated outputs connected to the output being removed.
6175 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006176 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6177 if (dupOutput->isDuplicated() &&
6178 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6179 sp<SwAudioOutputDescriptor> remainingOutput =
6180 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006181 // As all active tracks on duplicated output will be deleted,
6182 // and as they were also referenced on the other output, the reference
6183 // count for their stream type must be adjusted accordingly on
6184 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006185 const bool wasActive = remainingOutput->isActive();
6186 // Note: no-op on the closing output where all clients has already been set inactive
6187 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006188 // stop() will be a no op if the output is still active but is needed in case all
6189 // active streams refcounts where cleared above
6190 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006191 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006192 }
Eric Laurente552edb2014-03-10 17:42:56 -07006193 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6194 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6195
6196 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006197 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006198 }
6199 }
6200
Eric Laurent05b90f82014-08-27 15:32:29 -07006201 nextAudioPortGeneration();
6202
François Gaffie1c878552018-11-22 16:53:21 +01006203 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006204 if (index >= 0) {
6205 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006206 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6207 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006208 mAudioPatches.removeItemsAt(index);
6209 mpClientInterface->onAudioPatchListUpdate();
6210 }
6211
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006212 if (closingOutputWasActive) {
6213 closingOutput->stop();
6214 }
François Gaffie1c878552018-11-22 16:53:21 +01006215 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006216
François Gaffie53615e22015-03-19 09:24:12 +01006217 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006218 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006219 if (closingOutput == mSpatializerOutput) {
6220 mSpatializerOutput.clear();
6221 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006222
6223 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6224 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006225 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006226 bool directOutputOpen = false;
6227 for (size_t i = 0; i < mOutputs.size(); i++) {
6228 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6229 directOutputOpen = true;
6230 break;
6231 }
6232 }
6233 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006234 ALOGV("no direct outputs open, reset MSD patches");
6235 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6236 // how output devices for patching are resolved. Avoid by caching and reusing the
6237 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6238 // devices to patch to. This may be complicated by the fact that devices may become
6239 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006240 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006241 }
6242 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006243}
6244
6245void AudioPolicyManager::closeInput(audio_io_handle_t input)
6246{
6247 ALOGV("closeInput(%d)", input);
6248
6249 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6250 if (inputDesc == NULL) {
6251 ALOGW("closeInput() unknown input %d", input);
6252 return;
6253 }
6254
Eric Laurent6a94d692014-05-20 11:18:06 -07006255 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006256
François Gaffie11d30102018-11-02 16:09:09 +01006257 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006258 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006259 if (index >= 0) {
6260 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006261 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6262 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006263 mAudioPatches.removeItemsAt(index);
6264 mpClientInterface->onAudioPatchListUpdate();
6265 }
6266
Eric Laurentfe231122017-11-17 17:48:06 -08006267 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006268 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006269
François Gaffie11d30102018-11-02 16:09:09 +01006270 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6271 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006272 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006273 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006274 }
Eric Laurente552edb2014-03-10 17:42:56 -07006275}
6276
François Gaffie11d30102018-11-02 16:09:09 +01006277SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6278 const DeviceVector &devices,
6279 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006280{
6281 SortedVector<audio_io_handle_t> outputs;
6282
François Gaffie11d30102018-11-02 16:09:09 +01006283 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006284 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006285 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006286 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006287 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006288 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006289 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006290 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006291 outputs.add(openOutputs.keyAt(i));
6292 }
6293 }
6294 return outputs;
6295}
6296
Mikhail Naganov37977152018-07-11 15:54:44 -07006297void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6298{
6299 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6300 // output is suspended before any tracks are moved to it
6301 checkA2dpSuspend();
6302 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006303 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006304 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006305 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006306 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006307 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6308 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6309 // configuration changes will ultimately be rerouted correctly. We can still avoid
6310 // unnecessary rerouting by caching and reusing the arguments to
6311 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6312 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006313 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006314 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006315 // an event that changed routing likely occurred, inform upper layers
6316 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006317}
6318
François Gaffiec005e562018-11-06 15:04:49 +01006319bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6320 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006321{
François Gaffiec005e562018-11-06 15:04:49 +01006322 return mEngine->getProductStrategyForAttributes(lAttr) ==
6323 mEngine->getProductStrategyForAttributes(rAttr);
6324}
6325
Francois Gaffieff1eb522020-05-06 18:37:04 +02006326void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6327{
6328 for (size_t i = 0; i < mAudioSources.size(); i++) {
6329 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6330 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006331 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006332 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006333 connectAudioSource(sourceDesc);
6334 }
6335 }
6336}
6337
6338void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6339{
6340 for (size_t i = 0; i < mAudioSources.size(); i++) {
6341 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6342 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6343 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6344 disconnectAudioSource(sourceDesc);
6345 }
6346 }
6347}
6348
François Gaffiec005e562018-11-06 15:04:49 +01006349void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6350{
6351 auto psId = mEngine->getProductStrategyForAttributes(attr);
6352
6353 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6354 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006355
François Gaffie11d30102018-11-02 16:09:09 +01006356 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6357 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006358
Eric Laurentc209fe42020-06-05 18:11:23 -07006359 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006360 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006361 // take into account dynamic audio policies related changes: if a client is now associated
6362 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006363 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006364 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6365 if (desc->isDuplicated()) {
6366 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006367 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006368 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6369 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6370 continue;
6371 }
6372 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006373 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6374 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006375 if (status != OK) {
6376 continue;
6377 }
yucliuf4de36d2020-09-14 14:57:56 -07006378 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006379 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006380 maxLatency = desc->latency();
6381 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006382 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006383 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006384 }
6385 }
6386
Eric Laurent56ed8842022-11-15 16:04:41 +01006387 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006388 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6389 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006390 for (audio_io_handle_t srcOut : srcOutputs) {
6391 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006392 if (desc == nullptr) continue;
6393
6394 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006395 maxLatency = desc->latency();
6396 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006397
Eric Laurent56ed8842022-11-15 16:04:41 +01006398 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006399 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006400 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006401 // a client on a non direct outputs has necessarily a linear PCM format
6402 // so we can call selectOutput() safely
6403 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6404 client->flags(),
6405 client->config().format,
6406 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006407 client->config().sample_rate,
6408 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006409 if (newOutput != srcOut) {
6410 invalidate = true;
6411 break;
6412 }
6413 } else {
6414 sp<IOProfile> profile = getProfileForOutput(newDevices,
6415 client->config().sample_rate,
6416 client->config().format,
6417 client->config().channel_mask,
6418 client->flags(),
6419 true /* directOnly */);
6420 if (profile != desc->mProfile) {
6421 invalidate = true;
6422 break;
6423 }
6424 }
6425 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006426 // mute strategy while moving tracks from one output to another
6427 if (invalidate) {
6428 invalidatedOutputs.push_back(desc);
6429 if (desc->isStrategyActive(psId)) {
6430 setStrategyMute(psId, true, desc);
6431 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6432 newDevices.types());
6433 }
Eric Laurente552edb2014-03-10 17:42:56 -07006434 }
François Gaffiec005e562018-11-06 15:04:49 +01006435 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006436 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006437 connectAudioSource(source);
6438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439 }
6440
Eric Laurent56ed8842022-11-15 16:04:41 +01006441 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6442 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6443 std::to_string(srcOutputs[0]).c_str(),
6444 std::to_string(dstOutputs[0]).c_str());
6445
François Gaffiec005e562018-11-06 15:04:49 +01006446 // Move effects associated to this stream from previous output to new output
6447 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006448 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006449 }
François Gaffiec005e562018-11-06 15:04:49 +01006450 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006451 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006452 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6453 mpClientInterface->invalidateStream(stream);
6454 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006455 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006456 desc->setTracksInvalidatedStatusByStrategy(psId);
6457 }
Eric Laurente552edb2014-03-10 17:42:56 -07006458 }
6459 }
6460}
6461
Eric Laurente0720872014-03-11 09:30:41 -07006462void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006463{
François Gaffiec005e562018-11-06 15:04:49 +01006464 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6465 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6466 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006467 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006468 }
Eric Laurente552edb2014-03-10 17:42:56 -07006469}
6470
Kevin Rocard153f92d2018-12-18 18:33:28 -08006471void AudioPolicyManager::checkSecondaryOutputs() {
6472 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006473 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006474 for (size_t i = 0; i < mOutputs.size(); i++) {
6475 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6476 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006477 sp<AudioPolicyMix> primaryMix;
6478 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006479 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6480 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006481 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6482 for (auto &secondaryMix : secondaryMixes) {
6483 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6484 if (outputDesc != nullptr &&
6485 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6486 secondaryDescs.push_back(outputDesc);
6487 }
6488 }
6489
jiabin10a03f12021-05-07 23:46:28 +00006490 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006491 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006492 } else if (!std::equal(
6493 client->getSecondaryOutputs().begin(),
6494 client->getSecondaryOutputs().end(),
6495 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006496 if (!audio_is_linear_pcm(client->config().format)) {
6497 // If the format is not PCM, the tracks should be invalidated to get correct
6498 // behavior when the secondary output is changed.
6499 streamsToInvalidate.insert(client->stream());
6500 } else {
6501 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6502 std::vector<audio_io_handle_t> secondaryOutputIds;
6503 for (const auto &secondaryDesc: secondaryDescs) {
6504 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6505 weakSecondaryDescs.push_back(secondaryDesc);
6506 }
6507 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6508 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006509 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006510 }
6511 }
6512 }
jiabin10a03f12021-05-07 23:46:28 +00006513 if (!trackSecondaryOutputs.empty()) {
6514 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6515 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006516 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006517 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006518 mpClientInterface->invalidateStream(stream);
6519 }
6520}
6521
Eric Laurent2517af32020-11-25 15:31:27 +01006522bool AudioPolicyManager::isScoRequestedForComm() const {
6523 AudioDeviceTypeAddrVector devices;
6524 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6525 for (const auto &device : devices) {
6526 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6527 return true;
6528 }
6529 }
6530 return false;
6531}
6532
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006533bool AudioPolicyManager::isHearingAidUsedForComm() const {
6534 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6535 true /*fromCache*/);
6536 for (const auto &device : devices) {
6537 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6538 return true;
6539 }
6540 }
6541 return false;
6542}
6543
6544
Eric Laurente0720872014-03-11 09:30:41 -07006545void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006546{
François Gaffie53615e22015-03-19 09:24:12 +01006547 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006548 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006549 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006550 return;
6551 }
6552
Eric Laurent3a4311c2014-03-17 12:00:47 -07006553 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006554 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6555 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006556 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006557
6558 // if suspended, restore A2DP output if:
6559 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006560 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006561 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006562 //
Eric Laurentf732e072016-08-03 19:30:28 -07006563 // if not suspended, suspend A2DP output if:
6564 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006565 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006566 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006567 //
6568 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006569 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006570 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006571 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006572 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006573
6574 mpClientInterface->restoreOutput(a2dpOutput);
6575 mA2dpSuspended = false;
6576 }
6577 } else {
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->suspendOutput(a2dpOutput);
6584 mA2dpSuspended = true;
6585 }
6586 }
6587}
6588
François Gaffie11d30102018-11-02 16:09:09 +01006589DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6590 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006591{
François Gaffie11d30102018-11-02 16:09:09 +01006592 DeviceVector devices;
6593
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006594 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006595 if (index >= 0) {
6596 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006597 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006598 ALOGV("%s device %s forced by patch %d", __func__,
6599 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6600 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006601 }
6602 }
6603
Dean Wheatley514b4312020-06-17 21:45:00 +10006604 // Do not retrieve engine device for outputs through MSD
6605 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6606 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6607 return outputDesc->devices();
6608 }
6609
Eric Laurent97ac8712018-07-27 18:59:02 -07006610 // Honor explicit routing requests only if no client using default routing is active on this
6611 // input: a specific app can not force routing for other apps by setting a preferred device.
6612 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006613 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006614 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006615 if (device != nullptr) {
6616 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006617 }
6618
François Gaffiea807ef92018-11-05 10:44:33 +01006619 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6620 // of setForceUse / Default Bus device here
6621 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6622 if (device != nullptr) {
6623 return DeviceVector(device);
6624 }
6625
François Gaffiec005e562018-11-06 15:04:49 +01006626 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6627 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6628 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306629 auto hasStreamActive = [&](auto stream) {
6630 return hasStream(streams, stream) && isStreamActive(stream, 0);
6631 };
Eric Laurent484e9272018-06-07 17:29:23 -07006632
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306633 auto doGetOutputDevicesForVoice = [&]() {
6634 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006635 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306636 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006637 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6638 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306639 };
6640
6641 // With low-latency playing on speaker, music on WFD, when the first low-latency
6642 // output is stopped, getNewOutputDevices checks for a product strategy
6643 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006644 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306645 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6646 // stream is associated to the output descriptor.
6647 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6648 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6649 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6650 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006651 // Retrieval of devices for voice DL is done on primary output profile, cannot
6652 // check the route (would force modifying configuration file for this profile)
6653 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6654 break;
6655 }
Eric Laurente552edb2014-03-10 17:42:56 -07006656 }
François Gaffiec005e562018-11-06 15:04:49 +01006657 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006658 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006659}
6660
François Gaffie11d30102018-11-02 16:09:09 +01006661sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6662 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006663{
François Gaffie11d30102018-11-02 16:09:09 +01006664 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006665
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006666 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006667 if (index >= 0) {
6668 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006669 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006670 ALOGV("getNewInputDevice() device %s forced by patch %d",
6671 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6672 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006673 }
6674 }
6675
Eric Laurent97ac8712018-07-27 18:59:02 -07006676 // Honor explicit routing requests only if no client using default routing is active on this
6677 // input: a specific app can not force routing for other apps by setting a preferred device.
6678 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006679 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6680 if (device != nullptr) {
6681 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006682 }
6683
Eric Laurentdc95a252018-04-12 12:46:56 -07006684 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006685 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006686 audio_attributes_t attributes;
6687 uid_t uid;
6688 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6689 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006690 attributes = topClient->attributes();
6691 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006692 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006693 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6694 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006695 }
6696
Francois Gaffie716e1432019-01-14 16:58:59 +01006697 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6698 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006699 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006700 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006701 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006702 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006703
Eric Laurente552edb2014-03-10 17:42:56 -07006704 return device;
6705}
6706
Eric Laurent794fde22016-03-11 09:50:45 -08006707bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6708 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006709 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006710}
6711
Dorin Drimusf2196d82022-01-03 12:11:18 +01006712// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006713status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006714 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006715 if (devices == nullptr) {
6716 return BAD_VALUE;
6717 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006718
6719 // Devices are determined in the following precedence:
6720 //
6721 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6722 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6723 //
6724 // If no such dynamic policy then
6725 // 2) Devices containing an active client using setPreferredDevice
6726 // with same strategy as the attributes.
6727 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6728 //
6729 // If no corresponding active client with setPreferredDevice then
6730 // 3) Devices associated with the strategy determined by the attributes
6731 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6732 //
6733 // See related getOutputForAttrInt().
6734
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006735 // check dynamic policies but only for primary descriptors (secondary not used for audible
6736 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006737 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006738 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6739 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006740 if (status != OK) {
6741 return status;
6742 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006743
6744 DeviceVector curDevices;
6745 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6746 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6747 // as they are unaffected by device/stream volume
6748 // (per SwAudioOutputDescriptor::isFixedVolume()).
6749 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6750 ) {
6751 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6752 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6753 curDevices.add(deviceDesc);
6754 } else {
6755 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6756 // which selects setPreferredDevice if active. This means forVolume call
6757 // will take an active setPreferredDevice, if such exists.
6758
6759 curDevices = mEngine->getOutputDevicesForAttributes(
6760 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006761 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006762
6763 if (forVolume) {
6764 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6765 // for single volume control in AudioService (such relationship should exist if
6766 // SPEAKER_SAFE is present).
6767 //
6768 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6769 DeviceVector speakerSafeDevices =
6770 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6771 if (!speakerSafeDevices.isEmpty()) {
6772 curDevices.merge(
6773 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6774 curDevices.remove(speakerSafeDevices);
6775 }
6776 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006777 for (const auto& device : curDevices) {
6778 devices->push_back(device->getDeviceTypeAddr());
6779 }
6780 return NO_ERROR;
6781}
6782
Eric Laurente0720872014-03-11 09:30:41 -07006783void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006784 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006785 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006786 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006787 updateDevicesAndOutputs();
6788 break;
6789 default:
6790 break;
6791 }
6792}
6793
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006794uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006795
6796 // skip beacon mute management if a dedicated TTS output is available
6797 if (mTtsOutputAvailable) {
6798 return 0;
6799 }
6800
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006801 switch(event) {
6802 case STARTING_OUTPUT:
6803 mBeaconMuteRefCount++;
6804 break;
6805 case STOPPING_OUTPUT:
6806 if (mBeaconMuteRefCount > 0) {
6807 mBeaconMuteRefCount--;
6808 }
6809 break;
6810 case STARTING_BEACON:
6811 mBeaconPlayingRefCount++;
6812 break;
6813 case STOPPING_BEACON:
6814 if (mBeaconPlayingRefCount > 0) {
6815 mBeaconPlayingRefCount--;
6816 }
6817 break;
6818 }
6819
6820 if (mBeaconMuteRefCount > 0) {
6821 // any playback causes beacon to be muted
6822 return setBeaconMute(true);
6823 } else {
6824 // no other playback: unmute when beacon starts playing, mute when it stops
6825 return setBeaconMute(mBeaconPlayingRefCount == 0);
6826 }
6827}
6828
6829uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6830 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6831 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6832 // keep track of muted state to avoid repeating mute/unmute operations
6833 if (mBeaconMuted != mute) {
6834 // mute/unmute AUDIO_STREAM_TTS on all outputs
6835 ALOGV("\t muting %d", mute);
6836 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006837 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6838 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6839 ALOGV("\t no tts volume source available");
6840 return 0;
6841 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006842 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006843 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006844 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006845 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006846 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006847 maxLatency = latency;
6848 }
6849 }
6850 mBeaconMuted = mute;
6851 return maxLatency;
6852 }
6853 return 0;
6854}
6855
Eric Laurente0720872014-03-11 09:30:41 -07006856void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006857{
François Gaffiec005e562018-11-06 15:04:49 +01006858 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006859 mPreviousOutputs = mOutputs;
6860}
6861
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006862uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006863 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006864 uint32_t delayMs)
6865{
6866 // mute/unmute strategies using an incompatible device combination
6867 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6868 // if unmuting, unmute only after the specified delay
6869 if (outputDesc->isDuplicated()) {
6870 return 0;
6871 }
6872
6873 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006874 DeviceVector devices = outputDesc->devices();
6875 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006876
François Gaffiec005e562018-11-06 15:04:49 +01006877 auto productStrategies = mEngine->getOrderedProductStrategies();
6878 for (const auto &productStrategy : productStrategies) {
6879 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6880 DeviceVector curDevices =
6881 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6882 curDevices = curDevices.filter(outputDesc->supportedDevices());
6883 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006884 bool doMute = false;
6885
François Gaffiec005e562018-11-06 15:04:49 +01006886 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006887 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006888 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6889 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006890 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006891 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006892 }
Eric Laurent99401132014-05-07 19:48:15 -07006893 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006894 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006895 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006896 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006897 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006898 continue;
6899 }
François Gaffiec005e562018-11-06 15:04:49 +01006900 ALOGVV("%s() %s (curDevice %s)", __func__,
6901 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6902 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6903 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006904 if (mute) {
6905 // FIXME: should not need to double latency if volume could be applied
6906 // immediately by the audioflinger mixer. We must account for the delay
6907 // between now and the next time the audioflinger thread for this output
6908 // will process a buffer (which corresponds to one buffer size,
6909 // usually 1/2 or 1/4 of the latency).
6910 if (muteWaitMs < desc->latency() * 2) {
6911 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006912 }
6913 }
6914 }
6915 }
6916 }
6917 }
6918
Eric Laurent99401132014-05-07 19:48:15 -07006919 // temporary mute output if device selection changes to avoid volume bursts due to
6920 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006921 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006922 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006923
Eric Laurentdc462862016-07-19 12:29:53 -07006924 if (muteWaitMs < tempMuteWaitMs) {
6925 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006926 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006927
6928 // If recommended duration is defined, replace temporary mute duration to avoid
6929 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6930 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6931 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6932 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6933 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6934
François Gaffieaaac0fd2018-11-22 17:56:39 +01006935 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6936 // make sure that we do not start the temporary mute period too early in case of
6937 // delayed device change
6938 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6939 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006940 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006941 }
6942 }
6943
Eric Laurente552edb2014-03-10 17:42:56 -07006944 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6945 if (muteWaitMs > delayMs) {
6946 muteWaitMs -= delayMs;
6947 usleep(muteWaitMs * 1000);
6948 return muteWaitMs;
6949 }
6950 return 0;
6951}
6952
François Gaffie11d30102018-11-02 16:09:09 +01006953uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6954 const DeviceVector &devices,
6955 bool force,
6956 int delayMs,
6957 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006958 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006959{
François Gaffie11d30102018-11-02 16:09:09 +01006960 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006961 uint32_t muteWaitMs;
6962
6963 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006964 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6965 nullptr /* patchHandle */, requiresMuteCheck);
6966 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6967 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006968 return muteWaitMs;
6969 }
Eric Laurente552edb2014-03-10 17:42:56 -07006970
6971 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006972 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006973 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006974 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006975
François Gaffie11d30102018-11-02 16:09:09 +01006976 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6977
6978 if (!filteredDevices.isEmpty()) {
6979 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006980 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006981
6982 // if the outputs are not materially active, there is no need to mute.
6983 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006984 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006985 } else {
6986 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6987 muteWaitMs = 0;
6988 }
Eric Laurente552edb2014-03-10 17:42:56 -07006989
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006990 bool outputRouted = outputDesc->isRouted();
6991
Eric Laurent79ea9582020-06-11 18:49:24 -07006992 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6993 // output profile or if new device is not supported AND previous device(s) is(are) still
6994 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006995 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006996 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6997 // restore previous device after evaluating strategy mute state
6998 outputDesc->setDevices(prevDevices);
6999 return muteWaitMs;
7000 }
7001
Eric Laurente552edb2014-03-10 17:42:56 -07007002 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007003 // the requested device is AUDIO_DEVICE_NONE
7004 // OR the requested device is the same as current device
7005 // AND force is not specified
7006 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007007 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007008 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007009 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7010 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007011 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7012 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7013 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7014 }
Eric Laurente552edb2014-03-10 17:42:56 -07007015 return muteWaitMs;
7016 }
7017
François Gaffie11d30102018-11-02 16:09:09 +01007018 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007019
Eric Laurente552edb2014-03-10 17:42:56 -07007020 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007021 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007022 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007023 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007024 PatchBuilder patchBuilder;
7025 patchBuilder.addSource(outputDesc);
7026 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7027 for (const auto &filteredDevice : filteredDevices) {
7028 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007029 }
7030
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007031 // Add half reported latency to delayMs when muteWaitMs is null in order
7032 // to avoid disordered sequence of muting volume and changing devices.
7033 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7034 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007035 }
Eric Laurente552edb2014-03-10 17:42:56 -07007036
7037 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007038 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007039
7040 return muteWaitMs;
7041}
7042
Eric Laurentc75307b2015-03-17 15:29:32 -07007043status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007044 int delayMs,
7045 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007046{
Eric Laurent6a94d692014-05-20 11:18:06 -07007047 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007048 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7049 return INVALID_OPERATION;
7050 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007051 if (patchHandle) {
7052 index = mAudioPatches.indexOfKey(*patchHandle);
7053 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007054 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007055 }
7056 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007057 return INVALID_OPERATION;
7058 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007059 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007060 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007061 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007062 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007063 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007064 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007065 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007066 return status;
7067}
7068
7069status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007070 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007071 bool force,
7072 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007073{
7074 status_t status = NO_ERROR;
7075
Eric Laurent1f2f2232014-06-02 12:01:23 -07007076 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007077 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7078 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007079
François Gaffie11d30102018-11-02 16:09:09 +01007080 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007081 PatchBuilder patchBuilder;
7082 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007083 // AUDIO_SOURCE_HOTWORD is for internal use only:
7084 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007085 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7086 auto result = usecase;
7087 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7088 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7089 }
7090 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007091 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007092 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007093 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007094 }
7095 }
7096 return status;
7097}
7098
Eric Laurent6a94d692014-05-20 11:18:06 -07007099status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7100 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007101{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007102 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007103 ssize_t index;
7104 if (patchHandle) {
7105 index = mAudioPatches.indexOfKey(*patchHandle);
7106 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007107 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007108 }
7109 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007110 return INVALID_OPERATION;
7111 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007112 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007113 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007114 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007115 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007116 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007117 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007118 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007119 return status;
7120}
7121
François Gaffie11d30102018-11-02 16:09:09 +01007122sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007123 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007124 audio_format_t& format,
7125 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007126 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007127{
7128 // Choose an input profile based on the requested capture parameters: select the first available
7129 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007130 //
7131 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7132 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007133
Glenn Kasten730b9262018-03-29 15:01:26 -07007134 sp<IOProfile> firstInexact;
7135 uint32_t updatedSamplingRate = 0;
7136 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7137 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007138 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007139 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007140 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007141 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007142 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007143 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007144 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007145 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007146 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007147 &channelMask /*updatedChannelMask*/,
7148 // FIXME ugly cast
7149 (audio_output_flags_t) flags,
7150 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007151 return profile;
7152 }
François Gaffie11d30102018-11-02 16:09:09 +01007153 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007154 samplingRate,
7155 &updatedSamplingRate,
7156 format,
7157 &updatedFormat,
7158 channelMask,
7159 &updatedChannelMask,
7160 // FIXME ugly cast
7161 (audio_output_flags_t) flags,
7162 false /*exactMatchRequiredForInputFlags*/)) {
7163 firstInexact = profile;
7164 }
7165
Eric Laurente552edb2014-03-10 17:42:56 -07007166 }
7167 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007168 if (firstInexact != nullptr) {
7169 samplingRate = updatedSamplingRate;
7170 format = updatedFormat;
7171 channelMask = updatedChannelMask;
7172 return firstInexact;
7173 }
Eric Laurente552edb2014-03-10 17:42:56 -07007174 return NULL;
7175}
7176
François Gaffieaaac0fd2018-11-22 17:56:39 +01007177float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7178 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007179 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007180 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007181{
jiabin9a3361e2019-10-01 09:38:30 -07007182 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007183
7184 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7185 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7186 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7187 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007188 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7189 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7190 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7191 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7192 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007193
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007194 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007195 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7196 mOutputs.isActive(ringVolumeSrc, 0)) {
7197 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007198 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007199 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007200 }
7201
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007202 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007203 if ((volumeSource != callVolumeSrc && (isInCall() ||
7204 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007205 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007206 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7207 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007208 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7209 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7210 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007211 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007212 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007213 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007214 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007215 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007216 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007217 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7218 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7219 // programmatically muted.
7220 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7221 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7222 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007223 bool exemptFromCapping =
7224 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7225 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007226 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7227 volumeSource, volumeDb);
7228 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007229 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7230 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7231 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007232 }
7233 }
Eric Laurente552edb2014-03-10 17:42:56 -07007234 // if a headset is connected, apply the following rules to ring tones and notifications
7235 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007236 // - always attenuate notifications volume by 6dB
7237 // - attenuate ring tones volume by 6dB unless music is not playing and
7238 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007239 // - if music is playing, always limit the volume to current music volume,
7240 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007241 if (!Intersection(deviceTypes,
7242 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7243 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007244 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7245 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007246 ((volumeSource == alarmVolumeSrc ||
7247 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007248 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7249 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7250 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007251 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7252 curves.canBeMuted()) {
7253
Eric Laurente552edb2014-03-10 17:42:56 -07007254 // when the phone is ringing we must consider that music could have been paused just before
7255 // by the music application and behave as if music was active if the last music track was
7256 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007257 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007258 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007259 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007260 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007261 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7262 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007263 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007264 float musicVolDb = computeVolume(musicCurves,
7265 musicVolumeSrc,
7266 musicCurves.getVolumeIndex(musicDevice),
7267 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007268 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7269 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7270 if (volumeDb > minVolDb) {
7271 volumeDb = minVolDb;
7272 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007273 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007274 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7275 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7276 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007277 // on A2DP, also ensure notification volume is not too low compared to media when
7278 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007279 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007280 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007281 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7282 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007283 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7284 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007285 }
7286 }
jiabin9a3361e2019-10-01 09:38:30 -07007287 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007288 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007289 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007290 }
7291 }
7292
François Gaffie43c73442018-11-08 08:21:55 +01007293 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007294}
7295
Eric Laurent3839bc02018-07-10 18:33:34 -07007296int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007297 VolumeSource fromVolumeSource,
7298 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007299{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007300 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007301 return srcIndex;
7302 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007303 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7304 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007305 float minSrc = (float)srcCurves.getVolumeIndexMin();
7306 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7307 float minDst = (float)dstCurves.getVolumeIndexMin();
7308 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007309
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007310 // preserve mute request or correct range
7311 if (srcIndex < minSrc) {
7312 if (srcIndex == 0) {
7313 return 0;
7314 }
7315 srcIndex = minSrc;
7316 } else if (srcIndex > maxSrc) {
7317 srcIndex = maxSrc;
7318 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007319 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7320}
7321
François Gaffieaaac0fd2018-11-22 17:56:39 +01007322status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7323 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007324 int index,
7325 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007326 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007327 int delayMs,
7328 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007329{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007330 // do not change actual attributes volume if the attributes is muted
7331 if (outputDesc->isMuted(volumeSource)) {
7332 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7333 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007334 return NO_ERROR;
7335 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007336 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7337 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7338 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7339 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007340
Eric Laurent2517af32020-11-25 15:31:27 +01007341 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007342 bool isHAUsed = isHearingAidUsedForComm();
7343
Eric Laurente552edb2014-03-10 17:42:56 -07007344 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007345 // if sco and call follow same curves, bypass forceUseForComm
7346 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007347 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007348 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7349 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007350 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007351 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007352 // Do not return an error here as AudioService will always set both voice call
7353 // and bluetooth SCO volumes due to stream aliasing.
7354 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007355 }
jiabin9a3361e2019-10-01 09:38:30 -07007356 if (deviceTypes.empty()) {
7357 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007358 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007359
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007360 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7361 ALOGE("invalid volume index range");
7362 return BAD_VALUE;
7363 }
7364
jiabin9a3361e2019-10-01 09:38:30 -07007365 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7366 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007367 // Force VoIP volume to max for bluetooth SCO device except if muted
7368 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007369 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007370 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007371 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007372 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007373 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007374 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007375
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007376 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007377 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007378 // 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 +01007379 if (isVoiceVolSrc) {
7380 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007381 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007382 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007383 }
Eric Laurent18fba842016-03-31 14:41:26 -07007384 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007385 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7386 mLastVoiceVolume = voiceVolume;
7387 }
7388 }
Eric Laurente552edb2014-03-10 17:42:56 -07007389 return NO_ERROR;
7390}
7391
Eric Laurentc75307b2015-03-17 15:29:32 -07007392void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007393 const DeviceTypeSet& deviceTypes,
7394 int delayMs,
7395 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007396{
jiabincd510522020-01-22 09:40:55 -08007397 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007398 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7399 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7400 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007401 curves.getVolumeIndex(deviceTypes),
7402 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007403 }
7404}
7405
François Gaffiec005e562018-11-06 15:04:49 +01007406void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7407 bool on,
7408 const sp<AudioOutputDescriptor>& outputDesc,
7409 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007410 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007411{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007412 std::vector<VolumeSource> sourcesToMute;
7413 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7414 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7415 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007416 VolumeSource source = toVolumeSource(attributes, false);
7417 if ((source != VOLUME_SOURCE_NONE) &&
7418 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7419 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007420 sourcesToMute.push_back(source);
7421 }
Eric Laurente552edb2014-03-10 17:42:56 -07007422 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007423 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007424 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007425 }
7426
Eric Laurente552edb2014-03-10 17:42:56 -07007427}
7428
François Gaffieaaac0fd2018-11-22 17:56:39 +01007429void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7430 bool on,
7431 const sp<AudioOutputDescriptor>& outputDesc,
7432 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007433 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007434{
jiabin9a3361e2019-10-01 09:38:30 -07007435 if (deviceTypes.empty()) {
7436 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007437 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007438 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007439 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007440 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007441 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007442 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007443 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7444 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007445 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007446 }
7447 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007448 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7449 // ignored
7450 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007451 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007452 if (!outputDesc->isMuted(volumeSource)) {
7453 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007454 return;
7455 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007456 if (outputDesc->decMuteCount(volumeSource) == 0) {
7457 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007458 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007459 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007460 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007461 delayMs);
7462 }
7463 }
7464}
7465
François Gaffie53615e22015-03-19 09:24:12 +01007466bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7467{
François Gaffiec005e562018-11-06 15:04:49 +01007468 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007469 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7470 return true;
7471 }
7472
7473 // has known usage?
7474 switch (paa->usage) {
7475 case AUDIO_USAGE_UNKNOWN:
7476 case AUDIO_USAGE_MEDIA:
7477 case AUDIO_USAGE_VOICE_COMMUNICATION:
7478 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7479 case AUDIO_USAGE_ALARM:
7480 case AUDIO_USAGE_NOTIFICATION:
7481 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7482 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7483 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7484 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7485 case AUDIO_USAGE_NOTIFICATION_EVENT:
7486 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7487 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7488 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7489 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007490 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007491 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007492 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007493 case AUDIO_USAGE_EMERGENCY:
7494 case AUDIO_USAGE_SAFETY:
7495 case AUDIO_USAGE_VEHICLE_STATUS:
7496 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007497 break;
7498 default:
7499 return false;
7500 }
7501 return true;
7502}
7503
François Gaffie2110e042015-03-24 08:41:51 +01007504audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7505{
7506 return mEngine->getForceUse(usage);
7507}
7508
Eric Laurent96d1dda2022-03-14 17:14:19 +01007509bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007510 return isStateInCall(mEngine->getPhoneState());
7511}
7512
Eric Laurent96d1dda2022-03-14 17:14:19 +01007513bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007514 return is_state_in_call(state);
7515}
7516
Eric Laurentf9cccec2022-11-16 19:12:00 +01007517bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007518 audio_mode_t mode = mEngine->getPhoneState();
7519 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007520 || (mode == AUDIO_MODE_CALL_SCREEN)
7521 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007522}
7523
Eric Laurentf9cccec2022-11-16 19:12:00 +01007524bool AudioPolicyManager::isInCallOrScreening() const {
7525 audio_mode_t mode = mEngine->getPhoneState();
7526 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7527}
7528
Eric Laurentd60560a2015-04-10 11:31:20 -07007529void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7530{
7531 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007532 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007533 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007534 sourceDesc->sinkDevice()->equals(deviceDesc))
7535 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007536 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007537 }
7538 }
7539
7540 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7541 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7542 bool release = false;
7543 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7544 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7545 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7546 source->ext.device.type == deviceDesc->type()) {
7547 release = true;
7548 }
7549 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007550 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007551 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7552 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7553 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007554 sink->ext.device.type == deviceDesc->type() &&
7555 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7556 || strncmp(sink->ext.device.address, address,
7557 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007558 release = true;
7559 }
7560 }
7561 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007562 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7563 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007564 }
7565 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007566
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007567 mInputs.clearSessionRoutesForDevice(deviceDesc);
7568
Francois Gaffie716e1432019-01-14 16:58:59 +01007569 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007570}
7571
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007572void AudioPolicyManager::modifySurroundFormats(
7573 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007574 std::unordered_set<audio_format_t> enforcedSurround(
7575 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007576 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganovb0fbc1b2023-04-28 13:06:32 -07007577 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007578 allSurround.insert(pair.first);
7579 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7580 }
Phil Burk09bc4612016-02-24 15:58:15 -08007581
7582 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7583 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007584 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007585 // This is the resulting set of formats depending on the surround mode:
7586 // 'all surround' = allSurround
7587 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7588 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7589 // 'manual surround' = mManualSurroundFormats
7590 // AUTO: formats v 'enforced surround'
7591 // ALWAYS: formats v 'all surround' v 'enforced surround'
7592 // NEVER: formats ^ 'non-surround'
7593 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007594
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007595 std::unordered_set<audio_format_t> formatSet;
7596 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7597 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007598 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007599 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007600 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007601 formatSet.insert(*formatIter);
7602 }
7603 }
7604 } else {
7605 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7606 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007608
jiabin81772902018-04-02 17:52:27 -07007609 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007610 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007611 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7612 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7613 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007614 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007615 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7616 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7617 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007618 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007619 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007620 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007621 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007622 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007623 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007624}
7625
jiabin06e4bab2019-07-29 10:13:34 -07007626void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7627 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007628 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7629 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7630
7631 // If NEVER, then remove support for channelMasks > stereo.
7632 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007633 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7634 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007635 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007636 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007637 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007638 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007639 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007640 }
7641 }
jiabin81772902018-04-02 17:52:27 -07007642 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7643 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7644 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007645 bool supports5dot1 = false;
7646 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007647 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007648 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7649 supports5dot1 = true;
7650 break;
7651 }
7652 }
7653 // If not then add 5.1 support.
7654 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007655 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007656 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007657 }
Phil Burk09bc4612016-02-24 15:58:15 -08007658 }
7659}
7660
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007661void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007662 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007663 AudioProfileVector &profiles)
7664{
7665 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007666 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007667
François Gaffie112b0af2015-11-19 16:13:25 +01007668 // Format MUST be checked first to update the list of AudioProfile
7669 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007670 reply = mpClientInterface->getParameters(
7671 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007672 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007673 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00007674 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08007675 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00007676 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
7677 formats = formatsFromString(reply.string());
7678 } else if (devDesc->hasValidAudioProfile()) {
7679 ALOGD("%s: using the device profiles", __func__);
7680 formats = devDesc->getAudioProfiles().getSupportedFormats();
7681 } else {
7682 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01007683 return;
7684 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01007685 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007686 if (device == AUDIO_DEVICE_OUT_HDMI
7687 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007688 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007689 }
jiabin3e277cc2019-09-10 14:27:34 -07007690 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007691 }
François Gaffie112b0af2015-11-19 16:13:25 +01007692
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007693 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00007694 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07007695 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007696 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007697 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007698
7699 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007700 reply = mpClientInterface->getParameters(
7701 ioHandle,
7702 requestedParameters.toString() + ";" +
7703 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007704 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007705 AudioParameter repliedParameters(reply);
7706 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007707 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007708 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007709 } else {
7710 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01007711 }
7712 }
7713 if (profiles.hasDynamicChannelsFor(format)) {
7714 reply = mpClientInterface->getParameters(ioHandle,
7715 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007716 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007717 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007718 AudioParameter repliedParameters(reply);
7719 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007720 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007721 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007722 } else {
7723 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
7724 }
7725 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
7726 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
7727 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01007728 }
7729 }
jiabin3e277cc2019-09-10 14:27:34 -07007730 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00007731 profiles, new AudioProfile(
7732 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007733 }
7734}
Eric Laurentd60560a2015-04-10 11:31:20 -07007735
Mikhail Naganovdc769682018-05-04 15:34:08 -07007736status_t AudioPolicyManager::installPatch(const char *caller,
7737 audio_patch_handle_t *patchHandle,
7738 AudioIODescriptorInterface *ioDescriptor,
7739 const struct audio_patch *patch,
7740 int delayMs)
7741{
7742 ssize_t index = mAudioPatches.indexOfKey(
7743 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7744 *patchHandle : ioDescriptor->getPatchHandle());
7745 sp<AudioPatch> patchDesc;
7746 status_t status = installPatch(
7747 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7748 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007749 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007750 }
7751 return status;
7752}
7753
7754status_t AudioPolicyManager::installPatch(const char *caller,
7755 ssize_t index,
7756 audio_patch_handle_t *patchHandle,
7757 const struct audio_patch *patch,
7758 int delayMs,
7759 uid_t uid,
7760 sp<AudioPatch> *patchDescPtr)
7761{
7762 sp<AudioPatch> patchDesc;
7763 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7764 if (index >= 0) {
7765 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007766 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007767 }
7768
7769 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7770 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7771 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7772 if (status == NO_ERROR) {
7773 if (index < 0) {
7774 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007775 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007776 } else {
7777 patchDesc->mPatch = *patch;
7778 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007779 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007780 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007781 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007782 }
7783 nextAudioPortGeneration();
7784 mpClientInterface->onAudioPatchListUpdate();
7785 }
7786 if (patchDescPtr) *patchDescPtr = patchDesc;
7787 return status;
7788}
7789
jiabinbce0c1d2020-10-05 11:20:18 -07007790bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7791{
7792 const TrackClientVector activeClients = output->getActiveClients();
7793 if (activeClients.empty()) {
7794 return true;
7795 }
7796 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7797 if (index < 0) {
7798 ALOGE("%s, no audio patch found while there are active clients on output %d",
7799 __func__, output->getId());
7800 return false;
7801 }
7802 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7803 DeviceVector routedDevices;
7804 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7805 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7806 patchDesc->mPatch.sinks[i].id);
7807 if (device == nullptr) {
7808 ALOGE("%s, no audio device found with id(%d)",
7809 __func__, patchDesc->mPatch.sinks[i].id);
7810 return false;
7811 }
7812 routedDevices.add(device);
7813 }
7814 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007815 if (client->isInvalid()) {
7816 // No need to take care about invalidated clients.
7817 continue;
7818 }
jiabinbce0c1d2020-10-05 11:20:18 -07007819 sp<DeviceDescriptor> preferredDevice =
7820 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7821 if (mEngine->getOutputDevicesForAttributes(
7822 client->attributes(), preferredDevice, false) == routedDevices) {
7823 return false;
7824 }
7825 }
7826 return true;
7827}
7828
7829sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007830 const sp<IOProfile>& profile, const DeviceVector& devices,
7831 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007832{
7833 for (const auto& device : devices) {
7834 // TODO: This should be checking if the profile supports the device combo.
7835 if (!profile->supportsDevice(device)) {
7836 return nullptr;
7837 }
7838 }
7839 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7840 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007841 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007842 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7843 if (status != NO_ERROR) {
7844 return nullptr;
7845 }
7846
7847 // Here is where the out_set_parameters() for card & device gets called
7848 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7849 const audio_devices_t deviceType = device->type();
7850 const String8 &address = String8(device->address().c_str());
7851 if (!address.isEmpty()) {
7852 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7853 mpClientInterface->setParameters(output, String8(param));
7854 free(param);
7855 }
7856 updateAudioProfiles(device, output, profile->getAudioProfiles());
7857 if (!profile->hasValidAudioProfile()) {
7858 ALOGW("%s() missing param", __func__);
7859 desc->close();
7860 return nullptr;
7861 } else if (profile->hasDynamicAudioProfile()) {
7862 desc->close();
7863 output = AUDIO_IO_HANDLE_NONE;
7864 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7865 profile->pickAudioProfile(
7866 config.sample_rate, config.channel_mask, config.format);
7867 config.offload_info.sample_rate = config.sample_rate;
7868 config.offload_info.channel_mask = config.channel_mask;
7869 config.offload_info.format = config.format;
7870
Eric Laurentb4f42a92022-01-17 17:37:31 +01007871 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007872 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7873 if (status != NO_ERROR) {
7874 return nullptr;
7875 }
7876 }
7877
7878 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007879
baek.kim -61c20122022-07-27 10:05:32 +00007880 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7881 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7882
jiabinbce0c1d2020-10-05 11:20:18 -07007883 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7884 sp<AudioPolicyMix> policyMix;
7885 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7886 policyMix->setOutput(desc);
7887 desc->mPolicyMix = policyMix;
7888 } else {
7889 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7890 address.string());
7891 }
7892
baek.kim -61c20122022-07-27 10:05:32 +00007893 } else if (hasPrimaryOutput() && speaker != nullptr
7894 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007895 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7896 // no duplicated output for:
7897 // - direct outputs
7898 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007899 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007900 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7901
7902 //TODO: configure audio effect output stage here
7903
7904 // open a duplicating output thread for the new output and the primary output
7905 sp<SwAudioOutputDescriptor> dupOutputDesc =
7906 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7907 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7908 if (status == NO_ERROR) {
7909 // add duplicated output descriptor
7910 addOutput(duplicatedOutput, dupOutputDesc);
7911 } else {
7912 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7913 mPrimaryOutput->mIoHandle, output);
7914 desc->close();
7915 removeOutput(output);
7916 nextAudioPortGeneration();
7917 return nullptr;
7918 }
7919 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007920 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7921 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7922 mPrimaryOutput = desc;
7923 }
jiabinbce0c1d2020-10-05 11:20:18 -07007924 return desc;
7925}
7926
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007927} // namespace android