blob: 3d6bc5b9d450d96cd0bc77be3f46361aa1007c59 [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();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
789 struct audio_port_config source = {};
790 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 mCallTxSourceClient = new InternalSourceClientDescriptor(
792 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200793 mCommunnicationStrategy, toVolumeSource(aa));
794 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
795 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
797 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
799 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200802}
803
Eric Laurente0720872014-03-11 09:30:41 -0700804void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700805{
806 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100807 // store previous phone state for management of sonification strategy below
808 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100809 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100810
811 if (mEngine->setPhoneState(state) != NO_ERROR) {
812 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700813 return;
814 }
François Gaffie2110e042015-03-24 08:41:51 +0100815 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700816 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700817 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700818 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800819 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700820 }
821
François Gaffie2110e042015-03-24 08:41:51 +0100822 /**
823 * Switching to or from incall state or switching between telephony and VoIP lead to force
824 * routing command.
825 */
Eric Laurent74b71512019-11-06 17:21:57 -0800826 bool force = ((isStateInCall(oldState) != isStateInCall(state))
827 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700828
829 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700830 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700831
Eric Laurente552edb2014-03-10 17:42:56 -0700832 int delayMs = 0;
833 if (isStateInCall(state)) {
834 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100835 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
836 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700837 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700838 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700839 // mute media and sonification strategies and delay device switch by the largest
840 // latency of any output where either strategy is active.
841 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100842 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
843 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
844 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700845 (delayMs < (int)desc->latency()*2)) {
846 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700847 }
François Gaffiec005e562018-11-06 15:04:49 +0100848 setStrategyMute(musicStrategy, true, desc);
849 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
850 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
851 nullptr, true /*fromCache*/).types());
852 setStrategyMute(sonificationStrategy, true, desc);
853 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
854 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
855 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700856 }
857 }
858
Eric Laurent87ffa392015-05-22 10:32:38 -0700859 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700860 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100861 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700862 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100863 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
864 // force routing command to audio hardware when ending call
865 // even if no device change is needed
866 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
867 rxDevices = mPrimaryOutput->devices();
868 }
869 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200870 disconnectTelephonyAudioSource(mCallRxSourceClient);
871 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100872 }
François Gaffie11d30102018-11-02 16:09:09 +0100873 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700874 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700875 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700876
877 // reevaluate routing on all outputs in case tracks have been started during the call
878 for (size_t i = 0; i < mOutputs.size(); i++) {
879 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100880 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200881 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
882 bool forceRouting = !newDevices.isEmpty();
883 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
884 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700885 }
886 }
887
Eric Laurent96d1dda2022-03-14 17:14:19 +0100888 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 if (isStateInCall(state)) {
891 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700892 // force reevaluating accessibility routing when call starts
893 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700894 }
895
896 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100897 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
898 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700899}
900
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700901audio_mode_t AudioPolicyManager::getPhoneState() {
902 return mEngine->getPhoneState();
903}
904
Eric Laurente0720872014-03-11 09:30:41 -0700905void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100906 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700907{
François Gaffie2110e042015-03-24 08:41:51 +0100908 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700909 if (config == mEngine->getForceUse(usage)) {
910 return;
911 }
Eric Laurente552edb2014-03-10 17:42:56 -0700912
François Gaffie2110e042015-03-24 08:41:51 +0100913 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
914 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
915 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700916 }
François Gaffie2110e042015-03-24 08:41:51 +0100917 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
918 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
919 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700920
921 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700922 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800923
Eric Laurent22fcda22019-05-17 16:28:47 -0700924 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
925 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
926 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
927 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
928 }
929
Eric Laurentdc462862016-07-19 12:29:53 -0700930 //FIXME: workaround for truncated touch sounds
931 // to be removed when the problem is handled by system UI
932 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700933 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
934 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
935 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700936
937 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100938 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700939}
940
Eric Laurente0720872014-03-11 09:30:41 -0700941void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700942{
943 ALOGV("setSystemProperty() property %s, value %s", property, value);
944}
945
Dorin Drimusecc9f422022-03-09 17:57:40 +0100946// Find an MSD output profile compatible with the parameters passed.
947// When "directOnly" is set, restrict search to profiles for direct outputs.
948sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
949 const DeviceVector& devices,
950 uint32_t samplingRate,
951 audio_format_t format,
952 audio_channel_mask_t channelMask,
953 audio_output_flags_t flags,
954 bool directOnly)
955{
956 flags = getRelevantFlags(flags, directOnly);
957
958 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
959 if (msdModule != nullptr) {
960 // for the msd module check if there are patches to the output devices
961 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
962 HwModuleCollection modules;
963 modules.add(msdModule);
964 return searchCompatibleProfileHwModules(
965 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
966 flags, directOnly);
967 }
968 }
969 return nullptr;
970}
971
Michael Chana94fbb22018-04-24 14:31:19 +1000972// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
973// search to profiles for direct outputs.
974sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100975 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000976 uint32_t samplingRate,
977 audio_format_t format,
978 audio_channel_mask_t channelMask,
979 audio_output_flags_t flags,
980 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700981{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100982 flags = getRelevantFlags(flags, directOnly);
983
984 return searchCompatibleProfileHwModules(
985 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
986}
987
988audio_output_flags_t AudioPolicyManager::getRelevantFlags (
989 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000990 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100991 // only retain flags that will drive the direct output profile selection
992 // if explicitly requested
993 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000994 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100995 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
996 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000997 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998 return flags;
999}
Eric Laurent861a6282015-05-18 15:40:16 -07001000
Dorin Drimusecc9f422022-03-09 17:57:40 +01001001sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1002 const HwModuleCollection& hwModules,
1003 const DeviceVector& devices,
1004 uint32_t samplingRate,
1005 audio_format_t format,
1006 audio_channel_mask_t channelMask,
1007 audio_output_flags_t flags,
1008 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001009 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001010 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001011 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012 if (!curProfile->isCompatibleProfile(devices,
1013 samplingRate, NULL /*updatedSamplingRate*/,
1014 format, NULL /*updatedFormat*/,
1015 channelMask, NULL /*updatedChannelMask*/,
1016 flags)) {
1017 continue;
1018 }
1019 // reject profiles not corresponding to a device currently available
1020 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1021 continue;
1022 }
1023 // reject profiles if connected device does not support codec
1024 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1025 continue;
1026 }
1027 if (!directOnly) {
1028 return curProfile;
1029 }
1030
1031 // when searching for direct outputs, if several profiles are compatible, give priority
1032 // to one with offload capability
Patty Huangf5082dd2022-07-06 00:14:12 +08001033 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001034 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001035 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 }
1037 profile = curProfile;
1038 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1039 break;
1040 }
Eric Laurente552edb2014-03-10 17:42:56 -07001041 }
1042 }
Eric Laurent861a6282015-05-18 15:40:16 -07001043 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001044}
1045
Eric Laurentfa0f6742021-08-17 18:39:44 +02001046sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001047 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001048{
1049 for (const auto& hwModule : mHwModules) {
1050 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001051 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001052 continue;
1053 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001054 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001055 // reject profiles not corresponding to a device currently available
1056 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1057 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1058 continue;
1059 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001060 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1061 != devices.size()) {
1062 continue;
1063 }
1064 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001065 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1066 return curProfile;
1067 }
1068 }
1069 return nullptr;
1070}
1071
Eric Laurentf4e63452017-11-06 19:31:46 +00001072audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
François Gaffiec005e562018-11-06 15:04:49 +01001074 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001075
1076 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1077 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1078 // format, flags, etc. This may result in some discrepancy for functions that utilize
1079 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1080 // and AudioSystem::getOutputSamplingRate().
1081
François Gaffie11d30102018-11-02 16:09:09 +01001082 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001083 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001084
François Gaffie11d30102018-11-02 16:09:09 +01001085 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1086 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001087 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001088}
1089
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001090status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1091 const audio_attributes_t *srcAttr,
1092 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001093{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001094 if (srcAttr != NULL) {
1095 if (!isValidAttributes(srcAttr)) {
1096 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1097 __func__,
1098 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1099 srcAttr->tags);
1100 return BAD_VALUE;
1101 }
1102 *dstAttr = *srcAttr;
1103 } else {
1104 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1105 ALOGE("%s: invalid stream type", __func__);
1106 return BAD_VALUE;
1107 }
François Gaffiec005e562018-11-06 15:04:49 +01001108 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001109 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001110
1111 // Only honor audibility enforced when required. The client will be
1112 // forced to reconnect if the forced usage changes.
1113 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001114 dstAttr->flags = static_cast<audio_flags_mask_t>(
1115 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001116 }
1117
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001118 return NO_ERROR;
1119}
1120
Kevin Rocard153f92d2018-12-18 18:33:28 -08001121status_t AudioPolicyManager::getOutputForAttrInt(
1122 audio_attributes_t *resultAttr,
1123 audio_io_handle_t *output,
1124 audio_session_t session,
1125 const audio_attributes_t *attr,
1126 audio_stream_type_t *stream,
1127 uid_t uid,
1128 const audio_config_t *config,
1129 audio_output_flags_t *flags,
1130 audio_port_handle_t *selectedDeviceId,
1131 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001132 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001133 output_type_t *outputType,
1134 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001135{
François Gaffiec005e562018-11-06 15:04:49 +01001136 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001137 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001138 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001139 const sp<DeviceDescriptor> requestedDevice =
1140 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1141
Eric Laurent8a1095a2019-11-08 14:44:16 -08001142 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001143 *isSpatialized = false;
1144
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001145 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1146 if (status != NO_ERROR) {
1147 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001148 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001149 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001150 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001151 }
François Gaffiec005e562018-11-06 15:04:49 +01001152 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001153
François Gaffiec005e562018-11-06 15:04:49 +01001154 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1155 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001156
Kevin Rocard153f92d2018-12-18 18:33:28 -08001157 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1158 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1159 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001160 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001161 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1162 .channel_mask = config->channel_mask,
1163 .format = config->format,
1164 };
1165 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1166 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001167 if (status != OK) {
1168 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001170
Kevin Rocard153f92d2018-12-18 18:33:28 -08001171 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001173
1174 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001175 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1176 && !audio_is_linear_pcm(config->format)) {
1177 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001178 return BAD_VALUE;
1179 }
1180 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001181 sp<DeviceDescriptor> deviceDesc =
1182 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1183 primaryMix->mDeviceAddress,
1184 AUDIO_FORMAT_DEFAULT);
1185 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001186 bool tryDirectForFlags = policyDesc == nullptr ||
1187 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1188 // if a direct output can be opened to deliver the track's multi-channel content to the
1189 // output rather than being downmixed by the primary output, then use this direct
1190 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1191 // mix.
1192 bool tryDirectForChannelMask = policyDesc != nullptr
1193 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1194 audio_channel_count_from_out_mask(config->channel_mask));
1195 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001196 audio_io_handle_t newOutput;
1197 status = openDirectOutput(
1198 *stream, session, config,
1199 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1200 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001201 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001202 policyDesc = mOutputs.valueFor(newOutput);
1203 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001204 } else if (tryDirectForFlags) {
1205 policyDesc = nullptr;
1206 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001207 }
1208 if (policyDesc != nullptr) {
1209 policyDesc->mPolicyMix = primaryMix;
1210 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001211 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001212
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001213 ALOGV("getOutputForAttr() returns output %d", *output);
1214 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1215 *outputType = API_OUT_MIX_PLAYBACK;
1216 } else {
1217 *outputType = API_OUTPUT_LEGACY;
1218 }
1219 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001220 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001221 }
François Gaffiec005e562018-11-06 15:04:49 +01001222 // Virtual sources must always be dynamicaly or explicitly routed
1223 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1224 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1225 return BAD_VALUE;
1226 }
1227 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1228 // in order to let the choice of the order to future vendor engine
1229 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001230
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001231 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001232 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001233 }
1234
Nadav Barb2f18162018-07-18 13:01:53 +03001235 // Set incall music only if device was explicitly set, and fallback to the device which is
1236 // chosen by the engine if not.
1237 // FIXME: provide a more generic approach which is not device specific and move this back
1238 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001239 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001240 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001241 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001242 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001243 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001244 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001245 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001246 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001247 }
1248 }
1249
François Gaffiec005e562018-11-06 15:04:49 +01001250 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1251 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1252 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001253
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001254 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001255 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001256 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001257 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001258 ALOGV("%s() Using MSD devices %s instead of devices %s",
1259 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001260 } else {
1261 *output = AUDIO_IO_HANDLE_NONE;
1262 }
1263 }
1264 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001265 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001266 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001267 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001268 if (*output == AUDIO_IO_HANDLE_NONE) {
1269 return INVALID_OPERATION;
1270 }
Paul McLeanaa981192015-03-21 09:55:15 -07001271
François Gaffiec005e562018-11-06 15:04:49 +01001272 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001273 for (auto &outputDevice : outputDevices) {
1274 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1275 *selectedDeviceId = outputDevice->getId();
1276 break;
1277 }
1278 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001279
Eric Laurent8a1095a2019-11-08 14:44:16 -08001280 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1281 *outputType = API_OUTPUT_TELEPHONY_TX;
1282 } else {
1283 *outputType = API_OUTPUT_LEGACY;
1284 }
1285
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001286 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1287
1288 return NO_ERROR;
1289}
1290
1291status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1292 audio_io_handle_t *output,
1293 audio_session_t session,
1294 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001295 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001296 const audio_config_t *config,
1297 audio_output_flags_t *flags,
1298 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001299 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001300 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001301 output_type_t *outputType,
1302 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001303{
1304 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1305 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1306 return INVALID_OPERATION;
1307 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001308 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001309 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001310 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001311 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001312 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001313 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001314 const sp<DeviceDescriptor> requestedDevice =
1315 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1316
1317 // Prevent from storing invalid requested device id in clients
1318 const audio_port_handle_t sanitizedRequestedPortId =
1319 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1320 *selectedDeviceId = sanitizedRequestedPortId;
1321
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001322 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001323 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001324 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001325 if (status != NO_ERROR) {
1326 return status;
1327 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001328 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001329 if (secondaryOutputs != nullptr) {
1330 for (auto &secondaryMix : secondaryMixes) {
1331 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1332 if (outputDesc != nullptr &&
1333 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1334 secondaryOutputs->push_back(outputDesc->mIoHandle);
1335 weakSecondaryOutputDescs.push_back(outputDesc);
1336 }
1337 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001338 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001339
Eric Laurent8fc147b2018-07-22 19:13:55 -07001340 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001341 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001342 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001343 };
jiabin4ef93452019-09-10 14:29:54 -07001344 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001345
Eric Laurentc209fe42020-06-05 18:11:23 -07001346 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001347 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001348 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001349 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001350 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001351 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001352 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001353 std::move(weakSecondaryOutputDescs),
1354 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001355 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001356
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001357 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1358 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001359
Eric Laurente83b55d2014-11-14 10:06:21 -08001360 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001361}
1362
Eric Laurentc529cf62020-04-17 18:19:10 -07001363status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1364 audio_session_t session,
1365 const audio_config_t *config,
1366 audio_output_flags_t flags,
1367 const DeviceVector &devices,
1368 audio_io_handle_t *output) {
1369
1370 *output = AUDIO_IO_HANDLE_NONE;
1371
1372 // skip direct output selection if the request can obviously be attached to a mixed output
1373 // and not explicitly requested
1374 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1375 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1376 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1377 return NAME_NOT_FOUND;
1378 }
1379
1380 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1381 // This prevents creating an offloaded track and tearing it down immediately after start
1382 // when audioflinger detects there is an active non offloadable effect.
1383 // FIXME: We should check the audio session here but we do not have it in this context.
1384 // This may prevent offloading in rare situations where effects are left active by apps
1385 // in the background.
1386 sp<IOProfile> profile;
1387 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1388 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1389 profile = getProfileForOutput(
1390 devices, config->sample_rate, config->format, config->channel_mask,
1391 flags, true /* directOnly */);
1392 }
1393
1394 if (profile == nullptr) {
1395 return NAME_NOT_FOUND;
1396 }
1397
1398 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1399 for (size_t i = 0; i < mOutputs.size(); i++) {
1400 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1401 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1402 // reuse direct output if currently open by the same client
1403 // and configured with same parameters
1404 if ((config->sample_rate == desc->getSamplingRate()) &&
1405 (config->format == desc->getFormat()) &&
1406 (config->channel_mask == desc->getChannelMask()) &&
1407 (session == desc->mDirectClientSession)) {
1408 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001409 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001410 mOutputs.keyAt(i), session);
1411 *output = mOutputs.keyAt(i);
1412 return NO_ERROR;
1413 }
1414 }
1415 }
1416
1417 if (!profile->canOpenNewIo()) {
1418 return NAME_NOT_FOUND;
1419 }
1420
1421 sp<SwAudioOutputDescriptor> outputDesc =
1422 new SwAudioOutputDescriptor(profile, mpClientInterface);
1423
Michael Chan6fb34492020-12-08 15:44:49 +11001424 // An MSD patch may be using the only output stream that can service this request. Release
1425 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001426 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001427
Eric Laurentf1f22e72021-07-13 14:04:14 +02001428 status_t status =
1429 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001430
1431 // only accept an output with the requested parameters
1432 if (status != NO_ERROR ||
1433 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1434 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1435 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1436 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1437 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1438 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1439 config->channel_mask, outputDesc->getChannelMask());
1440 if (*output != AUDIO_IO_HANDLE_NONE) {
1441 outputDesc->close();
1442 }
1443 // fall back to mixer output if possible when the direct output could not be open
1444 if (audio_is_linear_pcm(config->format) &&
1445 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1446 return NAME_NOT_FOUND;
1447 }
1448 *output = AUDIO_IO_HANDLE_NONE;
1449 return BAD_VALUE;
1450 }
1451 outputDesc->mDirectOpenCount = 1;
1452 outputDesc->mDirectClientSession = session;
1453
1454 addOutput(*output, outputDesc);
1455 mPreviousOutputs = mOutputs;
1456 ALOGV("%s returns new direct output %d", __func__, *output);
1457 mpClientInterface->onAudioPortListUpdate();
1458 return NO_ERROR;
1459}
1460
François Gaffie11d30102018-11-02 16:09:09 +01001461audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1462 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001463 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001464 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001465 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001466 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001467 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001468 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001469{
Andy Hungc88b0642018-04-27 15:42:35 -07001470 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001471
jiabine375d412019-02-26 12:54:53 -08001472 // Discard haptic channel mask when forcing muting haptic channels.
1473 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001474 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1475 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001476
Eric Laurente552edb2014-03-10 17:42:56 -07001477 // open a direct output if required by specified parameters
1478 //force direct flag if offload flag is set: offloading implies a direct output stream
1479 // and all common behaviors are driven by checking only the direct flag
1480 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001481 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1482 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001483 }
Nadav Bar766fb022018-01-07 12:18:03 +02001484 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1485 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001486 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001487
1488 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1489
Eric Laurente83b55d2014-11-14 10:06:21 -08001490 // only allow deep buffering for music stream type
1491 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001492 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001493 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001494 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001495 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1496 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001497 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001498 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001499 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001500 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001501 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001502 audio_is_linear_pcm(config->format) &&
1503 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001504 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001505 AUDIO_OUTPUT_FLAG_DIRECT);
1506 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001507 }
Eric Laurente552edb2014-03-10 17:42:56 -07001508
Carter Hsua3abb402021-10-26 11:11:20 +08001509 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1510 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1511 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1512 }
1513
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001514 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001515 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001516 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001517 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001518 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001519 }
1520
Eric Laurentc529cf62020-04-17 18:19:10 -07001521 audio_config_t directConfig = *config;
1522 directConfig.channel_mask = channelMask;
1523 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1524 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001525 return output;
1526 }
1527
Eric Laurent14cbfca2016-03-17 09:42:16 -07001528 // A request for HW A/V sync cannot fallback to a mixed output because time
1529 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001530 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001531 return AUDIO_IO_HANDLE_NONE;
1532 }
1533
Eric Laurente552edb2014-03-10 17:42:56 -07001534 // ignoring channel mask due to downmix capability in mixer
1535
1536 // open a non direct output
1537
1538 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001539 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001540 // get which output is suitable for the specified stream. The actual
1541 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001542 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001543
Eric Laurent8838a382014-09-08 16:44:28 -07001544 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001545 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001546 output = selectOutput(
1547 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001548 }
François Gaffie11d30102018-11-02 16:09:09 +01001549 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001550 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001551 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001552
Eric Laurente552edb2014-03-10 17:42:56 -07001553 return output;
1554}
1555
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001556sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001557 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1558 mAvailableInputDevices);
1559 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1560}
1561
1562DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1563 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1564 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001565}
1566
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001567const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001569 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1570 if (msdModule != 0) {
1571 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1572 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1573 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1574 const struct audio_port_config *source = &patch->mPatch.sources[j];
1575 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1576 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001577 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001578 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001579 }
1580 }
1581 }
1582 return msdPatches;
1583}
1584
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001585bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1586 ssize_t index = mAudioPatches.indexOfKey(handle);
1587 if (index < 0) {
1588 return false;
1589 }
1590 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1591 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1592 if (msdModule == nullptr) {
1593 return false;
1594 }
1595 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1596 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1597 return true;
1598 }
1599 index = getMsdOutputPatches().indexOfKey(handle);
1600 if (index < 0) {
1601 return false;
1602 }
1603 return true;
1604}
1605
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001606status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1607 const InputProfileCollection &inputProfiles,
1608 const OutputProfileCollection &outputProfiles,
1609 const sp<DeviceDescriptor> &sourceDevice,
1610 const sp<DeviceDescriptor> &sinkDevice,
1611 AudioProfileVector& sourceProfiles,
1612 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001613 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001614 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001615 return NO_INIT;
1616 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001617 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001618 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001619 return NO_INIT;
1620 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001621 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001622 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1623 inProfile->supportsDevice(sourceDevice)) {
1624 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001625 }
1626 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001627 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001628 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001629 outProfile->supportsDevice(sinkDevice)) {
1630 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001631 }
1632 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001633 return NO_ERROR;
1634}
1635
1636status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1637 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1638 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1639{
Dean Wheatley16809da2022-12-09 14:55:46 +11001640 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1641 static const std::vector<audio_format_t> formatsOrder = {{
1642 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1643 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1644 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1645 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1646 // preferred).
1647 std::vector<audio_channel_mask_t> masks = {{
1648 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1649 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1650 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1651 // insert index masks (higher counts most preferred) as preferred over position masks
1652 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1653 masks.insert(
1654 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1655 }
1656 return masks;
1657 }();
1658
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001659 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001660 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1661 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001662 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001663 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1664 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001665 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001666 }
1667 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1668 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1669 sinkConfig->format = bestSinkConfig.format;
1670 // For encoded streams force direct flag to prevent downstream mixing.
1671 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1672 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001673 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1674 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001675 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001676 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1677 // raw and IEC61937 framed streams.
1678 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1679 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1680 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001681 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1682 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001683 sourceConfig->channel_mask =
1684 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1685 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1686 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001687 sourceConfig->format = bestSinkConfig.format;
1688 // Copy input stream directly without any processing (e.g. resampling).
1689 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1690 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1691 if (hwAvSync) {
1692 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1693 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1694 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1695 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1696 }
1697 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1698 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1699 sinkConfig->config_mask |= config_mask;
1700 sourceConfig->config_mask |= config_mask;
1701 return NO_ERROR;
1702}
1703
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001704PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1705 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001706{
1707 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001708 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1709 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1710 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1711 if (deviceModule == nullptr) {
1712 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1713 return patchBuilder;
1714 }
1715 const InputProfileCollection inputProfiles = msdIsSource ?
1716 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1717 const OutputProfileCollection outputProfiles = msdIsSource ?
1718 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1719
1720 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1721 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1722 device : getMsdAudioOutDevices().itemAt(0);
1723 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1724
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001725 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1726 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001727 AudioProfileVector sourceProfiles;
1728 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001729 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1730 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001731 for (auto hwAvSync : { true, false }) {
1732 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1733 sourceProfiles, sinkProfiles) != NO_ERROR) {
1734 continue;
1735 }
1736 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1737 &sinkConfig) == NO_ERROR) {
1738 // Found a matching config. Re-create PatchBuilder with this config.
1739 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1740 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001741 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001742 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 " supporting PCM format conversion.", __func__);
1744 return patchBuilder;
1745}
1746
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001747status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001748 DeviceVector devices;
1749 if (outputDevices != nullptr && outputDevices->size() > 0) {
1750 devices.add(*outputDevices);
1751 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001752 // Use media strategy for unspecified output device. This should only
1753 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1754 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001755 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001756 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001757 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 }
Michael Chan6fb34492020-12-08 15:44:49 +11001759 std::vector<PatchBuilder> patchesToCreate;
1760 for (auto i = 0u; i < devices.size(); ++i) {
1761 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001762 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001763 }
1764 // Retain only the MSD patches associated with outputDevices request.
1765 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001766 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001767 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1768 auto retainedPatch = false;
1769 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1770 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1771 patchesToRemove.removeItemsAt(i);
1772 retainedPatch = true;
1773 break;
1774 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 }
Michael Chan6fb34492020-12-08 15:44:49 +11001776 if (retainedPatch) {
1777 it = patchesToCreate.erase(it);
1778 continue;
1779 }
1780 ++it;
1781 }
1782 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1783 return NO_ERROR;
1784 }
1785 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1786 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001787 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788 }
Michael Chan6fb34492020-12-08 15:44:49 +11001789 status_t status = NO_ERROR;
1790 for (const auto &p : patchesToCreate) {
1791 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1792 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1793 char message[256];
1794 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1795 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1796 currStatus == NO_ERROR ? "Success" : "Error",
1797 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1798 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1799 if (currStatus == NO_ERROR) {
1800 ALOGD("%s", message);
1801 } else {
1802 ALOGE("%s", message);
1803 if (status == NO_ERROR) {
1804 status = currStatus;
1805 }
1806 }
1807 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808 return status;
1809}
1810
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001811void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1812 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001813 for (size_t i = 0; i < msdPatches.size(); i++) {
1814 const auto& patch = msdPatches[i];
1815 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1816 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1817 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1818 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1819 releaseAudioPatch(patch->getHandle(), mUidCached);
1820 break;
1821 }
1822 }
1823 }
1824}
1825
Dorin Drimus94d94412022-02-02 09:05:02 +01001826bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1827 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1828 AudioPatchCollection msdPatches = getMsdOutputPatches();
1829 for (size_t i = 0; i < msdPatches.size(); i++) {
1830 const auto& patch = msdPatches[i];
1831 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1832 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1833 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1834 const auto& foundDevice = devicesToCheck.getDevice(
1835 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1836 if (foundDevice != nullptr) {
1837 devicesToCheck.remove(foundDevice);
1838 if (devicesToCheck.isEmpty()) {
1839 return true;
1840 }
1841 }
1842 }
1843 }
1844 }
1845 return false;
1846}
1847
Eric Laurente0720872014-03-11 09:30:41 -07001848audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001849 audio_output_flags_t flags,
1850 audio_format_t format,
1851 audio_channel_mask_t channelMask,
1852 uint32_t samplingRate,
1853 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001854{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001855 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1856 "%s called with format %#x", __func__, format);
1857
jiabinebb6af42020-06-09 17:31:17 -07001858 // Return the output that haptic-generating attached to when 1) session id is specified,
1859 // 2) haptic-generating effect exists for given session id and 3) the output that
1860 // haptic-generating effect attached to is in given outputs.
1861 if (sessionId != AUDIO_SESSION_NONE) {
1862 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1863 sessionId, FX_IID_HAPTICGENERATOR);
1864 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1865 return hapticGeneratingOutput;
1866 }
1867 }
1868
Eric Laurent16c66dd2019-05-01 17:54:10 -07001869 // Flags disqualifying an output: the match must happen before calling selectOutput()
1870 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1871 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1872
1873 // Flags expressing a functional request: must be honored in priority over
1874 // other criteria
1875 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1876 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001877 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1878 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 // Flags expressing a performance request: have lower priority than serving
1880 // requested sampling rate or channel mask
1881 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1882 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1883 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1884
1885 const audio_output_flags_t functionalFlags =
1886 (audio_output_flags_t)(flags & kFunctionalFlags);
1887 const audio_output_flags_t performanceFlags =
1888 (audio_output_flags_t)(flags & kPerformanceFlags);
1889
1890 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1891
Eric Laurente552edb2014-03-10 17:42:56 -07001892 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001893 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001894 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001895 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001896 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001897 // with tiebreak preferring the minimum number of extra functional flags
1898 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001899 // 3: the output supporting the exact channel mask
1900 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001901 // 5: the output with the highest sampling rate if the requested sample rate is
1902 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001903 // 6: the output with the highest number of requested performance flags
1904 // 7: the output with the bit depth the closest to the requested one
1905 // 8: the primary output
1906 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001907
Eric Laurent16c66dd2019-05-01 17:54:10 -07001908 // matching criteria values in priority order for best matching output so far
1909 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001910
Eric Laurent16c66dd2019-05-01 17:54:10 -07001911 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1912 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1913 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001914
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001915 for (audio_io_handle_t output : outputs) {
1916 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 // matching criteria values in priority order for current output
1918 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001919
Eric Laurent16c66dd2019-05-01 17:54:10 -07001920 if (outputDesc->isDuplicated()) {
1921 continue;
1922 }
1923 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1924 continue;
1925 }
Eric Laurent8838a382014-09-08 16:44:28 -07001926
Eric Laurent16c66dd2019-05-01 17:54:10 -07001927 // If haptic channel is specified, use the haptic output if present.
1928 // When using haptic output, same audio format and sample rate are required.
1929 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001930 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001931 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1932 continue;
1933 }
1934 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001935 && format == outputDesc->getFormat()
1936 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001937 currentMatchCriteria[0] = outputHapticChannelCount;
1938 }
1939
1940 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001941 const int matchingFunctionalFlags =
1942 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1943 const int totalFunctionalFlags =
1944 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1945 // Prefer matching functional flags, but subtract unnecessary functional flags.
1946 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001947
1948 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001949 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1950 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001951 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1952 channelCount <= outputChannelCount) {
1953 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001954 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1955 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001957 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001958 currentMatchCriteria[3] = outputChannelCount;
1959 }
1960
1961 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001962 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001963 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001964 }
1965
1966 // performance flags match
1967 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1968
1969 // format match
1970 if (format != AUDIO_FORMAT_INVALID) {
1971 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001972 PolicyAudioPort::kFormatDistanceMax -
1973 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001974 }
1975
1976 // primary output match
1977 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1978
1979 // compare match criteria by priority then value
1980 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1981 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1982 bestMatchCriteria = currentMatchCriteria;
1983 bestOutput = output;
1984
1985 std::stringstream result;
1986 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1987 std::ostream_iterator<int>(result, " "));
1988 ALOGV("%s new bestOutput %d criteria %s",
1989 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001990 }
1991 }
1992
Eric Laurent16c66dd2019-05-01 17:54:10 -07001993 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001994}
1995
Eric Laurent8fc147b2018-07-22 19:13:55 -07001996status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001997{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001998 ALOGV("%s portId %d", __FUNCTION__, portId);
1999
2000 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2001 if (outputDesc == 0) {
2002 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002003 return BAD_VALUE;
2004 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002005 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002006
Eric Laurent8fc147b2018-07-22 19:13:55 -07002007 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002008 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002009
Eric Laurent733ce942017-12-07 12:18:25 -08002010 status_t status = outputDesc->start();
2011 if (status != NO_ERROR) {
2012 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002013 }
2014
Eric Laurent97ac8712018-07-27 18:59:02 -07002015 uint32_t delayMs;
2016 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002017
2018 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002019 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002020 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002021 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002022 if (delayMs != 0) {
2023 usleep(delayMs * 1000);
2024 }
2025
2026 return status;
2027}
2028
Eric Laurent96d1dda2022-03-14 17:14:19 +01002029bool AudioPolicyManager::isLeUnicastActive() const {
2030 if (isInCall()) {
2031 return true;
2032 }
2033 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2034}
2035
2036bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2037 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2038 return false;
2039 }
2040 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2041 ALOGV("%s active %d", __func__, active);
2042 return active;
2043}
2044
Eric Laurent97ac8712018-07-27 18:59:02 -07002045status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2046 const sp<TrackClientDescriptor>& client,
2047 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002048{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002049 // cannot start playback of STREAM_TTS if any other output is being used
2050 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002051
2052 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002053 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002054 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002055 auto clientStrategy = client->strategy();
2056 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002057 if (stream == AUDIO_STREAM_TTS) {
2058 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002059 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002060 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002061 return INVALID_OPERATION;
2062 } else {
2063 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2064 }
2065 } else {
2066 // some playback other than beacon starts
2067 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2068 }
2069
Eric Laurent77305a62016-07-25 16:39:22 -07002070 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002071 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002072 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002073
François Gaffie11d30102018-11-02 16:09:09 +01002074 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002075 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002076 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002077 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002078 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002079 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002080 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002081 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002082 } else {
2083 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002084 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002085 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2086 AUDIO_FORMAT_DEFAULT);
2087 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2088 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002089 }
2090
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002091 // requiresMuteCheck is false when we can bypass mute strategy.
2092 // It covers a common case when there is no materially active audio
2093 // and muting would result in unnecessary delay and dropped audio.
2094 const uint32_t outputLatencyMs = outputDesc->latency();
2095 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002096 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002097
Eric Laurente552edb2014-03-10 17:42:56 -07002098 // increment usage count for this stream on the requested output:
2099 // NOTE that the usage count is the same for duplicated output and hardware output which is
2100 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002101 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002102
2103 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002104 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2105 client->isPreferredDeviceForExclusiveUse()) {
2106 // Preferred device may be exclusive, use only if no other active clients on this output
2107 devices = DeviceVector(
2108 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2109 } else {
2110 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2111 }
François Gaffie11d30102018-11-02 16:09:09 +01002112 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002113 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002114 }
2115 }
Eric Laurente552edb2014-03-10 17:42:56 -07002116
François Gaffiec005e562018-11-06 15:04:49 +01002117 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002118 selectOutputForMusicEffects();
2119 }
2120
François Gaffie1c878552018-11-22 16:53:21 +01002121 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002122 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002123 if (devices.isEmpty()) {
2124 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002125 }
François Gaffiec005e562018-11-06 15:04:49 +01002126 bool shouldWait =
2127 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2128 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2129 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002130 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002131 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002132 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002133 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002134 // An output has a shared device if
2135 // - managed by the same hw module
2136 // - supports the currently selected device
2137 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002138 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002139
Eric Laurent77305a62016-07-25 16:39:22 -07002140 // force a device change if any other output is:
2141 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002142 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002143 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002144 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002145 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002146 // change the device currently selected by the other output.
2147 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002148 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002149 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002150 force = true;
2151 }
2152 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002153 // a notification so that audio focus effect can propagate, or that a mute/unmute
2154 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002155 const uint32_t latencyMs = desc->latency();
2156 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2157
2158 if (shouldWait && isActive && (waitMs < latencyMs)) {
2159 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002160 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002161
2162 // Require mute check if another output is on a shared device
2163 // and currently active to have proper drain and avoid pops.
2164 // Note restoring AudioTracks onto this output needs to invoke
2165 // a volume ramp if there is no mute.
2166 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002167 }
2168 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002169
2170 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002171 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002172
Eric Laurente552edb2014-03-10 17:42:56 -07002173 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002174 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002175 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002176 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002177 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002178 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002179 outputDesc->useHwGain() /*force*/)) {
2180 // request AudioService to reinitialize the volume curves asynchronously
2181 ALOGE("checkAndSetVolume failed, requesting volume range init");
2182 mpClientInterface->onVolumeRangeInitRequest();
2183 };
Eric Laurente552edb2014-03-10 17:42:56 -07002184
2185 // update the outputs if starting an output with a stream that can affect notification
2186 // routing
2187 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002188
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002189 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002190 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002191 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2192 }
Eric Laurentdc462862016-07-19 12:29:53 -07002193
2194 if (waitMs > muteWaitMs) {
2195 *delayMs = waitMs - muteWaitMs;
2196 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002197
2198 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2199 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2200 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2201 // change occurs after the MixerThread starts and causes a stream volume
2202 // glitch.
2203 //
2204 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002205 }
Eric Laurentdc462862016-07-19 12:29:53 -07002206
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002207 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002208 mEngine->getForceUse(
2209 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002210 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002211 }
2212
Eric Laurent97ac8712018-07-27 18:59:02 -07002213 // Automatically enable the remote submix input when output is started on a re routing mix
2214 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002215 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2216 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002217 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2218 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2219 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002220 "remote-submix",
2221 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002222 }
2223
Eric Laurent96d1dda2022-03-14 17:14:19 +01002224 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2225
Eric Laurente552edb2014-03-10 17:42:56 -07002226 return NO_ERROR;
2227}
2228
Eric Laurent96d1dda2022-03-14 17:14:19 +01002229void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2230 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2231 bool isUnicastActive = isLeUnicastActive();
2232
2233 if (wasUnicastActive != isUnicastActive) {
2234 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2235 for (size_t i = 0; i < mOutputs.size(); i++) {
2236 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2237 if (desc != ignoredOutput && desc->isActive()
2238 && ((isUnicastActive &&
2239 !desc->devices().
2240 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2241 || (wasUnicastActive &&
2242 !desc->devices().getDevicesFromTypes(
2243 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2244 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2245 bool force = desc->devices() != newDevices;
2246 setOutputDevices(desc, newDevices, force, delayMs);
2247 // re-apply device specific volume if not done by setOutputDevice()
2248 if (!force) {
2249 applyStreamVolumes(desc, newDevices.types(), delayMs);
2250 }
2251 }
2252 }
2253 }
2254}
2255
Eric Laurent8fc147b2018-07-22 19:13:55 -07002256status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002257{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002258 ALOGV("%s portId %d", __FUNCTION__, portId);
2259
2260 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2261 if (outputDesc == 0) {
2262 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002263 return BAD_VALUE;
2264 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002265 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002266
Eric Laurent97ac8712018-07-27 18:59:02 -07002267 ALOGV("stopOutput() output %d, stream %d, session %d",
2268 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002269
Eric Laurent97ac8712018-07-27 18:59:02 -07002270 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002271
Eric Laurent733ce942017-12-07 12:18:25 -08002272 if (status == NO_ERROR ) {
2273 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002274 }
2275 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002276}
2277
Eric Laurent97ac8712018-07-27 18:59:02 -07002278status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2279 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002280{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002281 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002282 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002283 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002284 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002285
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002286 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2287
François Gaffie1c878552018-11-22 16:53:21 +01002288 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2289 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002290 // Automatically disable the remote submix input when output is stopped on a
2291 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002292 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002293 if (isSingleDeviceType(
2294 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002295 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002296 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002297 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2298 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002299 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002300 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002301 }
2302 }
2303 bool forceDeviceUpdate = false;
2304 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002305 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002306 forceDeviceUpdate = true;
2307 }
2308
Eric Laurente552edb2014-03-10 17:42:56 -07002309 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002310 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002311
Eric Laurente552edb2014-03-10 17:42:56 -07002312 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002313 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002314 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002315 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002316
2317 // If the routing does not change, if an output is routed on a device using HwGain
2318 // (aka setAudioPortConfig) and there are still active clients following different
2319 // volume group(s), force reapply volume
2320 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2321 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2322
Eric Laurente552edb2014-03-10 17:42:56 -07002323 // delay the device switch by twice the latency because stopOutput() is executed when
2324 // the track stop() command is received and at that time the audio track buffer can
2325 // still contain data that needs to be drained. The latency only covers the audio HAL
2326 // and kernel buffers. Also the latency does not always include additional delay in the
2327 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002328 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2329 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002330
2331 // force restoring the device selection on other active outputs if it differs from the
2332 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002333 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002334 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002335 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002336 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002337 desc->isActive() &&
2338 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002339 (newDevices != desc->devices())) {
2340 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2341 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002342
François Gaffie11d30102018-11-02 16:09:09 +01002343 setOutputDevices(desc, newDevices2, force, delayMs);
2344
Eric Laurent57de36c2016-09-28 16:59:11 -07002345 // re-apply device specific volume if not done by setOutputDevice()
2346 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002347 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002348 }
Eric Laurente552edb2014-03-10 17:42:56 -07002349 }
2350 }
2351 // update the outputs if stopping one with a stream that can affect notification routing
2352 handleNotificationRoutingForStream(stream);
2353 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002354
2355 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2356 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002357 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002358 }
2359
François Gaffiec005e562018-11-06 15:04:49 +01002360 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002361 selectOutputForMusicEffects();
2362 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002363
2364 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2365
Eric Laurente552edb2014-03-10 17:42:56 -07002366 return NO_ERROR;
2367 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002368 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002369 return INVALID_OPERATION;
2370 }
2371}
2372
jiabinbce0c1d2020-10-05 11:20:18 -07002373bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002374{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002375 ALOGV("%s portId %d", __FUNCTION__, portId);
2376
2377 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2378 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002379 // If an output descriptor is closed due to a device routing change,
2380 // then there are race conditions with releaseOutput from tracks
2381 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2382 // destroyed shortly thereafter.
2383 //
2384 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002385 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002386 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002387 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002388
2389 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002390
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302391 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2392 if (outputDesc->isClientActive(client)) {
2393 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2394 stopOutput(portId);
2395 }
2396
Eric Laurent8fc147b2018-07-22 19:13:55 -07002397 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2398 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002399 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002400 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002401 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002402 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002403 if (--outputDesc->mDirectOpenCount == 0) {
2404 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002405 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002406 }
2407 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302408
Andy Hung39efb7a2018-09-26 15:39:28 -07002409 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002410 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2411 // The output is pending reopened to query dynamic profiles and
2412 // there is no active clients
2413 closeOutput(outputDesc->mIoHandle);
2414 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2415 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2416 if (newOutputDesc == nullptr) {
2417 ALOGE("%s failed to open output", __func__);
2418 }
2419 return true;
2420 }
2421 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002422}
2423
Eric Laurentcaf7f482014-11-25 17:50:47 -08002424status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2425 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002426 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002427 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002428 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002429 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002430 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002431 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002432 input_type_t *inputType,
2433 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002434{
François Gaffiec005e562018-11-06 15:04:49 +01002435 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002436 "flags %#x attributes=%s requested device ID %d",
2437 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2438 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002439
Eric Laurentad2e7b92017-09-14 20:06:42 -07002440 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002441 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002442 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002443 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002444 sp<AudioInputDescriptor> inputDesc;
2445 sp<RecordClientDescriptor> clientDesc;
2446 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002447 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002448 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002449
2450 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2451 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2452 return INVALID_OPERATION;
2453 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002454
Francois Gaffie716e1432019-01-14 16:58:59 +01002455 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2456 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002457 }
2458
Paul McLean466dc8e2015-04-17 13:15:36 -06002459 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002460 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002461 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002462
Eric Laurentad2e7b92017-09-14 20:06:42 -07002463 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2464 // possible
2465 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2466 *input != AUDIO_IO_HANDLE_NONE) {
2467 ssize_t index = mInputs.indexOfKey(*input);
2468 if (index < 0) {
2469 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2470 status = BAD_VALUE;
2471 goto error;
2472 }
2473 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002474 RecordClientVector clients = inputDesc->getClientsForSession(session);
2475 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002476 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2477 status = BAD_VALUE;
2478 goto error;
2479 }
2480 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2481 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002482 // corresponds to a new client and is only permitted from the same UID.
2483 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002484 if (clients.size() > 1) {
2485 for (const auto& client : clients) {
2486 // The client map is ordered by key values (portId) and portIds are allocated
2487 // incrementaly. So the first client in this list is the one opened by audio flinger
2488 // when the mmap stream is created and should be ignored as it does not correspond
2489 // to an actual client
2490 if (client == *clients.cbegin()) {
2491 continue;
2492 }
2493 if (uid != client->uid() && !client->isSilenced()) {
2494 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2495 uid, client->portId(), client->uid());
2496 status = INVALID_OPERATION;
2497 goto error;
2498 }
Eric Laurent331679c2018-04-16 17:03:16 -07002499 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002500 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002501 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002502 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002503
Eric Laurentfecbceb2021-02-09 14:46:43 +01002504 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002505 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002506 }
2507
2508 *input = AUDIO_IO_HANDLE_NONE;
2509 *inputType = API_INPUT_INVALID;
2510
Francois Gaffie716e1432019-01-14 16:58:59 +01002511 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2512 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2513 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002514 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002515 ALOGW("%s could not find input mix for attr %s",
2516 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002517 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002518 }
jiabinc1de2df2019-05-07 14:26:40 -07002519 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2520 String8(attr->tags + strlen("addr=")),
2521 AUDIO_FORMAT_DEFAULT);
2522 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002523 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002524 __func__, attributes.source, attributes.tags);
2525 status = BAD_VALUE;
2526 goto error;
2527 }
2528
Kevin Rocard25f9b052019-02-27 15:08:54 -08002529 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2530 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2531 } else {
2532 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2533 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002534 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002535 if (explicitRoutingDevice != nullptr) {
2536 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002537 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002538 // Prevent from storing invalid requested device id in clients
2539 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002540 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002541 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2542 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 }
François Gaffie11d30102018-11-02 16:09:09 +01002544 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002545 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002546 status = BAD_VALUE;
2547 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002548 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002549 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2550 *inputType = API_INPUT_MIX_CAPTURE;
2551 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002552 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2553 // there is an external policy, but this input is attached to a mix of recorders,
2554 // meaning it receives audio injected into the framework, so the recorder doesn't
2555 // know about it and is therefore considered "legacy"
2556 *inputType = API_INPUT_LEGACY;
2557 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002558 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002559 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002560 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002561 } else {
2562 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002563 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002564
Eric Laurent599c7582015-12-07 18:05:55 -08002565 }
2566
François Gaffiec005e562018-11-06 15:04:49 +01002567 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002568 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002569 status = INVALID_OPERATION;
2570 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002571 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002572
Eric Laurent8f42ea12018-08-08 09:08:25 -07002573exit:
2574
François Gaffiec005e562018-11-06 15:04:49 +01002575 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2576 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002577
Francois Gaffie716e1432019-01-14 16:58:59 +01002578 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002579 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002580 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002581
Mikhail Naganov2996f672019-04-18 12:29:59 -07002582 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002583 requestedDeviceId, attributes.source, flags,
2584 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002585 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002586 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002587
2588 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2589 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002590
Eric Laurent599c7582015-12-07 18:05:55 -08002591 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002592
2593error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002594 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002595}
2596
2597
François Gaffie11d30102018-11-02 16:09:09 +01002598audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002599 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002600 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002601 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002602 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002603 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002604{
2605 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002606 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002607 bool isSoundTrigger = false;
2608
François Gaffiec005e562018-11-06 15:04:49 +01002609 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002610 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2611 if (index >= 0) {
2612 input = mSoundTriggerSessions.valueFor(session);
2613 isSoundTrigger = true;
2614 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2615 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2616 } else {
2617 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002618 }
François Gaffiec005e562018-11-06 15:04:49 +01002619 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002620 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002621 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002622 }
2623
Carter Hsua3abb402021-10-26 11:11:20 +08002624 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2625 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2626 }
2627
Andy Hungf129b032015-04-07 13:45:50 -07002628 // find a compatible input profile (not necessarily identical in parameters)
2629 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002630 // sampling rate and flags may be updated by getInputProfile
2631 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2632 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002633 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002634 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002635 audio_input_flags_t profileFlags = flags;
2636 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002637 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002638 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002639 profileFlags);
2640 if (profile != 0) {
2641 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002642 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2643 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002644 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002645 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2646 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002647 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002648 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002649 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002650 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002651 }
Eric Laurente552edb2014-03-10 17:42:56 -07002652 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002653 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002654 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002655 if (samplingRate == 0) {
2656 samplingRate = profileSamplingRate;
2657 }
Eric Laurente552edb2014-03-10 17:42:56 -07002658
Eric Laurent322b4d22015-04-03 15:57:54 -07002659 if (profile->getModuleHandle() == 0) {
2660 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002661 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002662 }
2663
Eric Laurentec376dc2021-04-08 20:41:22 +02002664 // Reuse an already opened input if a client with the same session ID already exists
2665 // on that input
2666 for (size_t i = 0; i < mInputs.size(); i++) {
2667 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2668 if (desc->mProfile != profile) {
2669 continue;
2670 }
2671 RecordClientVector clients = desc->clientsList();
2672 for (const auto &client : clients) {
2673 if (session == client->session()) {
2674 return desc->mIoHandle;
2675 }
2676 }
2677 }
2678
Eric Laurent3974e3b2017-12-07 17:58:43 -08002679 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002680 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002681 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002682 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002683 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002684 continue;
2685 }
2686 // if sound trigger, reuse input if used by other sound trigger on same session
2687 // else
2688 // reuse input if active client app is not in IDLE state
2689 //
2690 RecordClientVector clients = desc->clientsList();
2691 bool doClose = false;
2692 for (const auto& client : clients) {
2693 if (isSoundTrigger != client->isSoundTrigger()) {
2694 continue;
2695 }
2696 if (client->isSoundTrigger()) {
2697 if (session == client->session()) {
2698 return desc->mIoHandle;
2699 }
2700 continue;
2701 }
2702 if (client->active() && client->appState() != APP_STATE_IDLE) {
2703 return desc->mIoHandle;
2704 }
2705 doClose = true;
2706 }
2707 if (doClose) {
2708 closeInput(desc->mIoHandle);
2709 } else {
2710 i++;
2711 }
2712 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002713 }
2714
Eric Laurentfe231122017-11-17 17:48:06 -08002715 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002716
Eric Laurentfe231122017-11-17 17:48:06 -08002717 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2718 lConfig.sample_rate = profileSamplingRate;
2719 lConfig.channel_mask = profileChannelMask;
2720 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002721
François Gaffie11d30102018-11-02 16:09:09 +01002722 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002723
2724 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002725 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002726 (profileSamplingRate != lConfig.sample_rate) ||
2727 !audio_formats_match(profileFormat, lConfig.format) ||
2728 (profileChannelMask != lConfig.channel_mask)) {
2729 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002730 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002731 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002732 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002733 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002734 }
Eric Laurent599c7582015-12-07 18:05:55 -08002735 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002736 }
2737
Eric Laurentc722f302014-12-10 11:21:49 -08002738 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002739
Eric Laurent599c7582015-12-07 18:05:55 -08002740 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002741 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002742
Eric Laurent599c7582015-12-07 18:05:55 -08002743 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002744}
2745
Eric Laurent4eb58f12018-12-07 16:41:02 -08002746status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002747{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002748 ALOGV("%s portId %d", __FUNCTION__, portId);
2749
2750 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2751 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002752 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002753 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002754 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002755 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002756 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002757 if (client->active()) {
2758 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2759 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002760 }
2761
Eric Laurent8f42ea12018-08-08 09:08:25 -07002762 audio_session_t session = client->session();
2763
Eric Laurent4eb58f12018-12-07 16:41:02 -08002764 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002765
Eric Laurent4eb58f12018-12-07 16:41:02 -08002766 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002767
Eric Laurent4eb58f12018-12-07 16:41:02 -08002768 status_t status = inputDesc->start();
2769 if (status != NO_ERROR) {
2770 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002771 }
Eric Laurente552edb2014-03-10 17:42:56 -07002772
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002773 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002774 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002776
Eric Laurent8f42ea12018-08-08 09:08:25 -07002777 // indicate active capture to sound trigger service if starting capture from a mic on
2778 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002779 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002780 if (device != nullptr) {
2781 status = setInputDevice(input, device, true /* force */);
2782 } else {
2783 ALOGW("%s no new input device can be found for descriptor %d",
2784 __FUNCTION__, inputDesc->getId());
2785 status = BAD_VALUE;
2786 }
Eric Laurente552edb2014-03-10 17:42:56 -07002787
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002788 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002789 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002790 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002791 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002792 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2793 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002794 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002795 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002796
François Gaffie11d30102018-11-02 16:09:09 +01002797 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2798 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002799 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002800 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002801 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002802
Eric Laurent8f42ea12018-08-08 09:08:25 -07002803 // automatically enable the remote submix output when input is started if not
2804 // used by a policy mix of type MIX_TYPE_RECORDERS
2805 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002806 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002808 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002809 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002810 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2811 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002812 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002813 if (address != "") {
2814 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2815 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002816 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002817 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002818 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002819 } else if (status != NO_ERROR) {
2820 // Restore client activity state.
2821 inputDesc->setClientActive(client, false);
2822 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002823 }
2824
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002825 ALOGV("%s input %d source = %d status = %d exit",
2826 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002827
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002828 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002829}
2830
Eric Laurent8fc147b2018-07-22 19:13:55 -07002831status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002832{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002833 ALOGV("%s portId %d", __FUNCTION__, portId);
2834
2835 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2836 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002838 return BAD_VALUE;
2839 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002840 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002841 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 if (!client->active()) {
2843 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002844 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002845 }
Carter Hsue6139d52021-07-08 10:30:20 +08002846 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002847 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002848
Eric Laurent8f42ea12018-08-08 09:08:25 -07002849 inputDesc->stop();
2850 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002851 auto current_source = inputDesc->source();
2852 setInputDevice(input, getNewInputDevice(inputDesc),
2853 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002854 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002855 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002856 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002857 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002858 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2859 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002861 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002862
2863 // automatically disable the remote submix output when input is stopped if not
2864 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002865 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002866 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002867 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002868 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002869 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2870 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002871 }
2872 if (address != "") {
2873 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2874 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002875 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002876 }
2877 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002878 resetInputDevice(input);
2879
2880 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2881 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002882 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2883 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002885 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002886 }
2887 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002888 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002889 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002890}
2891
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002893{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 ALOGV("%s portId %d", __FUNCTION__, portId);
2895
2896 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2897 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002898 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002899 return;
2900 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002901 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002902 audio_io_handle_t input = inputDesc->mIoHandle;
2903
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002905
Andy Hung39efb7a2018-09-26 15:39:28 -07002906 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002907
Andy Hung39efb7a2018-09-26 15:39:28 -07002908 if (inputDesc->getClientCount() > 0) {
2909 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002910 return;
2911 }
2912
Eric Laurent05b90f82014-08-27 15:32:29 -07002913 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002914 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002915 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002916}
2917
Eric Laurent8f42ea12018-08-08 09:08:25 -07002918void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002919{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002920 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002921
2922 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002923 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002924 }
2925}
2926
Eric Laurent8f42ea12018-08-08 09:08:25 -07002927void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2928{
2929 stopInput(portId);
2930 releaseInput(portId);
2931}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002932
Eric Laurent0dd51852019-04-19 18:18:58 -07002933void AudioPolicyManager::checkCloseInputs() {
2934 // After connecting or disconnecting an input device, close input if:
2935 // - it has no client (was just opened to check profile) OR
2936 // - none of its supported devices are connected anymore OR
2937 // - one of its clients cannot be routed to one of its supported
2938 // devices anymore. Otherwise update device selection
2939 std::vector<audio_io_handle_t> inputsToClose;
2940 for (size_t i = 0; i < mInputs.size(); i++) {
2941 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2942 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002943 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002944 inputsToClose.push_back(mInputs.keyAt(i));
2945 } else {
2946 bool close = false;
2947 for (const auto& client : input->clientsList()) {
2948 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002949 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002950 if (!input->supportedDevices().contains(device)) {
2951 close = true;
2952 break;
2953 }
2954 }
2955 if (close) {
2956 inputsToClose.push_back(mInputs.keyAt(i));
2957 } else {
2958 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2959 }
2960 }
2961 }
2962
2963 for (const audio_io_handle_t handle : inputsToClose) {
2964 ALOGV("%s closing input %d", __func__, handle);
2965 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002966 }
Eric Laurentd4692962014-05-05 18:13:44 -07002967}
2968
François Gaffie251c7f02018-11-07 10:41:08 +01002969void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002970{
2971 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002972 if (indexMin < 0 || indexMax < 0) {
2973 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2974 return;
2975 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002976 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002977
2978 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002979 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2980 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002981 continue;
2982 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002983 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002984 }
Eric Laurente552edb2014-03-10 17:42:56 -07002985}
2986
Eric Laurente0720872014-03-11 09:30:41 -07002987status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002988 int index,
2989 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002990{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002991 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002992 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2993 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2994 return NO_ERROR;
2995 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002996 ALOGV("%s: stream %s attributes=%s", __func__,
2997 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002998 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002999}
3000
Eric Laurente0720872014-03-11 09:30:41 -07003001status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003002 int *index,
3003 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003004{
François Gaffiec005e562018-11-06 15:04:49 +01003005 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3006 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003007 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003008 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003009 deviceTypes = mEngine->getOutputDevicesForStream(
3010 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003011 }
jiabin9a3361e2019-10-01 09:38:30 -07003012 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003013}
3014
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003015status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003016 int index,
3017 audio_devices_t device)
3018{
3019 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003020 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3021 if (group == VOLUME_GROUP_NONE) {
3022 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003023 return BAD_VALUE;
3024 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003025 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003026 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003027 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003028 VolumeSource vs = toVolumeSource(group);
3029 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3030
3031 status = setVolumeCurveIndex(index, device, curves);
3032 if (status != NO_ERROR) {
3033 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3034 return status;
3035 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003036
jiabin9a3361e2019-10-01 09:38:30 -07003037 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003038 auto curCurvAttrs = curves.getAttributes();
3039 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3040 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003041 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003042 } else if (!curves.getStreamTypes().empty()) {
3043 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003044 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003045 } else {
3046 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3047 return BAD_VALUE;
3048 }
jiabin9a3361e2019-10-01 09:38:30 -07003049 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3050 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003051
François Gaffiecfe17322018-11-07 13:41:29 +01003052 // update volume on all outputs and streams matching the following:
3053 // - The requested stream (or a stream matching for volume control) is active on the output
3054 // - The device (or devices) selected by the engine for this stream includes
3055 // the requested device
3056 // - For non default requested device, currently selected device on the output is either the
3057 // requested device or one of the devices selected by the engine for this stream
3058 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3059 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003060 for (size_t i = 0; i < mOutputs.size(); i++) {
3061 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003062 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003063
jiabin9a3361e2019-10-01 09:38:30 -07003064 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3065 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003066 }
François Gaffieed91f582020-01-31 10:35:37 +01003067 if (!(desc->isActive(vs) || isInCall())) {
3068 continue;
3069 }
3070 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3071 curDevices.find(device) == curDevices.end()) {
3072 continue;
3073 }
3074 bool applyVolume = false;
3075 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3076 curSrcDevices.insert(device);
3077 applyVolume = (curSrcDevices.find(
3078 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3079 } else {
3080 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3081 }
3082 if (!applyVolume) {
3083 continue; // next output
3084 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003085 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3086 // If a higher priority strategy is active, and the output is routed to a device with a
3087 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003088 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003089 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003090 // If the volume source is active with higher priority source, ensure at least Sw Muted
3091 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003092 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3093 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3094 false /*preferredDevice*/);
3095 if (activeClients.empty()) {
3096 continue;
3097 }
3098 bool isPreempted = false;
3099 bool isHigherPriority = productStrategy < strategy;
3100 for (const auto &client : activeClients) {
3101 if (isHigherPriority && (client->volumeSource() != vs)) {
3102 ALOGV("%s: Strategy=%d (\nrequester:\n"
3103 " group %d, volumeGroup=%d attributes=%s)\n"
3104 " higher priority source active:\n"
3105 " volumeGroup=%d attributes=%s) \n"
3106 " on output %zu, bailing out", __func__, productStrategy,
3107 group, group, toString(attributes).c_str(),
3108 client->volumeSource(), toString(client->attributes()).c_str(), i);
3109 applyVolume = false;
3110 isPreempted = true;
3111 break;
3112 }
3113 // However, continue for loop to ensure no higher prio clients running on output
3114 if (client->volumeSource() == vs) {
3115 applyVolume = true;
3116 }
3117 }
3118 if (isPreempted || applyVolume) {
3119 break;
3120 }
3121 }
3122 if (!applyVolume) {
3123 continue; // next output
3124 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003125 }
François Gaffieed91f582020-01-31 10:35:37 +01003126 //FIXME: workaround for truncated touch sounds
3127 // delayed volume change for system stream to be removed when the problem is
3128 // handled by system UI
3129 status_t volStatus = checkAndSetVolume(
3130 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003131 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003132 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3133 if (volStatus != NO_ERROR) {
3134 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135 }
3136 }
François Gaffiecfe17322018-11-07 13:41:29 +01003137 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3138 return status;
3139}
3140
François Gaffieaaac0fd2018-11-22 17:56:39 +01003141status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003142 audio_devices_t device,
3143 IVolumeCurves &volumeCurves)
3144{
3145 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3146 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003147 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3148 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003149 (index > volumeCurves.getVolumeIndexMax())) {
3150 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3151 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3152 return BAD_VALUE;
3153 }
3154 if (!audio_is_output_device(device)) {
3155 return BAD_VALUE;
3156 }
3157
3158 // Force max volume if stream cannot be muted
3159 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3160
François Gaffieaaac0fd2018-11-22 17:56:39 +01003161 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003162 volumeCurves.addCurrentVolumeIndex(device, index);
3163 return NO_ERROR;
3164}
3165
3166status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3167 int &index,
3168 audio_devices_t device)
3169{
3170 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3171 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003172 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003173 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003174 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003175 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003176 }
jiabin9a3361e2019-10-01 09:38:30 -07003177 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003178}
3179
3180status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3181 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003182 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003183{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003184 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003185 return BAD_VALUE;
3186 }
jiabin9a3361e2019-10-01 09:38:30 -07003187 index = curves.getVolumeIndex(deviceTypes);
3188 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003189 return NO_ERROR;
3190}
3191
3192status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3193 int &index)
3194{
3195 index = getVolumeCurves(attr).getVolumeIndexMin();
3196 return NO_ERROR;
3197}
3198
3199status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3200 int &index)
3201{
3202 index = getVolumeCurves(attr).getVolumeIndexMax();
3203 return NO_ERROR;
3204}
3205
Eric Laurent36829f92017-04-07 19:04:42 -07003206audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003207{
3208 // select one output among several suitable for global effects.
3209 // The priority is as follows:
3210 // 1: An offloaded output. If the effect ends up not being offloadable,
3211 // AudioFlinger will invalidate the track and the offloaded output
3212 // will be closed causing the effect to be moved to a PCM output.
3213 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003214 // 3: The primary output
3215 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003216
François Gaffiec005e562018-11-06 15:04:49 +01003217 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3218 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003219 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003220
Eric Laurent36829f92017-04-07 19:04:42 -07003221 if (outputs.size() == 0) {
3222 return AUDIO_IO_HANDLE_NONE;
3223 }
Eric Laurente552edb2014-03-10 17:42:56 -07003224
Eric Laurent36829f92017-04-07 19:04:42 -07003225 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3226 bool activeOnly = true;
3227
3228 while (output == AUDIO_IO_HANDLE_NONE) {
3229 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3230 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3231 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3232
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003233 for (audio_io_handle_t output : outputs) {
3234 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003235 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003236 continue;
3237 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003238 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3239 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003240 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003241 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003242 }
3243 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003244 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003245 }
3246 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003247 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003248 }
3249 }
3250 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3251 output = outputOffloaded;
3252 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3253 output = outputDeepBuffer;
3254 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3255 output = outputPrimary;
3256 } else {
3257 output = outputs[0];
3258 }
3259 activeOnly = false;
3260 }
3261
3262 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003263 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003264 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3265 mMusicEffectOutput = output;
3266 }
3267
3268 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003269 return output;
3270}
3271
Eric Laurent36829f92017-04-07 19:04:42 -07003272audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3273{
3274 return selectOutputForMusicEffects();
3275}
3276
Eric Laurente0720872014-03-11 09:30:41 -07003277status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003278 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003279 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003280 int session,
3281 int id)
3282{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003283 if (session != AUDIO_SESSION_DEVICE) {
3284 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003285 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003286 index = mInputs.indexOfKey(io);
3287 if (index < 0) {
3288 ALOGW("registerEffect() unknown io %d", io);
3289 return INVALID_OPERATION;
3290 }
Eric Laurente552edb2014-03-10 17:42:56 -07003291 }
3292 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003293 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3294 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3295 || strategy == PRODUCT_STRATEGY_NONE));
3296 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003297}
3298
Eric Laurentc241b0d2018-11-28 09:08:49 -08003299status_t AudioPolicyManager::unregisterEffect(int id)
3300{
3301 if (mEffects.getEffect(id) == nullptr) {
3302 return INVALID_OPERATION;
3303 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003304 if (mEffects.isEffectEnabled(id)) {
3305 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3306 setEffectEnabled(id, false);
3307 }
3308 return mEffects.unregisterEffect(id);
3309}
3310
3311status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3312{
3313 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3314 if (effect == nullptr) {
3315 return INVALID_OPERATION;
3316 }
3317
3318 status_t status = mEffects.setEffectEnabled(id, enabled);
3319 if (status == NO_ERROR) {
3320 mInputs.trackEffectEnabled(effect, enabled);
3321 }
3322 return status;
3323}
3324
Eric Laurent6c796322019-04-09 14:13:17 -07003325
3326status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3327{
3328 mEffects.moveEffects(ids, io);
3329 return NO_ERROR;
3330}
3331
Eric Laurentc75307b2015-03-17 15:29:32 -07003332bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3333{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003334 auto vs = toVolumeSource(stream, false);
3335 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003336}
3337
3338bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3339{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003340 auto vs = toVolumeSource(stream, false);
3341 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003342}
3343
Eric Laurente0720872014-03-11 09:30:41 -07003344bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003345{
3346 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003347 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003348 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003349 return true;
3350 }
3351 }
3352 return false;
3353}
3354
Eric Laurent275e8e92014-11-30 15:14:47 -08003355// Register a list of custom mixes with their attributes and format.
3356// When a mix is registered, corresponding input and output profiles are
3357// added to the remote submix hw module. The profile contains only the
3358// parameters (sampling rate, format...) specified by the mix.
3359// The corresponding input remote submix device is also connected.
3360//
3361// When a remote submix device is connected, the address is checked to select the
3362// appropriate profile and the corresponding input or output stream is opened.
3363//
3364// When capture starts, getInputForAttr() will:
3365// - 1 look for a mix matching the address passed in attribtutes tags if any
3366// - 2 if none found, getDeviceForInputSource() will:
3367// - 2.1 look for a mix matching the attributes source
3368// - 2.2 if none found, default to device selection by policy rules
3369// At this time, the corresponding output remote submix device is also connected
3370// and active playback use cases can be transferred to this mix if needed when reconnecting
3371// after AudioTracks are invalidated
3372//
3373// When playback starts, getOutputForAttr() will:
3374// - 1 look for a mix matching the address passed in attribtutes tags if any
3375// - 2 if none found, look for a mix matching the attributes usage
3376// - 3 if none found, default to device and output selection by policy rules.
3377
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003378status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003379{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3381 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003382 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003383 sp<HwModule> rSubmixModule;
3384 // examine each mix's route type
3385 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003386 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003387 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3388 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3389 ALOGE("Unsupported Policy Mix %zu of %zu: "
3390 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3391 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003392 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003393 break;
3394 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003395 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3396 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003397 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003398 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3399 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003400 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003401 rSubmixModule = mHwModules.getModuleFromName(
3402 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3403 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003404 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003405 i);
3406 res = INVALID_OPERATION;
3407 break;
3408 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003409 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003410
Eric Laurent97ac8712018-07-27 18:59:02 -07003411 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003412 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003413 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003414 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003415 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3416 } else {
3417 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3418 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003419 }
François Gaffie036e1e92015-03-19 10:16:24 +01003420
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003421 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003422 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003423 res = INVALID_OPERATION;
3424 break;
3425 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003426 audio_config_t outputConfig = mix.mFormat;
3427 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003428 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3429 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003430 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3431 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003432 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003433 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003434 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003435 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003436
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003437 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003438 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3439 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3440 ALOGE("Failed to set remote submix device available, type %u, address %s",
3441 mix.mDeviceType, address.string());
3442 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003443 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003444 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3445 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003446 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003447 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003448 i, mixes.size(), type, address.string());
3449
3450 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3451 mix.mDeviceType, mix.mDeviceAddress,
3452 String8(), AUDIO_FORMAT_DEFAULT);
3453 if (device == nullptr) {
3454 res = INVALID_OPERATION;
3455 break;
3456 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003457
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003458 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003459 // First try to find an already opened output supporting the device
3460 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003461 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003462
Eric Laurentc529cf62020-04-17 18:19:10 -07003463 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003464 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003465 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3466 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003468 } else {
3469 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003470 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003471 }
3472 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003473 // If no output found, try to find a direct output profile supporting the device
3474 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3475 sp<HwModule> module = mHwModules[i];
3476 for (size_t j = 0;
3477 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3478 j++) {
3479 sp<IOProfile> profile = module->getOutputProfiles()[j];
3480 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3481 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3482 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3483 address.string());
3484 res = INVALID_OPERATION;
3485 } else {
3486 foundOutput = true;
3487 }
3488 }
3489 }
3490 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003491 if (res != NO_ERROR) {
3492 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003493 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003494 res = INVALID_OPERATION;
3495 break;
3496 } else if (!foundOutput) {
3497 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003498 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003499 res = INVALID_OPERATION;
3500 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003501 } else {
3502 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003503 }
Eric Laurentc722f302014-12-10 11:21:49 -08003504 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003505 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003506 if (res != NO_ERROR) {
3507 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003508 } else if (checkOutputs) {
3509 checkForDeviceAndOutputChanges();
3510 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003511 }
3512 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003513}
3514
3515status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3516{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003517 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003518 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003519 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003520 sp<HwModule> rSubmixModule;
3521 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003522 for (const auto& mix : mixes) {
3523 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003524
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003525 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003526 rSubmixModule = mHwModules.getModuleFromName(
3527 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3528 if (rSubmixModule == 0) {
3529 res = INVALID_OPERATION;
3530 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003531 }
3532 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003533
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003535
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003536 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003537 res = INVALID_OPERATION;
3538 continue;
3539 }
3540
Kevin Rocard04ed0462019-05-02 17:53:24 -07003541 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3542 if (getDeviceConnectionState(device, address.string()) ==
3543 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3544 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3545 address.string(), "remote-submix",
3546 AUDIO_FORMAT_DEFAULT);
3547 if (res != OK) {
3548 ALOGE("Error making RemoteSubmix device unavailable for mix "
3549 "with type %d, address %s", device, address.string());
3550 }
3551 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003552 }
jiabin5740f082019-08-19 15:08:30 -07003553 rSubmixModule->removeOutputProfile(address.c_str());
3554 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003555
Kevin Rocard153f92d2018-12-18 18:33:28 -08003556 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003557 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003558 res = INVALID_OPERATION;
3559 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003560 } else {
3561 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003562 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003563 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003564 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003565 if (res == NO_ERROR && checkOutputs) {
3566 checkForDeviceAndOutputChanges();
3567 updateCallAndOutputRouting();
3568 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003569 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003570}
3571
Mikhail Naganov100f0122018-11-29 11:22:16 -08003572void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3573{
3574 size_t i = 0;
3575 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3576 for (const auto& fmt : mManualSurroundFormats) {
3577 if (i++ != 0) dst->append(", ");
3578 std::string sfmt;
3579 FormatConverter::toString(fmt, sfmt);
3580 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3581 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3582 }
3583}
3584
Eric Laurentc529cf62020-04-17 18:19:10 -07003585// Returns true if all devices types match the predicate and are supported by one HW module
3586bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003587 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003588 std::function<bool(audio_devices_t)> predicate,
3589 const char *context) {
3590 for (size_t i = 0; i < devices.size(); i++) {
3591 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003592 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003593 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003594 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003595 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003596 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003597 return false;
3598 }
3599 }
3600 return true;
3601}
3602
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003603status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003604 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003605 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003606 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3607 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003608 }
3609 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003610 if (res != NO_ERROR) {
3611 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3612 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003613 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003614
3615 checkForDeviceAndOutputChanges();
3616 updateCallAndOutputRouting();
3617
3618 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003619}
3620
3621status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3622 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003623 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3624 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003625 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003626 __FUNCTION__, uid);
3627 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003628 }
3629
Eric Laurentc529cf62020-04-17 18:19:10 -07003630 checkForDeviceAndOutputChanges();
3631 updateCallAndOutputRouting();
3632
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003633 return res;
3634}
3635
Eric Laurent2517af32020-11-25 15:31:27 +01003636
jiabin0a488932020-08-07 17:32:40 -07003637status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3638 device_role_t role,
3639 const AudioDeviceTypeAddrVector &devices) {
3640 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3641 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003642
Eric Laurentc529cf62020-04-17 18:19:10 -07003643 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003644 return BAD_VALUE;
3645 }
jiabin0a488932020-08-07 17:32:40 -07003646 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003647 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003648 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3649 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003650 return status;
3651 }
3652
3653 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003654
3655 bool forceVolumeReeval = false;
3656 // FIXME: workaround for truncated touch sounds
3657 // to be removed when the problem is handled by system UI
3658 uint32_t delayMs = 0;
3659 if (strategy == mCommunnicationStrategy) {
3660 forceVolumeReeval = true;
3661 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3662 updateInputRouting();
3663 }
3664 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003665
3666 return NO_ERROR;
3667}
3668
3669void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3670{
3671 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003672 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003673 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003674 // Only apply special touch sound delay once
3675 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003676 }
3677 for (size_t i = 0; i < mOutputs.size(); i++) {
3678 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3679 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003680 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3681 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003682 // As done in setDeviceConnectionState, we could also fix default device issue by
3683 // preventing the force re-routing in case of default dev that distinguishes on address.
3684 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003685 bool forceRouting = !newDevices.isEmpty();
3686 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3687 true /*requiresMuteCheck*/,
3688 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003689 // Only apply special touch sound delay once
3690 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003691 }
3692 if (forceVolumeReeval && !newDevices.isEmpty()) {
3693 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3694 }
3695 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003696 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003697}
3698
Eric Laurent2517af32020-11-25 15:31:27 +01003699void AudioPolicyManager::updateInputRouting() {
3700 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303701 // Skip for hotword recording as the input device switch
3702 // is handled within sound trigger HAL
3703 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3704 continue;
3705 }
Eric Laurent2517af32020-11-25 15:31:27 +01003706 auto newDevice = getNewInputDevice(activeDesc);
3707 // Force new input selection if the new device can not be reached via current input
3708 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3709 setInputDevice(activeDesc->mIoHandle, newDevice);
3710 } else {
3711 closeInput(activeDesc->mIoHandle);
3712 }
3713 }
3714}
3715
jiabin0a488932020-08-07 17:32:40 -07003716status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3717 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003718{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003719 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003720
jiabin0a488932020-08-07 17:32:40 -07003721 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003722 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003723 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3724 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003725 return status;
3726 }
3727
3728 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003729
3730 bool forceVolumeReeval = false;
3731 // FIXME: workaround for truncated touch sounds
3732 // to be removed when the problem is handled by system UI
3733 uint32_t delayMs = 0;
3734 if (strategy == mCommunnicationStrategy) {
3735 forceVolumeReeval = true;
3736 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3737 updateInputRouting();
3738 }
3739 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003740
3741 return NO_ERROR;
3742}
3743
jiabin0a488932020-08-07 17:32:40 -07003744status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3745 device_role_t role,
3746 AudioDeviceTypeAddrVector &devices) {
3747 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003748}
3749
Jiabin Huang3b98d322020-09-03 17:54:16 +00003750status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3751 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3752 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3753 dumpAudioDeviceTypeAddrVector(devices).c_str());
3754
Mikhail Naganov55773032020-10-01 15:08:13 -07003755 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003756 return BAD_VALUE;
3757 }
3758 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3759 ALOGW_IF(status != NO_ERROR,
3760 "Engine could not set preferred devices %s for audio source %d role %d",
3761 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3762
3763 return status;
3764}
3765
3766status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3767 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3768 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3769 dumpAudioDeviceTypeAddrVector(devices).c_str());
3770
Mikhail Naganov55773032020-10-01 15:08:13 -07003771 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003772 return BAD_VALUE;
3773 }
3774 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3775 ALOGW_IF(status != NO_ERROR,
3776 "Engine could not add preferred devices %s for audio source %d role %d",
3777 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3778
Eric Laurent2517af32020-11-25 15:31:27 +01003779 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003780 return status;
3781}
3782
3783status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3784 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3785{
3786 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3787 dumpAudioDeviceTypeAddrVector(devices).c_str());
3788
Mikhail Naganov55773032020-10-01 15:08:13 -07003789 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003790 return BAD_VALUE;
3791 }
3792
3793 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3794 audioSource, role, devices);
3795 ALOGW_IF(status != NO_ERROR,
3796 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3797
Eric Laurent2517af32020-11-25 15:31:27 +01003798 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003799 return status;
3800}
3801
3802status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3803 device_role_t role) {
3804 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3805
3806 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3807 ALOGW_IF(status != NO_ERROR,
3808 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3809
Eric Laurent2517af32020-11-25 15:31:27 +01003810 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003811 return status;
3812}
3813
3814status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3815 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3816 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3817}
3818
Oscar Azucena90e77632019-11-27 17:12:28 -08003819status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003820 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003821 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003822 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3823 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003824 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003825 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3826 if (status != NO_ERROR) {
3827 ALOGE("%s() could not set device affinity for userId %d",
3828 __FUNCTION__, userId);
3829 return status;
3830 }
3831
3832 // reevaluate outputs for all devices
3833 checkForDeviceAndOutputChanges();
3834 updateCallAndOutputRouting();
3835
3836 return NO_ERROR;
3837}
3838
3839status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003840 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003841 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3842 if (status != NO_ERROR) {
3843 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3844 __FUNCTION__, userId);
3845 return status;
3846 }
3847
3848 // reevaluate outputs for all devices
3849 checkForDeviceAndOutputChanges();
3850 updateCallAndOutputRouting();
3851
3852 return NO_ERROR;
3853}
3854
Andy Hungc29d82b2018-10-05 12:23:17 -07003855void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003856{
Andy Hungc29d82b2018-10-05 12:23:17 -07003857 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003858 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003859 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003860 std::string stateLiteral;
3861 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003862 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003863 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3864 "communications", "media", "record", "dock", "system",
3865 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3866 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3867 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003868 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3869 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3870 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3871 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3872 dst->append(" (MANUAL: ");
3873 dumpManualSurroundFormats(dst);
3874 dst->append(")");
3875 }
3876 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003877 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003878 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3879 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003880 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003881 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003882
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003883 dst->append("\n");
3884 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3885 dst->append("\n");
3886 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003887 mHwModulesAll.dump(dst);
3888 mOutputs.dump(dst);
3889 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003890 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003891 mAudioPatches.dump(dst);
3892 mPolicyMixes.dump(dst);
3893 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003894
Kevin Rocardb99cc752019-03-21 20:52:24 -07003895 dst->appendFormat(" AllowedCapturePolicies:\n");
3896 for (auto& policy : mAllowedCapturePolicies) {
3897 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3898 }
3899
François Gaffiec005e562018-11-06 15:04:49 +01003900 dst->appendFormat("\nPolicy Engine dump:\n");
3901 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003902}
3903
3904status_t AudioPolicyManager::dump(int fd)
3905{
3906 String8 result;
3907 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003908 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003909 return NO_ERROR;
3910}
3911
Kevin Rocardb99cc752019-03-21 20:52:24 -07003912status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3913{
3914 mAllowedCapturePolicies[uid] = capturePolicy;
3915 return NO_ERROR;
3916}
3917
Eric Laurente552edb2014-03-10 17:42:56 -07003918// This function checks for the parameters which can be offloaded.
3919// This can be enhanced depending on the capability of the DSP and policy
3920// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003921audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003922{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003923 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003924 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003925 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003926 offloadInfo.format,
3927 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3928 offloadInfo.has_video);
3929
jiabin2b9d5a12021-12-10 01:06:29 +00003930 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003931 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003932 }
3933
3934 // See if there is a profile to support this.
3935 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003936 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003937 offloadInfo.sample_rate,
3938 offloadInfo.format,
3939 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003940 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3941 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003942 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3943 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3944 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003945 if (profile == nullptr) {
3946 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3947 }
3948 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3949 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3950 }
3951 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003952}
3953
Michael Chana94fbb22018-04-24 14:31:19 +10003954bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3955 const audio_attributes_t& attributes) {
3956 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003957 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003958 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3959 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003960 config.sample_rate,
3961 config.format,
3962 config.channel_mask,
3963 output_flags,
3964 true /* directOnly */);
3965 ALOGV("%s() profile %sfound with name: %s, "
3966 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3967 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003968 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003969 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003970
3971 // also try the MSD module if compatible profile not found
3972 if (profile == nullptr) {
3973 profile = getMsdProfileForOutput(outputDevices,
3974 config.sample_rate,
3975 config.format,
3976 config.channel_mask,
3977 output_flags,
3978 true /* directOnly */);
3979 ALOGV("%s() MSD profile %sfound with name: %s, "
3980 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3981 __FUNCTION__, profile != 0 ? "" : "NOT ",
3982 (profile != 0 ? profile->getTagName().c_str() : "null"),
3983 config.sample_rate, config.format, config.channel_mask, output_flags);
3984 }
3985 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003986}
3987
jiabin2b9d5a12021-12-10 01:06:29 +00003988bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3989 bool durationIgnored) {
3990 if (mMasterMono) {
3991 return false; // no offloading if mono is set.
3992 }
3993
3994 // Check if offload has been disabled
3995 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3996 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3997 return false;
3998 }
3999
4000 // Check if stream type is music, then only allow offload as of now.
4001 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4002 {
4003 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4004 return false;
4005 }
4006
4007 //TODO: enable audio offloading with video when ready
4008 const bool allowOffloadWithVideo =
4009 property_get_bool("audio.offload.video", false /* default_value */);
4010 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4011 ALOGV("%s: has_video == true, returning false", __func__);
4012 return false;
4013 }
4014
4015 //If duration is less than minimum value defined in property, return false
4016 const int min_duration_secs = property_get_int32(
4017 "audio.offload.min.duration.secs", -1 /* default_value */);
4018 if (!durationIgnored) {
4019 if (min_duration_secs >= 0) {
4020 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4021 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4022 __func__, min_duration_secs);
4023 return false;
4024 }
4025 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4026 ALOGV("%s: Offload denied by duration < default min(=%u)",
4027 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4028 return false;
4029 }
4030 }
4031
4032 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4033 // creating an offloaded track and tearing it down immediately after start when audioflinger
4034 // detects there is an active non offloadable effect.
4035 // FIXME: We should check the audio session here but we do not have it in this context.
4036 // This may prevent offloading in rare situations where effects are left active by apps
4037 // in the background.
4038 if (mEffects.isNonOffloadableEffectEnabled()) {
4039 return false;
4040 }
4041
4042 return true;
4043}
4044
4045audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4046 const audio_config_t *config) {
4047 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4048 offloadInfo.format = config->format;
4049 offloadInfo.sample_rate = config->sample_rate;
4050 offloadInfo.channel_mask = config->channel_mask;
4051 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4052 offloadInfo.has_video = false;
4053 offloadInfo.is_streaming = false;
4054 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4055
4056 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4057 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4058 audio_flags_to_audio_output_flags(attr->flags, &flags);
4059 // only retain flags that will drive compressed offload or passthrough
4060 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4061 if (offloadPossible) {
4062 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4063 }
4064 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4065
Dorin Drimusfae3c642022-03-17 18:36:30 +01004066 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004067 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004068 DeviceVector outputDevices = engineOutputDevices;
4069 // the MSD module checks for different conditions and output devices
4070 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4071 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4072 continue;
4073 }
4074 outputDevices = getMsdAudioOutDevices();
4075 }
jiabin2b9d5a12021-12-10 01:06:29 +00004076 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004077 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004078 config->sample_rate, nullptr /*updatedSamplingRate*/,
4079 config->format, nullptr /*updatedFormat*/,
4080 config->channel_mask, nullptr /*updatedChannelMask*/,
4081 flags)) {
4082 continue;
4083 }
4084 // reject profiles not corresponding to a device currently available
4085 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4086 continue;
4087 }
4088 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4089 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004090 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004091 != AUDIO_DIRECT_NOT_SUPPORTED) {
4092 // Already reports offload gapless supported. No need to report offload support.
4093 continue;
4094 }
4095 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4096 != AUDIO_OUTPUT_FLAG_NONE) {
4097 // If offload gapless is reported, no need to report offload support.
4098 directMode = (audio_direct_mode_t) ((directMode &
4099 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4100 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4101 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004102 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004103 }
4104 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004105 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004106 }
4107 }
4108 }
4109 return directMode;
4110}
4111
Dorin Drimusf2196d82022-01-03 12:11:18 +01004112status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4113 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004114 if (mEffects.isNonOffloadableEffectEnabled()) {
4115 return OK;
4116 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004117 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004118 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004119 if (status != OK) {
4120 return status;
4121 }
4122 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4123 if (devices.empty()) {
4124 return OK; // no output devices for the attributes
4125 }
4126
4127 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004128 // the MSD module checks for different conditions
4129 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4130 continue;
4131 }
4132 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4133 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004134 continue;
4135 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004136 // allow only profiles that support all the available and routed devices
4137 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004138 != devices.size()) {
4139 continue;
4140 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004141 audioProfilesVector.addAllValidProfiles(
4142 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004143 }
4144 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004145
4146 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4147 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4148 if (msdModule != nullptr) {
4149 if (msdHasPatchesToAllDevices(devices)) {
4150 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4151 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4152 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4153 continue;
4154 }
4155 audioProfilesVector.addAllValidProfiles(
4156 outputProfile->asAudioPort()->getAudioProfiles());
4157 }
4158 } else {
4159 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4160 }
4161 }
4162
Dorin Drimusf2196d82022-01-03 12:11:18 +01004163 return NO_ERROR;
4164}
4165
Eric Laurent6a94d692014-05-20 11:18:06 -07004166status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4167 audio_port_type_t type,
4168 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004169 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004170 unsigned int *generation)
4171{
jiabin19cdba52020-11-24 11:28:58 -08004172 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4173 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004174 return BAD_VALUE;
4175 }
4176 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004177 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004178 *num_ports = 0;
4179 }
4180
4181 size_t portsWritten = 0;
4182 size_t portsMax = *num_ports;
4183 *num_ports = 0;
4184 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004185 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4186 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004188 for (const auto& dev : mAvailableOutputDevices) {
4189 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004190 continue;
4191 }
4192 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004193 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004194 }
4195 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 }
4198 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004199 for (const auto& dev : mAvailableInputDevices) {
4200 if (dev->type() == AUDIO_DEVICE_IN_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 }
4210 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4211 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4212 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4213 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4214 }
4215 *num_ports += mInputs.size();
4216 }
4217 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004218 size_t numOutputs = 0;
4219 for (size_t i = 0; i < mOutputs.size(); i++) {
4220 if (!mOutputs[i]->isDuplicated()) {
4221 numOutputs++;
4222 if (portsWritten < portsMax) {
4223 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4224 }
4225 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 }
Eric Laurent84c70242014-06-23 08:46:27 -07004227 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 }
4229 }
4230 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004231 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004232 return NO_ERROR;
4233}
4234
jiabin19cdba52020-11-24 11:28:58 -08004235status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004236{
Eric Laurent99fcae42018-05-17 16:59:18 -07004237 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4238 return BAD_VALUE;
4239 }
4240 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4241 if (dev != 0) {
4242 dev->toAudioPort(port);
4243 return NO_ERROR;
4244 }
4245 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4246 if (dev != 0) {
4247 dev->toAudioPort(port);
4248 return NO_ERROR;
4249 }
4250 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4251 if (out != 0) {
4252 out->toAudioPort(port);
4253 return NO_ERROR;
4254 }
4255 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4256 if (in != 0) {
4257 in->toAudioPort(port);
4258 return NO_ERROR;
4259 }
4260 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004261}
4262
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004263status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4264 audio_patch_handle_t *handle,
4265 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004266{
François Gaffieafd4cea2019-11-18 15:50:22 +01004267 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004268 if (handle == NULL || patch == NULL) {
4269 return BAD_VALUE;
4270 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004271 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004272 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004273 return BAD_VALUE;
4274 }
4275 // only one source per audio patch supported for now
4276 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004277 return INVALID_OPERATION;
4278 }
Eric Laurent874c42872014-08-08 15:13:39 -07004279 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004280 return INVALID_OPERATION;
4281 }
Eric Laurent874c42872014-08-08 15:13:39 -07004282 for (size_t i = 0; i < patch->num_sinks; i++) {
4283 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4284 return INVALID_OPERATION;
4285 }
4286 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004287
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004288 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4289 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4290 if (srcDevice == nullptr || sinkDevice == nullptr) {
4291 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4292 return BAD_VALUE;
4293 }
4294 ALOGV("%s between source %s and sink %s", __func__,
4295 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4296 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4297 // Default attributes, default volume priority, not to infer with non raw audio patches.
4298 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4299 const struct audio_port_config *source = &patch->sources[0];
4300 sp<SourceClientDescriptor> sourceDesc =
4301 new InternalSourceClientDescriptor(
4302 portId, uid, attributes, *source, srcDevice, sinkDevice,
4303 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4304
4305 status_t status =
4306 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4307
4308 if (status != NO_ERROR) {
4309 return INVALID_OPERATION;
4310 }
4311 mAudioSources.add(portId, sourceDesc);
4312 return NO_ERROR;
4313}
4314
4315status_t AudioPolicyManager::connectAudioSourceToSink(
4316 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4317 const struct audio_patch *patch,
4318 audio_patch_handle_t &handle,
4319 uid_t uid, uint32_t delayMs)
4320{
4321 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4322 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4323 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4324 return INVALID_OPERATION;
4325 }
4326 sourceDesc->connect(handle, sinkDevice);
4327 if (isMsdPatch(handle)) {
4328 return NO_ERROR;
4329 }
4330 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4331 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4332 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4333 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4334 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4335 goto FailurePatchAdded;
4336 }
4337 status = swOutput->start();
4338 if (status != NO_ERROR) {
4339 goto FailureSourceAdded;
4340 }
4341 swOutput->addClient(sourceDesc);
4342 status = startSource(swOutput, sourceDesc, &delayMs);
4343 if (status != NO_ERROR) {
4344 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4345 goto FailureSourceActive;
4346 }
4347 if (delayMs != 0) {
4348 usleep(delayMs * 1000);
4349 }
4350 return NO_ERROR;
4351
4352FailureSourceActive:
4353 swOutput->stop();
4354 releaseOutput(sourceDesc->portId());
4355FailureSourceAdded:
4356 sourceDesc->setSwOutput(nullptr);
4357FailurePatchAdded:
4358 releaseAudioPatchInternal(handle);
4359 return INVALID_OPERATION;
4360}
4361
4362status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4363 audio_patch_handle_t *handle,
4364 uid_t uid, uint32_t delayMs,
4365 const sp<SourceClientDescriptor>& sourceDesc)
4366{
4367 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004368 sp<AudioPatch> patchDesc;
4369 ssize_t index = mAudioPatches.indexOfKey(*handle);
4370
François Gaffieafd4cea2019-11-18 15:50:22 +01004371 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4372 patch->sources[0].role,
4373 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004374#if LOG_NDEBUG == 0
4375 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004376 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4377 patch->sinks[i].role,
4378 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004379 }
4380#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004381
4382 if (index >= 0) {
4383 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004384 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4385 __func__, mUidCached, patchDesc->getUid(), uid);
4386 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004387 return INVALID_OPERATION;
4388 }
4389 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004390 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004391 }
4392
4393 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004394 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004396 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004397 return BAD_VALUE;
4398 }
Eric Laurent84c70242014-06-23 08:46:27 -07004399 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4400 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 if (patchDesc != 0) {
4402 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004403 ALOGV("%s source id differs for patch current id %d new id %d",
4404 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 return BAD_VALUE;
4406 }
4407 }
Eric Laurent874c42872014-08-08 15:13:39 -07004408 DeviceVector devices;
4409 for (size_t i = 0; i < patch->num_sinks; i++) {
4410 // Only support mix to devices connection
4411 // TODO add support for mix to mix connection
4412 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004413 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004414 return INVALID_OPERATION;
4415 }
4416 sp<DeviceDescriptor> devDesc =
4417 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4418 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004419 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004420 return BAD_VALUE;
4421 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004422
François Gaffie11d30102018-11-02 16:09:09 +01004423 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004424 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004425 NULL, // updatedSamplingRate
4426 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004427 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004428 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004429 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004430 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004431 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004432 return INVALID_OPERATION;
4433 }
4434 devices.add(devDesc);
4435 }
4436 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004437 return INVALID_OPERATION;
4438 }
Eric Laurent874c42872014-08-08 15:13:39 -07004439
Eric Laurent6a94d692014-05-20 11:18:06 -07004440 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004441 ALOGV("%s setting device %s on output %d",
4442 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004443 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 index = mAudioPatches.indexOfKey(*handle);
4445 if (index >= 0) {
4446 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004447 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004448 }
4449 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 patchDesc->setUid(uid);
4451 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004452 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004453 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 return INVALID_OPERATION;
4455 }
4456 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4457 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4458 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004459 // only one sink supported when connecting an input device to a mix
4460 if (patch->num_sinks > 1) {
4461 return INVALID_OPERATION;
4462 }
François Gaffie53615e22015-03-19 09:24:12 +01004463 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 if (inputDesc == NULL) {
4465 return BAD_VALUE;
4466 }
4467 if (patchDesc != 0) {
4468 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4469 return BAD_VALUE;
4470 }
4471 }
François Gaffie11d30102018-11-02 16:09:09 +01004472 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004474 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004475 return BAD_VALUE;
4476 }
4477
François Gaffie11d30102018-11-02 16:09:09 +01004478 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004479 patch->sinks[0].sample_rate,
4480 NULL, /*updatedSampleRate*/
4481 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004482 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004483 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004484 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004485 // FIXME for the parameter type,
4486 // and the NONE
4487 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004488 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004489 return INVALID_OPERATION;
4490 }
4491 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004493 device->toString().c_str(), inputDesc->mIoHandle);
4494 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004495 index = mAudioPatches.indexOfKey(*handle);
4496 if (index >= 0) {
4497 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004498 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 }
4500 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004501 patchDesc->setUid(uid);
4502 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 return INVALID_OPERATION;
4506 }
4507 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4508 // device to device connection
4509 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004510 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004511 return BAD_VALUE;
4512 }
4513 }
François Gaffie11d30102018-11-02 16:09:09 +01004514 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004515 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004516 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004517 return BAD_VALUE;
4518 }
Eric Laurent874c42872014-08-08 15:13:39 -07004519
Eric Laurent6a94d692014-05-20 11:18:06 -07004520 //update source and sink with our own data as the data passed in the patch may
4521 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004522 PatchBuilder patchBuilder;
4523 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004524
4525 // if first sink is to MSD, establish single MSD patch
4526 if (getMsdAudioOutDevices().contains(
4527 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4528 ALOGV("%s patching to MSD", __FUNCTION__);
4529 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4530 goto installPatch;
4531 }
4532
François Gaffieafd4cea2019-11-18 15:50:22 +01004533 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4534 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004535
Eric Laurent874c42872014-08-08 15:13:39 -07004536 for (size_t i = 0; i < patch->num_sinks; i++) {
4537 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004538 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004539 return INVALID_OPERATION;
4540 }
François Gaffie11d30102018-11-02 16:09:09 +01004541 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004542 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004543 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004544 return BAD_VALUE;
4545 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004546 audio_port_config sinkPortConfig = {};
4547 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4548 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004549
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004550 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4551 // volume management purpose (tracking activity)
4552 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4553 // in config XML to reach the sink so that is can be declared as available.
4554 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4555 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004556 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004557 // take care of dynamic routing for SwOutput selection,
4558 audio_attributes_t attributes = sourceDesc->attributes();
4559 audio_stream_type_t stream = sourceDesc->stream();
4560 audio_attributes_t resultAttr;
4561 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4562 config.sample_rate = sourceDesc->config().sample_rate;
4563 config.channel_mask = sourceDesc->config().channel_mask;
4564 config.format = sourceDesc->config().format;
4565 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4566 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4567 bool isRequestedDeviceForExclusiveUse = false;
4568 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004569 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004570 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4571 &stream, sourceDesc->uid(), &config, &flags,
4572 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004573 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004574 if (output == AUDIO_IO_HANDLE_NONE) {
4575 ALOGV("%s no output for device %s",
4576 __FUNCTION__, sinkDevice->toString().c_str());
4577 return INVALID_OPERATION;
4578 }
4579 outputDesc = mOutputs.valueFor(output);
4580 if (outputDesc->isDuplicated()) {
4581 ALOGE("%s output is duplicated", __func__);
4582 return INVALID_OPERATION;
4583 }
4584 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004585 } else {
4586 // Same for "raw patches" aka created from createAudioPatch API
4587 SortedVector<audio_io_handle_t> outputs =
4588 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4589 // if the sink device is reachable via an opened output stream, request to
4590 // go via this output stream by adding a second source to the patch
4591 // description
4592 output = selectOutput(outputs);
4593 if (output == AUDIO_IO_HANDLE_NONE) {
4594 ALOGE("%s no output available for internal patch sink", __func__);
4595 return INVALID_OPERATION;
4596 }
4597 outputDesc = mOutputs.valueFor(output);
4598 if (outputDesc->isDuplicated()) {
4599 ALOGV("%s output for device %s is duplicated",
4600 __func__, sinkDevice->toString().c_str());
4601 return INVALID_OPERATION;
4602 }
4603 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004604 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004605 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004606 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004607 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004608 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004609 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4610 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004611 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4612 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004613 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004614 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004615 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004616 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004617 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004618 return INVALID_OPERATION;
4619 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004620 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004621 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004622 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004623 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004624 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004625 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4626 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4627 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004628 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004629 }
Eric Laurent83b88082014-06-20 18:31:16 -07004630 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004631 }
4632 // TODO: check from routing capabilities in config file and other conflicting patches
4633
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004634installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004635 status_t status = installPatch(
4636 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004637 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004638 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004639 return INVALID_OPERATION;
4640 }
4641 } else {
4642 return BAD_VALUE;
4643 }
4644 } else {
4645 return BAD_VALUE;
4646 }
4647 return NO_ERROR;
4648}
4649
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004650status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004651{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004652 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004653 ssize_t index = mAudioPatches.indexOfKey(handle);
4654
4655 if (index < 0) {
4656 return BAD_VALUE;
4657 }
4658 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004659 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4660 __func__, mUidCached, patchDesc->getUid(), uid);
4661 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004662 return INVALID_OPERATION;
4663 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004664 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4665 for (size_t i = 0; i < mAudioSources.size(); i++) {
4666 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4667 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4668 portId = sourceDesc->portId();
4669 break;
4670 }
4671 }
4672 return portId != AUDIO_PORT_HANDLE_NONE ?
4673 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004674}
Eric Laurent6a94d692014-05-20 11:18:06 -07004675
François Gaffieafd4cea2019-11-18 15:50:22 +01004676status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004677 uint32_t delayMs,
4678 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004679{
4680 ALOGV("%s patch %d", __func__, handle);
4681 if (mAudioPatches.indexOfKey(handle) < 0) {
4682 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4683 return BAD_VALUE;
4684 }
4685 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004687 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004689 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004691 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004692 return BAD_VALUE;
4693 }
4694
François Gaffie11d30102018-11-02 16:09:09 +01004695 setOutputDevices(outputDesc,
4696 getNewOutputDevices(outputDesc, true /*fromCache*/),
4697 true,
4698 0,
4699 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4701 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004702 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004703 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004704 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004705 return BAD_VALUE;
4706 }
4707 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004708 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004709 true,
4710 NULL);
4711 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004712 status_t status =
4713 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4714 ALOGV("%s patch panel returned %d patchHandle %d",
4715 __func__, status, patchDesc->getAfHandle());
4716 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004717 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004718 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004719 // SW or HW Bridge
4720 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4721 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004722 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004723 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4724 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4725 outputDesc = sourceDesc->swOutput().promote();
4726 }
4727 if (outputDesc == nullptr) {
4728 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4729 // releaseOutput has already called closeOutput in case of direct output
4730 return NO_ERROR;
4731 }
4732 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4733 resetOutputDevice(outputDesc);
4734 } else {
4735 // Reuse patch handle if still valid / do not force rerouting if still routed
4736 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004737 setOutputDevices(outputDesc,
4738 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004739 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004740 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004741 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004742 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 } else {
4744 return BAD_VALUE;
4745 }
4746 } else {
4747 return BAD_VALUE;
4748 }
4749 return NO_ERROR;
4750}
4751
4752status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4753 struct audio_patch *patches,
4754 unsigned int *generation)
4755{
François Gaffie53615e22015-03-19 09:24:12 +01004756 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004757 return BAD_VALUE;
4758 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004760 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004761}
4762
Eric Laurente1715a42014-05-20 11:30:42 -07004763status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004764{
Eric Laurente1715a42014-05-20 11:30:42 -07004765 ALOGV("setAudioPortConfig()");
4766
4767 if (config == NULL) {
4768 return BAD_VALUE;
4769 }
4770 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4771 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004772 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4773 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004774 }
4775
Eric Laurenta121f902014-06-03 13:32:54 -07004776 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004777 if (config->type == AUDIO_PORT_TYPE_MIX) {
4778 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004779 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004780 if (outputDesc == NULL) {
4781 return BAD_VALUE;
4782 }
Eric Laurent84c70242014-06-23 08:46:27 -07004783 ALOG_ASSERT(!outputDesc->isDuplicated(),
4784 "setAudioPortConfig() called on duplicated output %d",
4785 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004786 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004787 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004788 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004789 if (inputDesc == NULL) {
4790 return BAD_VALUE;
4791 }
Eric Laurenta121f902014-06-03 13:32:54 -07004792 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004793 } else {
4794 return BAD_VALUE;
4795 }
4796 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4797 sp<DeviceDescriptor> deviceDesc;
4798 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4799 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4800 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4801 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4802 } else {
4803 return BAD_VALUE;
4804 }
4805 if (deviceDesc == NULL) {
4806 return BAD_VALUE;
4807 }
Eric Laurenta121f902014-06-03 13:32:54 -07004808 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004809 } else {
4810 return BAD_VALUE;
4811 }
4812
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004813 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004814 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4815 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004816 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004817 audioPortConfig->toAudioPortConfig(&newConfig, config);
4818 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004819 }
Eric Laurenta121f902014-06-03 13:32:54 -07004820 if (status != NO_ERROR) {
4821 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004822 }
Eric Laurente1715a42014-05-20 11:30:42 -07004823
4824 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004825}
4826
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004827void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4828{
Eric Laurentd60560a2015-04-10 11:31:20 -07004829 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004830 clearAudioPatches(uid);
4831 clearSessionRoutes(uid);
4832}
4833
Eric Laurent6a94d692014-05-20 11:18:06 -07004834void AudioPolicyManager::clearAudioPatches(uid_t uid)
4835{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004836 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004838 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004839 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 }
4841 }
4842}
4843
François Gaffiec005e562018-11-06 15:04:49 +01004844void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004845{
François Gaffiec005e562018-11-06 15:04:49 +01004846 // Take the first attributes following the product strategy as it is used to retrieve the routed
4847 // device. All attributes wihin a strategy follows the same "routing strategy"
4848 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4849 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004850 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004851 for (size_t j = 0; j < mOutputs.size(); j++) {
4852 if (mOutputs.keyAt(j) == ouptutToSkip) {
4853 continue;
4854 }
4855 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004856 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004857 continue;
4858 }
4859 // If the default device for this strategy is on another output mix,
4860 // invalidate all tracks in this strategy to force re connection.
4861 // Otherwise select new device on the output mix.
4862 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004863 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4864 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004865 }
4866 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004867 setOutputDevices(
4868 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004869 }
4870 }
4871}
4872
4873void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4874{
4875 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004876 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004877 for (size_t i = 0; i < mOutputs.size(); i++) {
4878 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004879 for (const auto& client : outputDesc->getClientIterable()) {
4880 if (client->hasPreferredDevice() && client->uid() == uid) {
4881 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004882 auto clientStrategy = client->strategy();
4883 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4884 end(affectedStrategies)) {
4885 continue;
4886 }
4887 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004888 }
4889 }
4890 }
4891 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004892 for (const auto& strategy : affectedStrategies) {
4893 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004894 }
4895
4896 // remove input routes associated with this uid
4897 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004898 for (size_t i = 0; i < mInputs.size(); i++) {
4899 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004900 for (const auto& client : inputDesc->getClientIterable()) {
4901 if (client->hasPreferredDevice() && client->uid() == uid) {
4902 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4903 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004904 }
4905 }
4906 }
4907 // reroute inputs if necessary
4908 SortedVector<audio_io_handle_t> inputsToClose;
4909 for (size_t i = 0; i < mInputs.size(); i++) {
4910 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004911 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004912 inputsToClose.add(inputDesc->mIoHandle);
4913 }
4914 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004915 for (const auto& input : inputsToClose) {
4916 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004917 }
4918}
4919
Eric Laurentd60560a2015-04-10 11:31:20 -07004920void AudioPolicyManager::clearAudioSources(uid_t uid)
4921{
4922 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004923 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4924 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004925 stopAudioSource(mAudioSources.keyAt(i));
4926 }
4927 }
4928}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004929
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004930status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4931 audio_io_handle_t *ioHandle,
4932 audio_devices_t *device)
4933{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004934 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4935 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004936 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004937 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004938
François Gaffiedf372692015-03-19 10:43:27 +01004939 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004940}
4941
Eric Laurentd60560a2015-04-10 11:31:20 -07004942status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004943 const audio_attributes_t *attributes,
4944 audio_port_handle_t *portId,
4945 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004946{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004947 ALOGV("%s", __FUNCTION__);
4948 *portId = AUDIO_PORT_HANDLE_NONE;
4949
4950 if (source == NULL || attributes == NULL || portId == NULL) {
4951 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4952 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004953 return BAD_VALUE;
4954 }
4955
Eric Laurentd60560a2015-04-10 11:31:20 -07004956 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4957 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004958 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4959 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004960 return INVALID_OPERATION;
4961 }
4962
François Gaffie11d30102018-11-02 16:09:09 +01004963 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004964 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004965 String8(source->ext.device.address),
4966 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004967 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004968 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004969 return BAD_VALUE;
4970 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004971
jiabin4ef93452019-09-10 14:29:54 -07004972 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004973
François Gaffieaaac0fd2018-11-22 17:56:39 +01004974 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004975 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004976 mEngine->getStreamTypeForAttributes(*attributes),
4977 mEngine->getProductStrategyForAttributes(*attributes),
4978 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004979
4980 status_t status = connectAudioSource(sourceDesc);
4981 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004982 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004983 }
4984 return status;
4985}
4986
Francois Gaffie601801d2021-06-22 13:27:39 +02004987sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4988 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4989{
4990 ALOGV("%s", __FUNCTION__);
4991 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4992
4993 status_t status = startAudioSource(source, attributes, &portId, uid);
4994 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4995 return mAudioSources.valueFor(portId);
4996}
4997
4998
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004999status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005000{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005001 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005002
5003 // make sure we only have one patch per source.
5004 disconnectAudioSource(sourceDesc);
5005
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005006 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005007 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5008 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5009 sourceDesc->srcDevice()->type(),
5010 String8(sourceDesc->srcDevice()->address().c_str()),
5011 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005012 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005013 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005014 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005015 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005016 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5017 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5018 return INVALID_OPERATION;
5019 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005020 PatchBuilder patchBuilder;
5021 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5022 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005023
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005024 return connectAudioSourceToSink(
5025 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005026}
5027
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005028status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005029{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005030 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5031 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005032 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005033 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005034 return BAD_VALUE;
5035 }
5036 status_t status = disconnectAudioSource(sourceDesc);
5037
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005038 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005039 return status;
5040}
5041
Andy Hung2ddee192015-12-18 17:34:44 -08005042status_t AudioPolicyManager::setMasterMono(bool mono)
5043{
5044 if (mMasterMono == mono) {
5045 return NO_ERROR;
5046 }
5047 mMasterMono = mono;
5048 // if enabling mono we close all offloaded devices, which will invalidate the
5049 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5050 // for recreating the new AudioTrack as non-offloaded PCM.
5051 //
5052 // If disabling mono, we leave all tracks as is: we don't know which clients
5053 // and tracks are able to be recreated as offloaded. The next "song" should
5054 // play back offloaded.
5055 if (mMasterMono) {
5056 Vector<audio_io_handle_t> offloaded;
5057 for (size_t i = 0; i < mOutputs.size(); ++i) {
5058 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5059 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5060 offloaded.push(desc->mIoHandle);
5061 }
5062 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005063 for (const auto& handle : offloaded) {
5064 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005065 }
5066 }
5067 // update master mono for all remaining outputs
5068 for (size_t i = 0; i < mOutputs.size(); ++i) {
5069 updateMono(mOutputs.keyAt(i));
5070 }
5071 return NO_ERROR;
5072}
5073
5074status_t AudioPolicyManager::getMasterMono(bool *mono)
5075{
5076 *mono = mMasterMono;
5077 return NO_ERROR;
5078}
5079
Eric Laurentac9cef52017-06-09 15:46:26 -07005080float AudioPolicyManager::getStreamVolumeDB(
5081 audio_stream_type_t stream, int index, audio_devices_t device)
5082{
jiabin9a3361e2019-10-01 09:38:30 -07005083 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005084}
5085
jiabin81772902018-04-02 17:52:27 -07005086status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5087 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005088 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005089{
Kriti Dang6537def2021-03-02 13:46:59 +01005090 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5091 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005092 return BAD_VALUE;
5093 }
Kriti Dang6537def2021-03-02 13:46:59 +01005094 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5095 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005096
5097 size_t formatsWritten = 0;
5098 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005099
Kriti Dang6537def2021-03-02 13:46:59 +01005100 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005101 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5102 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005103 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005104 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005105 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005106 bool formatEnabled = true;
5107 switch (forceUse) {
5108 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005109 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005110 break;
5111 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5112 formatEnabled = false;
5113 break;
5114 default: // AUTO or ALWAYS => true
5115 break;
jiabin81772902018-04-02 17:52:27 -07005116 }
5117 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5118 }
jiabin81772902018-04-02 17:52:27 -07005119 }
5120 return NO_ERROR;
5121}
5122
Kriti Dang6537def2021-03-02 13:46:59 +01005123status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5124 audio_format_t *surroundFormats) {
5125 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5126 return BAD_VALUE;
5127 }
5128 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5129 __func__, *numSurroundFormats, surroundFormats);
5130
5131 size_t formatsWritten = 0;
5132 size_t formatsMax = *numSurroundFormats;
5133 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5134
5135 // Return formats from all device profiles that have already been resolved by
5136 // checkOutputsForDevice().
5137 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5138 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5139 audio_devices_t deviceType = device->type();
5140 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5141 // returns formats reported by HDMI devices.
5142 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5143 continue;
5144 }
5145 // Formats reported by sink devices
5146 std::unordered_set<audio_format_t> formatset;
5147 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5148 formatset.insert(it->second.begin(), it->second.end());
5149 }
5150
5151 // Formats hard-coded in the in policy configuration file (if any).
5152 FormatVector encodedFormats = device->encodedFormats();
5153 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5154 // Filter the formats which are supported by the vendor hardware.
5155 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5156 if (mConfig.getSurroundFormats().count(*it) != 0) {
5157 formats.insert(*it);
5158 } else {
5159 for (const auto& pair : mConfig.getSurroundFormats()) {
5160 if (pair.second.count(*it) != 0) {
5161 formats.insert(pair.first);
5162 break;
5163 }
5164 }
5165 }
5166 }
5167 }
5168 *numSurroundFormats = formats.size();
5169 for (const auto& format: formats) {
5170 if (formatsWritten < formatsMax) {
5171 surroundFormats[formatsWritten++] = format;
5172 }
5173 }
5174 return NO_ERROR;
5175}
5176
jiabin81772902018-04-02 17:52:27 -07005177status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5178{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005179 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005180 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5181 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005182 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005183 return BAD_VALUE;
5184 }
5185
Mikhail Naganov100f0122018-11-29 11:22:16 -08005186 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5187 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005188 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005189 return INVALID_OPERATION;
5190 }
5191
Mikhail Naganov100f0122018-11-29 11:22:16 -08005192 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005193 return NO_ERROR;
5194 }
5195
Mikhail Naganov100f0122018-11-29 11:22:16 -08005196 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005197 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005198 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005199 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005200 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005201 }
5202 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005203 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005204 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005205 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005206 }
5207 }
5208
5209 sp<SwAudioOutputDescriptor> outputDesc;
5210 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005211 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5212 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005213 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5214 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005215 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005216 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005217 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5218 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5219 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005220 name.c_str(),
5221 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005222 if (status != NO_ERROR) {
5223 continue;
5224 }
5225 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5226 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5227 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005228 name.c_str(),
5229 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005230 profileUpdated |= (status == NO_ERROR);
5231 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005232 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005233 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005234 AUDIO_DEVICE_IN_HDMI);
5235 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5236 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005237 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005238 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005239 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5240 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5241 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005242 name.c_str(),
5243 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005244 if (status != NO_ERROR) {
5245 continue;
5246 }
5247 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5248 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5249 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005250 name.c_str(),
5251 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005252 profileUpdated |= (status == NO_ERROR);
5253 }
5254
jiabin81772902018-04-02 17:52:27 -07005255 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005256 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005257 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005258 }
5259
5260 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5261}
5262
Eric Laurent5ada82e2019-08-29 17:53:54 -07005263void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005264{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005265 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005266 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005267 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005268 }
5269}
5270
jiabin6012f912018-11-02 17:06:30 -07005271bool AudioPolicyManager::isHapticPlaybackSupported()
5272{
5273 for (const auto& hwModule : mHwModules) {
5274 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5275 for (const auto &outProfile : outputProfiles) {
5276 struct audio_port audioPort;
5277 outProfile->toAudioPort(&audioPort);
5278 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5279 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5280 return true;
5281 }
5282 }
5283 }
5284 }
5285 return false;
5286}
5287
Carter Hsu325a8eb2022-01-19 19:56:51 +08005288bool AudioPolicyManager::isUltrasoundSupported()
5289{
5290 bool hasUltrasoundOutput = false;
5291 bool hasUltrasoundInput = false;
5292 for (const auto& hwModule : mHwModules) {
5293 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5294 if (!hasUltrasoundOutput) {
5295 for (const auto &outProfile : outputProfiles) {
5296 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5297 hasUltrasoundOutput = true;
5298 break;
5299 }
5300 }
5301 }
5302
5303 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5304 if (!hasUltrasoundInput) {
5305 for (const auto &inputProfile : inputProfiles) {
5306 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5307 hasUltrasoundInput = true;
5308 break;
5309 }
5310 }
5311 }
5312
5313 if (hasUltrasoundOutput && hasUltrasoundInput)
5314 return true;
5315 }
5316 return false;
5317}
5318
Eric Laurent8340e672019-11-06 11:01:08 -08005319bool AudioPolicyManager::isCallScreenModeSupported()
5320{
5321 return getConfig().isCallScreenModeSupported();
5322}
5323
5324
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005325status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005326{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005327 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005328 if (!sourceDesc->isConnected()) {
5329 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5330 return NO_ERROR;
5331 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005332 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5333 if (swOutput != 0) {
5334 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005335 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005336 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005337 }
jiabinbce0c1d2020-10-05 11:20:18 -07005338 if (releaseOutput(sourceDesc->portId())) {
5339 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5340 // no need to release audio patch here but just return NO_ERROR.
5341 return NO_ERROR;
5342 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005343 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005344 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005345 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005346 // close Hwoutput and remove from mHwOutputs
5347 } else {
5348 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5349 }
5350 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005351 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005352 sourceDesc->disconnect();
5353 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005354}
5355
François Gaffiec005e562018-11-06 15:04:49 +01005356sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5357 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005358{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005359 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005360 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005361 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005362 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005363 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5364 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005365 source = sourceDesc;
5366 break;
5367 }
5368 }
5369 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005370}
5371
Eric Laurentb4f42a92022-01-17 17:37:31 +01005372bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005373 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005374 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005375{
5376 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5377 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005378 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005379 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005380 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5381 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5382 return false;
5383 }
5384 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5385 return false;
5386 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005387 }
5388
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005389 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005390 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005391 if (profile == nullptr) {
5392 return false;
5393 }
5394
5395 // The caller can have the audio config criteria ignored by either passing a null ptr or
5396 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005397 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005398 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005399
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005400 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005401 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005402 return false;
5403 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005404 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005405 return true;
5406}
5407
5408void AudioPolicyManager::checkVirtualizerClientRoutes() {
5409 std::set<audio_stream_type_t> streamsToInvalidate;
5410 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005411 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5412 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005413 audio_attributes_t attr = client->attributes();
5414 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5415 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5416 audio_config_base_t clientConfig = client->config();
5417 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005418 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005419 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005420 streamsToInvalidate.insert(client->stream());
5421 }
5422 }
5423 }
5424
5425 for (audio_stream_type_t stream : streamsToInvalidate) {
5426 mpClientInterface->invalidateStream(stream);
5427 }
5428}
5429
Eric Laurente191d1b2022-04-15 11:59:25 +02005430
5431bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5432 const sp<SwAudioOutputDescriptor>& outputDesc) {
5433 if (outputDesc->isDuplicated()) {
5434 return false;
5435 }
5436 DeviceVector devices = outputDesc->supportedDevices();
5437 for (size_t i = 0; i < mOutputs.size(); i++) {
5438 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5439 if (desc == outputDesc || desc->isDuplicated()) {
5440 continue;
5441 }
5442 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5443 if (!sharedDevices.isEmpty()
5444 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5445 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5446 return false;
5447 }
5448 }
5449 return true;
5450}
5451
5452
Eric Laurentfa0f6742021-08-17 18:39:44 +02005453status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005454 const audio_attributes_t *attr,
5455 audio_io_handle_t *output) {
5456 *output = AUDIO_IO_HANDLE_NONE;
5457
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005458 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5459 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5460 audio_config_t *configPtr = nullptr;
5461 audio_config_t config;
5462 if (mixerConfig != nullptr) {
5463 config = audio_config_initializer(mixerConfig);
5464 configPtr = &config;
5465 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005466 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005467 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005468 return BAD_VALUE;
5469 }
5470
5471 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005472 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005473 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005474 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005475 return BAD_VALUE;
5476 }
5477
Eric Laurente191d1b2022-04-15 11:59:25 +02005478 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005479 for (size_t i = 0; i < mOutputs.size(); i++) {
5480 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005481 if (!desc->isDuplicated()
5482 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5483 spatializerOutputs.push_back(desc);
5484 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005485 }
5486 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005487 mSpatializerOutput.clear();
5488 bool outputsChanged = false;
5489 for (const auto& desc : spatializerOutputs) {
5490 if (desc->mProfile == profile
5491 && (configPtr == nullptr
5492 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5493 mSpatializerOutput = desc;
5494 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5495 } else {
5496 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5497 " and devices %s", __func__, desc->mIoHandle,
5498 configPtr != nullptr ? configPtr->channel_mask : 0,
5499 devices.toString().c_str());
5500 closeOutput(desc->mIoHandle);
5501 outputsChanged = true;
5502 }
Eric Laurent39095982021-08-24 18:29:27 +02005503 }
5504
Eric Laurente191d1b2022-04-15 11:59:25 +02005505 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005506 sp<SwAudioOutputDescriptor> desc =
5507 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005508 if (desc != nullptr) {
5509 mSpatializerOutput = desc;
5510 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005511 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005512 }
5513
5514 checkVirtualizerClientRoutes();
5515
Eric Laurente191d1b2022-04-15 11:59:25 +02005516 if (outputsChanged) {
5517 mPreviousOutputs = mOutputs;
5518 mpClientInterface->onAudioPortListUpdate();
5519 }
5520
5521 if (mSpatializerOutput == nullptr) {
5522 ALOGV("%s could not open spatializer output with requested config", __func__);
5523 return BAD_VALUE;
5524 }
Eric Laurent39095982021-08-24 18:29:27 +02005525 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005526 ALOGV("%s returning new spatializer output %d", __func__, *output);
5527 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005528}
5529
Eric Laurentfa0f6742021-08-17 18:39:44 +02005530status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5531 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005532 return INVALID_OPERATION;
5533 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005534 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005535 return BAD_VALUE;
5536 }
Eric Laurent39095982021-08-24 18:29:27 +02005537
Eric Laurente191d1b2022-04-15 11:59:25 +02005538 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5539 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5540 closeOutput(mSpatializerOutput->mIoHandle);
5541 //from now on mSpatializerOutput is null
5542 checkVirtualizerClientRoutes();
5543 }
Eric Laurent39095982021-08-24 18:29:27 +02005544
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005545 return NO_ERROR;
5546}
5547
Eric Laurente552edb2014-03-10 17:42:56 -07005548// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005549// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005550// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005551uint32_t AudioPolicyManager::nextAudioPortGeneration()
5552{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005553 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005554}
5555
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005556static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005557 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5558 !audioPolicyXmlConfigFile.empty()) {
5559 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5560 if (ret == NO_ERROR) {
5561 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005562 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005563 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005564 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005565 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005566}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005567
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005568AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5569 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005570 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005571 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005572 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005573 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005574 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005575 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005576 mAudioPortGeneration(1),
5577 mBeaconMuteRefCount(0),
5578 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005579 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005580 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005581 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005582 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005583{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005584}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005585
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005586AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5587 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5588{
5589 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005590}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005591
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005592void AudioPolicyManager::loadConfig() {
5593 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005594 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005595 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005596 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005597}
5598
5599status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005600 {
5601 auto engLib = EngineLibrary::load(
5602 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5603 if (!engLib) {
5604 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5605 return NO_INIT;
5606 }
5607 mEngine = engLib->createEngine();
5608 if (mEngine == nullptr) {
5609 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5610 return NO_INIT;
5611 }
François Gaffie2110e042015-03-24 08:41:51 +01005612 }
5613 mEngine->setObserver(this);
5614 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005615 if (status != NO_ERROR) {
5616 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5617 return status;
5618 }
François Gaffie2110e042015-03-24 08:41:51 +01005619
Mikhail Naganove93ae282023-02-02 15:28:26 -08005620 // If microphones address is empty, set it according to device type
5621 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
5622 if (mInputDevicesAll[i]->address().empty()) {
5623 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
5624 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
5625 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
5626 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
5627 }
5628 }
5629 }
5630
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005631 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005632 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5633 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5634
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005635 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005636 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005637 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005638
Eric Laurent3a4311c2014-03-17 12:00:47 -07005639 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005640 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5641 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5642 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005643 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005644 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005645 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005646
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005647 // Silence ALOGV statements
5648 property_set("log.tag." LOG_TAG, "D");
5649
Eric Laurente552edb2014-03-10 17:42:56 -07005650 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005651 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005652}
5653
Eric Laurente0720872014-03-11 09:30:41 -07005654AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005655{
Eric Laurente552edb2014-03-10 17:42:56 -07005656 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005657 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005658 }
5659 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005660 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005661 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005662 mAvailableOutputDevices.clear();
5663 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005664 mOutputs.clear();
5665 mInputs.clear();
5666 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005667 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005668 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005669}
5670
Eric Laurente0720872014-03-11 09:30:41 -07005671status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005672{
Eric Laurent87ffa392015-05-22 10:32:38 -07005673 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005674}
5675
Eric Laurente552edb2014-03-10 17:42:56 -07005676// ---
5677
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005678void AudioPolicyManager::onNewAudioModulesAvailable()
5679{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005680 DeviceVector newDevices;
5681 onNewAudioModulesAvailableInt(&newDevices);
5682 if (!newDevices.empty()) {
5683 nextAudioPortGeneration();
5684 mpClientInterface->onAudioPortListUpdate();
5685 }
5686}
5687
5688void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5689{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005690 for (const auto& hwModule : mHwModulesAll) {
5691 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5692 continue;
5693 }
5694 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5695 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5696 ALOGW("could not open HW module %s", hwModule->getName());
5697 continue;
5698 }
5699 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005700 // open all output streams needed to access attached devices.
5701 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005702 // This also validates mAvailableOutputDevices list
5703 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5704 if (!outProfile->canOpenNewIo()) {
5705 ALOGE("Invalid Output profile max open count %u for profile %s",
5706 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5707 continue;
5708 }
5709 if (!outProfile->hasSupportedDevices()) {
5710 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5711 continue;
5712 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005713 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5714 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005715 mTtsOutputAvailable = true;
5716 }
5717
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005718 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5719 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5720 sp<DeviceDescriptor> supportedDevice = 0;
5721 if (supportedDevices.contains(mDefaultOutputDevice)) {
5722 supportedDevice = mDefaultOutputDevice;
5723 } else {
5724 // choose first device present in profile's SupportedDevices also part of
5725 // mAvailableOutputDevices.
5726 if (availProfileDevices.isEmpty()) {
5727 continue;
5728 }
5729 supportedDevice = availProfileDevices.itemAt(0);
5730 }
5731 if (!mOutputDevicesAll.contains(supportedDevice)) {
5732 continue;
5733 }
5734 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5735 mpClientInterface);
5736 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005737 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5738 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005739 AUDIO_STREAM_DEFAULT,
5740 AUDIO_OUTPUT_FLAG_NONE, &output);
5741 if (status != NO_ERROR) {
5742 ALOGW("Cannot open output stream for devices %s on hw module %s",
5743 supportedDevice->toString().c_str(), hwModule->getName());
5744 continue;
5745 }
5746 for (const auto &device : availProfileDevices) {
5747 // give a valid ID to an attached device once confirmed it is reachable
5748 if (!device->isAttached()) {
5749 device->attach(hwModule);
5750 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005751 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005752 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005753 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5754 }
5755 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005756 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005757 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5758 mPrimaryOutput = outputDesc;
5759 }
Eric Laurent39095982021-08-24 18:29:27 +02005760 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005761 outputDesc->close();
5762 } else {
5763 addOutput(output, outputDesc);
5764 setOutputDevices(outputDesc,
5765 DeviceVector(supportedDevice),
5766 true,
5767 0,
5768 NULL);
5769 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005770 }
5771 // open input streams needed to access attached devices to validate
5772 // mAvailableInputDevices list
5773 for (const auto& inProfile : hwModule->getInputProfiles()) {
5774 if (!inProfile->canOpenNewIo()) {
5775 ALOGE("Invalid Input profile max open count %u for profile %s",
5776 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5777 continue;
5778 }
5779 if (!inProfile->hasSupportedDevices()) {
5780 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5781 continue;
5782 }
5783 // chose first device present in profile's SupportedDevices also part of
5784 // available input devices
5785 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5786 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5787 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005788 ALOGV("%s: Input device list is empty! for profile %s",
5789 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005790 continue;
5791 }
5792 sp<AudioInputDescriptor> inputDesc =
5793 new AudioInputDescriptor(inProfile, mpClientInterface);
5794
5795 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5796 status_t status = inputDesc->open(nullptr,
5797 availProfileDevices.itemAt(0),
5798 AUDIO_SOURCE_MIC,
5799 AUDIO_INPUT_FLAG_NONE,
5800 &input);
5801 if (status != NO_ERROR) {
5802 ALOGW("Cannot open input stream for device %s on hw module %s",
5803 availProfileDevices.toString().c_str(),
5804 hwModule->getName());
5805 continue;
5806 }
5807 for (const auto &device : availProfileDevices) {
5808 // give a valid ID to an attached device once confirmed it is reachable
5809 if (!device->isAttached()) {
5810 device->attach(hwModule);
5811 device->importAudioPortAndPickAudioProfile(inProfile, true);
5812 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005813 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005814 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5815 }
5816 }
5817 inputDesc->close();
5818 }
5819 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005820
5821 // Check if spatializer outputs can be closed until used.
5822 // mOutputs vector never contains duplicated outputs at this point.
5823 std::vector<audio_io_handle_t> outputsClosed;
5824 for (size_t i = 0; i < mOutputs.size(); i++) {
5825 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5826 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5827 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5828 outputsClosed.push_back(desc->mIoHandle);
5829 desc->close();
5830 }
5831 }
5832 for (auto output : outputsClosed) {
5833 removeOutput(output);
5834 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005835}
5836
Eric Laurent98e38192018-02-15 18:31:53 -08005837void AudioPolicyManager::addOutput(audio_io_handle_t output,
5838 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005839{
Eric Laurent1c333e22014-05-20 10:48:17 -07005840 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005841 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005842 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005843 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005844 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005845}
5846
François Gaffie53615e22015-03-19 09:24:12 +01005847void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5848{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005849 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5850 ALOGV("%s: removing primary output", __func__);
5851 mPrimaryOutput = nullptr;
5852 }
François Gaffie53615e22015-03-19 09:24:12 +01005853 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005854 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005855}
5856
Eric Laurent98e38192018-02-15 18:31:53 -08005857void AudioPolicyManager::addInput(audio_io_handle_t input,
5858 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005859{
Eric Laurent1c333e22014-05-20 10:48:17 -07005860 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005861 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005862}
Eric Laurente552edb2014-03-10 17:42:56 -07005863
François Gaffie11d30102018-11-02 16:09:09 +01005864status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005865 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005866 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005867{
François Gaffie11d30102018-11-02 16:09:09 +01005868 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005869 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005870 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005871
François Gaffie11d30102018-11-02 16:09:09 +01005872 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005873 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005874 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005875 }
Eric Laurente552edb2014-03-10 17:42:56 -07005876
Eric Laurent3b73df72014-03-11 09:06:29 -07005877 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005878 // first call getAudioPort to get the supported attributes from the HAL
5879 struct audio_port_v7 port = {};
5880 device->toAudioPort(&port);
5881 status_t status = mpClientInterface->getAudioPort(&port);
5882 if (status == NO_ERROR) {
5883 device->importAudioPort(port);
5884 }
5885
5886 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005887 for (size_t i = 0; i < mOutputs.size(); i++) {
5888 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005889 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005890 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005891 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5892 mOutputs.keyAt(i), device->toString().c_str());
5893 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005894 }
5895 }
5896 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005897 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005898 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005899 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5900 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005901 if (profile->supportsDevice(device)) {
5902 profiles.add(profile);
5903 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5904 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005905 }
5906 }
5907 }
5908
Eric Laurent7b279bb2015-12-14 10:18:23 -08005909 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005910
Eric Laurente552edb2014-03-10 17:42:56 -07005911 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005912 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005913 return BAD_VALUE;
5914 }
5915
5916 // open outputs for matching profiles if needed. Direct outputs are also opened to
5917 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5918 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005919 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005920
5921 // nothing to do if one output is already opened for this profile
5922 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005923 for (j = 0; j < outputs.size(); j++) {
5924 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005925 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005926 // matching profile: save the sample rates, format and channel masks supported
5927 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005928 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005929 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005930 }
Eric Laurente552edb2014-03-10 17:42:56 -07005931 break;
5932 }
5933 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005934 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005935 continue;
5936 }
5937
Eric Laurent3974e3b2017-12-07 17:58:43 -08005938 if (!profile->canOpenNewIo()) {
5939 ALOGW("Max Output number %u already opened for this profile %s",
5940 profile->maxOpenCount, profile->getTagName().c_str());
5941 continue;
5942 }
5943
Eric Laurent83efe1c2017-07-09 16:51:08 -07005944 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005945 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005946 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5947 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005948 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005949 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005950 profiles.removeAt(profile_index);
5951 profile_index--;
5952 } else {
5953 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005954 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005955 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005956 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5957 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005958 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005959 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005960
François Gaffie11d30102018-11-02 16:09:09 +01005961 if (device_distinguishes_on_address(deviceType)) {
5962 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5963 device->toString().c_str());
5964 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5965 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005966 }
Eric Laurente552edb2014-03-10 17:42:56 -07005967 ALOGV("checkOutputsForDevice(): adding output %d", output);
5968 }
5969 }
5970
5971 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005972 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005973 return BAD_VALUE;
5974 }
Eric Laurentd4692962014-05-05 18:13:44 -07005975 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005976 // check if one opened output is not needed any more after disconnecting one device
5977 for (size_t i = 0; i < mOutputs.size(); i++) {
5978 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005979 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005980 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005981 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005982 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005983 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005984 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005985 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5986 mOutputs.keyAt(i));
5987 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005988 }
Eric Laurente552edb2014-03-10 17:42:56 -07005989 }
5990 }
Eric Laurentd4692962014-05-05 18:13:44 -07005991 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005992 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005993 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5994 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005995 if (!profile->supportsDevice(device)) {
5996 continue;
5997 }
5998 ALOGV("checkOutputsForDevice(): "
5999 "clearing direct output profile %zu on module %s",
6000 j, hwModule->getName());
6001 profile->clearAudioProfiles();
6002 if (!profile->hasDynamicAudioProfile()) {
6003 continue;
6004 }
6005 // When a device is disconnected, if there is an IOProfile that contains dynamic
6006 // profiles and supports the disconnected device, call getAudioPort to repopulate
6007 // the capabilities of the devices that is supported by the IOProfile.
6008 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6009 if (supportedDevice == device ||
6010 !mAvailableOutputDevices.contains(supportedDevice)) {
6011 continue;
6012 }
6013 struct audio_port_v7 port;
6014 supportedDevice->toAudioPort(&port);
6015 status_t status = mpClientInterface->getAudioPort(&port);
6016 if (status == NO_ERROR) {
6017 supportedDevice->importAudioPort(port);
6018 }
Eric Laurente552edb2014-03-10 17:42:56 -07006019 }
6020 }
6021 }
6022 }
6023 return NO_ERROR;
6024}
6025
François Gaffie11d30102018-11-02 16:09:09 +01006026status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006027 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006028{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006029 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006030
François Gaffie11d30102018-11-02 16:09:09 +01006031 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006032 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006033 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006034 }
6035
Eric Laurentd4692962014-05-05 18:13:44 -07006036 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006037 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006038 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006039 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006040 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006041 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006042 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006043 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006044
François Gaffie11d30102018-11-02 16:09:09 +01006045 if (profile->supportsDevice(device)) {
6046 profiles.add(profile);
6047 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6048 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006049 }
6050 }
6051 }
6052
Eric Laurent0dd51852019-04-19 18:18:58 -07006053 if (profiles.isEmpty()) {
6054 ALOGW("%s: No input profile available for device %s",
6055 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006056 return BAD_VALUE;
6057 }
6058
6059 // open inputs for matching profiles if needed. Direct inputs are also opened to
6060 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6061 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6062
Eric Laurent1c333e22014-05-20 10:48:17 -07006063 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006064
Eric Laurentd4692962014-05-05 18:13:44 -07006065 // nothing to do if one input is already opened for this profile
6066 size_t input_index;
6067 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6068 desc = mInputs.valueAt(input_index);
6069 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006070 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006071 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006072 }
Eric Laurentd4692962014-05-05 18:13:44 -07006073 break;
6074 }
6075 }
6076 if (input_index != mInputs.size()) {
6077 continue;
6078 }
6079
Eric Laurent3974e3b2017-12-07 17:58:43 -08006080 if (!profile->canOpenNewIo()) {
6081 ALOGW("Max Input number %u already opened for this profile %s",
6082 profile->maxOpenCount, profile->getTagName().c_str());
6083 continue;
6084 }
6085
Eric Laurentfe231122017-11-17 17:48:06 -08006086 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006087 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006088 status_t status = desc->open(nullptr,
6089 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006090 AUDIO_SOURCE_MIC,
6091 AUDIO_INPUT_FLAG_NONE,
6092 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006093
Eric Laurentcf2c0212014-07-25 16:20:43 -07006094 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006095 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006096 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006097 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006098 mpClientInterface->setParameters(input, String8(param));
6099 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006100 }
François Gaffie11d30102018-11-02 16:09:09 +01006101 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006102 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006103 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006104 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006105 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006106 }
6107
Eric Laurent0dd51852019-04-19 18:18:58 -07006108 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006109 addInput(input, desc);
6110 }
6111 } // endif input != 0
6112
Eric Laurentcf2c0212014-07-25 16:20:43 -07006113 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006114 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006115 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006116 profiles.removeAt(profile_index);
6117 profile_index--;
6118 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006119 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006120 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006121 }
Eric Laurentd4692962014-05-05 18:13:44 -07006122 ALOGV("checkInputsForDevice(): adding input %d", input);
6123 }
6124 } // end scan profiles
6125
6126 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006127 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006128 return BAD_VALUE;
6129 }
6130 } else {
6131 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006132 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006133 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006134 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006135 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006136 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006137 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006138 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006139 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6140 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006141 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006142 }
6143 }
6144 }
6145 } // end disconnect
6146
6147 return NO_ERROR;
6148}
6149
6150
Eric Laurente0720872014-03-11 09:30:41 -07006151void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006152{
6153 ALOGV("closeOutput(%d)", output);
6154
François Gaffie1c878552018-11-22 16:53:21 +01006155 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6156 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006157 ALOGW("closeOutput() unknown output %d", output);
6158 return;
6159 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006160 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006161 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006162
Eric Laurente552edb2014-03-10 17:42:56 -07006163 // look for duplicated outputs connected to the output being removed.
6164 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006165 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6166 if (dupOutput->isDuplicated() &&
6167 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6168 sp<SwAudioOutputDescriptor> remainingOutput =
6169 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006170 // As all active tracks on duplicated output will be deleted,
6171 // and as they were also referenced on the other output, the reference
6172 // count for their stream type must be adjusted accordingly on
6173 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006174 const bool wasActive = remainingOutput->isActive();
6175 // Note: no-op on the closing output where all clients has already been set inactive
6176 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006177 // stop() will be a no op if the output is still active but is needed in case all
6178 // active streams refcounts where cleared above
6179 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006180 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006181 }
Eric Laurente552edb2014-03-10 17:42:56 -07006182 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6183 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6184
6185 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006186 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006187 }
6188 }
6189
Eric Laurent05b90f82014-08-27 15:32:29 -07006190 nextAudioPortGeneration();
6191
François Gaffie1c878552018-11-22 16:53:21 +01006192 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006193 if (index >= 0) {
6194 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006195 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6196 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006197 mAudioPatches.removeItemsAt(index);
6198 mpClientInterface->onAudioPatchListUpdate();
6199 }
6200
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006201 if (closingOutputWasActive) {
6202 closingOutput->stop();
6203 }
François Gaffie1c878552018-11-22 16:53:21 +01006204 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006205
François Gaffie53615e22015-03-19 09:24:12 +01006206 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006207 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006208 if (closingOutput == mSpatializerOutput) {
6209 mSpatializerOutput.clear();
6210 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006211
6212 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6213 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006214 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006215 bool directOutputOpen = false;
6216 for (size_t i = 0; i < mOutputs.size(); i++) {
6217 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6218 directOutputOpen = true;
6219 break;
6220 }
6221 }
6222 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006223 ALOGV("no direct outputs open, reset MSD patches");
6224 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6225 // how output devices for patching are resolved. Avoid by caching and reusing the
6226 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6227 // devices to patch to. This may be complicated by the fact that devices may become
6228 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006229 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006230 }
6231 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006232}
6233
6234void AudioPolicyManager::closeInput(audio_io_handle_t input)
6235{
6236 ALOGV("closeInput(%d)", input);
6237
6238 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6239 if (inputDesc == NULL) {
6240 ALOGW("closeInput() unknown input %d", input);
6241 return;
6242 }
6243
Eric Laurent6a94d692014-05-20 11:18:06 -07006244 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006245
François Gaffie11d30102018-11-02 16:09:09 +01006246 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006247 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006248 if (index >= 0) {
6249 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006250 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6251 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006252 mAudioPatches.removeItemsAt(index);
6253 mpClientInterface->onAudioPatchListUpdate();
6254 }
6255
Eric Laurentfe231122017-11-17 17:48:06 -08006256 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006257 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006258
François Gaffie11d30102018-11-02 16:09:09 +01006259 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6260 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006261 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006262 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006263 }
Eric Laurente552edb2014-03-10 17:42:56 -07006264}
6265
François Gaffie11d30102018-11-02 16:09:09 +01006266SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6267 const DeviceVector &devices,
6268 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006269{
6270 SortedVector<audio_io_handle_t> outputs;
6271
François Gaffie11d30102018-11-02 16:09:09 +01006272 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006273 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006274 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006275 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006276 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006277 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006278 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006279 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006280 outputs.add(openOutputs.keyAt(i));
6281 }
6282 }
6283 return outputs;
6284}
6285
Mikhail Naganov37977152018-07-11 15:54:44 -07006286void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6287{
6288 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6289 // output is suspended before any tracks are moved to it
6290 checkA2dpSuspend();
6291 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006292 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006293 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006294 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006295 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006296 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6297 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6298 // configuration changes will ultimately be rerouted correctly. We can still avoid
6299 // unnecessary rerouting by caching and reusing the arguments to
6300 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6301 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006302 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006303 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006304 // an event that changed routing likely occurred, inform upper layers
6305 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006306}
6307
François Gaffiec005e562018-11-06 15:04:49 +01006308bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6309 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006310{
François Gaffiec005e562018-11-06 15:04:49 +01006311 return mEngine->getProductStrategyForAttributes(lAttr) ==
6312 mEngine->getProductStrategyForAttributes(rAttr);
6313}
6314
Francois Gaffieff1eb522020-05-06 18:37:04 +02006315void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6316{
6317 for (size_t i = 0; i < mAudioSources.size(); i++) {
6318 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6319 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006320 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006321 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006322 connectAudioSource(sourceDesc);
6323 }
6324 }
6325}
6326
6327void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6328{
6329 for (size_t i = 0; i < mAudioSources.size(); i++) {
6330 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6331 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6332 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6333 disconnectAudioSource(sourceDesc);
6334 }
6335 }
6336}
6337
François Gaffiec005e562018-11-06 15:04:49 +01006338void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6339{
6340 auto psId = mEngine->getProductStrategyForAttributes(attr);
6341
6342 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6343 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006344
François Gaffie11d30102018-11-02 16:09:09 +01006345 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6346 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006347
Eric Laurentc209fe42020-06-05 18:11:23 -07006348 uint32_t maxLatency = 0;
6349 bool invalidate = false;
6350 // take into account dynamic audio policies related changes: if a client is now associated
6351 // to a different policy mix than at creation time, invalidate corresponding stream
6352 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6353 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6354 if (desc->isDuplicated()) {
6355 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006356 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006357 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6358 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6359 continue;
6360 }
6361 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006362 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6363 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006364 if (status != OK) {
6365 continue;
6366 }
yucliuf4de36d2020-09-14 14:57:56 -07006367 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006368 invalidate = true;
6369 if (desc->isStrategyActive(psId)) {
6370 maxLatency = desc->latency();
6371 }
6372 break;
6373 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006374 }
6375 }
6376
Eric Laurentc209fe42020-06-05 18:11:23 -07006377 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006378 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6379 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006380 for (audio_io_handle_t srcOut : srcOutputs) {
6381 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006382 if (desc == nullptr) continue;
6383
6384 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006385 maxLatency = desc->latency();
6386 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006387
6388 if (invalidate) continue;
6389
6390 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006391 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006392 // a client on a non direct outputs has necessarily a linear PCM format
6393 // so we can call selectOutput() safely
6394 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6395 client->flags(),
6396 client->config().format,
6397 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006398 client->config().sample_rate,
6399 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006400 if (newOutput != srcOut) {
6401 invalidate = true;
6402 break;
6403 }
6404 } else {
6405 sp<IOProfile> profile = getProfileForOutput(newDevices,
6406 client->config().sample_rate,
6407 client->config().format,
6408 client->config().channel_mask,
6409 client->flags(),
6410 true /* directOnly */);
6411 if (profile != desc->mProfile) {
6412 invalidate = true;
6413 break;
6414 }
6415 }
6416 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006417 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006418
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006419 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006420 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006421 std::to_string(srcOutputs[0]).c_str(),
6422 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006423 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006424 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006425 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006426 if (desc == nullptr) continue;
6427
6428 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006429 setStrategyMute(psId, true, desc);
6430 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006431 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006432 }
François Gaffiec005e562018-11-06 15:04:49 +01006433 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006434 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006435 connectAudioSource(source);
6436 }
Eric Laurente552edb2014-03-10 17:42:56 -07006437 }
6438
François Gaffiec005e562018-11-06 15:04:49 +01006439 // Move effects associated to this stream from previous output to new output
6440 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006441 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006442 }
François Gaffiec005e562018-11-06 15:04:49 +01006443 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006444 if (invalidate) {
6445 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6446 mpClientInterface->invalidateStream(stream);
6447 }
jiabin49256852022-03-09 11:21:35 -08006448 for (audio_io_handle_t srcOut : srcOutputs) {
6449 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6450 if (desc == nullptr) continue;
6451
6452 desc->setTracksInvalidatedStatusByStrategy(psId);
6453 }
Eric Laurente552edb2014-03-10 17:42:56 -07006454 }
6455 }
6456}
6457
Eric Laurente0720872014-03-11 09:30:41 -07006458void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006459{
François Gaffiec005e562018-11-06 15:04:49 +01006460 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6461 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6462 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006463 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006464 }
Eric Laurente552edb2014-03-10 17:42:56 -07006465}
6466
Kevin Rocard153f92d2018-12-18 18:33:28 -08006467void AudioPolicyManager::checkSecondaryOutputs() {
6468 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006469 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006470 for (size_t i = 0; i < mOutputs.size(); i++) {
6471 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6472 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006473 sp<AudioPolicyMix> primaryMix;
6474 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006475 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6476 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006477 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6478 for (auto &secondaryMix : secondaryMixes) {
6479 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6480 if (outputDesc != nullptr &&
6481 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6482 secondaryDescs.push_back(outputDesc);
6483 }
6484 }
6485
jiabin10a03f12021-05-07 23:46:28 +00006486 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006487 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006488 } else if (!std::equal(
6489 client->getSecondaryOutputs().begin(),
6490 client->getSecondaryOutputs().end(),
6491 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006492 if (!audio_is_linear_pcm(client->config().format)) {
6493 // If the format is not PCM, the tracks should be invalidated to get correct
6494 // behavior when the secondary output is changed.
6495 streamsToInvalidate.insert(client->stream());
6496 } else {
6497 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6498 std::vector<audio_io_handle_t> secondaryOutputIds;
6499 for (const auto &secondaryDesc: secondaryDescs) {
6500 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6501 weakSecondaryDescs.push_back(secondaryDesc);
6502 }
6503 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6504 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006505 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006506 }
6507 }
6508 }
jiabin10a03f12021-05-07 23:46:28 +00006509 if (!trackSecondaryOutputs.empty()) {
6510 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6511 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006512 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006513 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006514 mpClientInterface->invalidateStream(stream);
6515 }
6516}
6517
Eric Laurent2517af32020-11-25 15:31:27 +01006518bool AudioPolicyManager::isScoRequestedForComm() const {
6519 AudioDeviceTypeAddrVector devices;
6520 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6521 for (const auto &device : devices) {
6522 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6523 return true;
6524 }
6525 }
6526 return false;
6527}
6528
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006529bool AudioPolicyManager::isHearingAidUsedForComm() const {
6530 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6531 true /*fromCache*/);
6532 for (const auto &device : devices) {
6533 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6534 return true;
6535 }
6536 }
6537 return false;
6538}
6539
6540
Eric Laurente0720872014-03-11 09:30:41 -07006541void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006542{
François Gaffie53615e22015-03-19 09:24:12 +01006543 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006544 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006545 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006546 return;
6547 }
6548
Eric Laurent3a4311c2014-03-17 12:00:47 -07006549 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006550 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6551 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006552 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006553
6554 // if suspended, restore A2DP output if:
6555 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006556 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006557 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006558 //
Eric Laurentf732e072016-08-03 19:30:28 -07006559 // if not suspended, suspend A2DP output if:
6560 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006561 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006562 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006563 //
6564 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006565 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006566 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006567 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006568 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006569
6570 mpClientInterface->restoreOutput(a2dpOutput);
6571 mA2dpSuspended = false;
6572 }
6573 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006574 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006575 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006576 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006577 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006578
6579 mpClientInterface->suspendOutput(a2dpOutput);
6580 mA2dpSuspended = true;
6581 }
6582 }
6583}
6584
François Gaffie11d30102018-11-02 16:09:09 +01006585DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6586 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006587{
François Gaffie11d30102018-11-02 16:09:09 +01006588 DeviceVector devices;
6589
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006590 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006591 if (index >= 0) {
6592 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006593 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006594 ALOGV("%s device %s forced by patch %d", __func__,
6595 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6596 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006597 }
6598 }
6599
Dean Wheatley514b4312020-06-17 21:45:00 +10006600 // Do not retrieve engine device for outputs through MSD
6601 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6602 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6603 return outputDesc->devices();
6604 }
6605
Eric Laurent97ac8712018-07-27 18:59:02 -07006606 // Honor explicit routing requests only if no client using default routing is active on this
6607 // input: a specific app can not force routing for other apps by setting a preferred device.
6608 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006609 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006610 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006611 if (device != nullptr) {
6612 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006613 }
6614
François Gaffiea807ef92018-11-05 10:44:33 +01006615 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6616 // of setForceUse / Default Bus device here
6617 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6618 if (device != nullptr) {
6619 return DeviceVector(device);
6620 }
6621
François Gaffiec005e562018-11-06 15:04:49 +01006622 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6623 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6624 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306625 auto hasStreamActive = [&](auto stream) {
6626 return hasStream(streams, stream) && isStreamActive(stream, 0);
6627 };
Eric Laurent484e9272018-06-07 17:29:23 -07006628
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306629 auto doGetOutputDevicesForVoice = [&]() {
6630 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006631 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306632 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006633 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6634 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306635 };
6636
6637 // With low-latency playing on speaker, music on WFD, when the first low-latency
6638 // output is stopped, getNewOutputDevices checks for a product strategy
6639 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006640 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306641 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6642 // stream is associated to the output descriptor.
6643 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6644 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6645 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6646 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006647 // Retrieval of devices for voice DL is done on primary output profile, cannot
6648 // check the route (would force modifying configuration file for this profile)
6649 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6650 break;
6651 }
Eric Laurente552edb2014-03-10 17:42:56 -07006652 }
François Gaffiec005e562018-11-06 15:04:49 +01006653 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006654 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006655}
6656
François Gaffie11d30102018-11-02 16:09:09 +01006657sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6658 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006659{
François Gaffie11d30102018-11-02 16:09:09 +01006660 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006661
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006662 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006663 if (index >= 0) {
6664 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006665 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006666 ALOGV("getNewInputDevice() device %s forced by patch %d",
6667 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6668 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006669 }
6670 }
6671
Eric Laurent97ac8712018-07-27 18:59:02 -07006672 // Honor explicit routing requests only if no client using default routing is active on this
6673 // input: a specific app can not force routing for other apps by setting a preferred device.
6674 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006675 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6676 if (device != nullptr) {
6677 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006678 }
6679
Eric Laurentdc95a252018-04-12 12:46:56 -07006680 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006681 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006682 audio_attributes_t attributes;
6683 uid_t uid;
6684 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6685 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006686 attributes = topClient->attributes();
6687 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006688 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006689 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6690 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006691 }
6692
Francois Gaffie716e1432019-01-14 16:58:59 +01006693 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6694 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006695 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006696 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006697 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006698 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006699
Eric Laurente552edb2014-03-10 17:42:56 -07006700 return device;
6701}
6702
Eric Laurent794fde22016-03-11 09:50:45 -08006703bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6704 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006705 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006706}
6707
Dorin Drimusf2196d82022-01-03 12:11:18 +01006708// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006709status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006710 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006711 if (devices == nullptr) {
6712 return BAD_VALUE;
6713 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006714
6715 // Devices are determined in the following precedence:
6716 //
6717 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6718 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6719 //
6720 // If no such dynamic policy then
6721 // 2) Devices containing an active client using setPreferredDevice
6722 // with same strategy as the attributes.
6723 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6724 //
6725 // If no corresponding active client with setPreferredDevice then
6726 // 3) Devices associated with the strategy determined by the attributes
6727 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6728 //
6729 // See related getOutputForAttrInt().
6730
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006731 // check dynamic policies but only for primary descriptors (secondary not used for audible
6732 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006733 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006734 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6735 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006736 if (status != OK) {
6737 return status;
6738 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006739
6740 DeviceVector curDevices;
6741 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6742 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6743 // as they are unaffected by device/stream volume
6744 // (per SwAudioOutputDescriptor::isFixedVolume()).
6745 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6746 ) {
6747 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6748 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6749 curDevices.add(deviceDesc);
6750 } else {
6751 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6752 // which selects setPreferredDevice if active. This means forVolume call
6753 // will take an active setPreferredDevice, if such exists.
6754
6755 curDevices = mEngine->getOutputDevicesForAttributes(
6756 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006757 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006758
6759 if (forVolume) {
6760 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6761 // for single volume control in AudioService (such relationship should exist if
6762 // SPEAKER_SAFE is present).
6763 //
6764 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6765 DeviceVector speakerSafeDevices =
6766 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6767 if (!speakerSafeDevices.isEmpty()) {
6768 curDevices.merge(
6769 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6770 curDevices.remove(speakerSafeDevices);
6771 }
6772 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006773 for (const auto& device : curDevices) {
6774 devices->push_back(device->getDeviceTypeAddr());
6775 }
6776 return NO_ERROR;
6777}
6778
Eric Laurente0720872014-03-11 09:30:41 -07006779void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006780 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006781 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006782 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006783 updateDevicesAndOutputs();
6784 break;
6785 default:
6786 break;
6787 }
6788}
6789
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006790uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006791
6792 // skip beacon mute management if a dedicated TTS output is available
6793 if (mTtsOutputAvailable) {
6794 return 0;
6795 }
6796
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006797 switch(event) {
6798 case STARTING_OUTPUT:
6799 mBeaconMuteRefCount++;
6800 break;
6801 case STOPPING_OUTPUT:
6802 if (mBeaconMuteRefCount > 0) {
6803 mBeaconMuteRefCount--;
6804 }
6805 break;
6806 case STARTING_BEACON:
6807 mBeaconPlayingRefCount++;
6808 break;
6809 case STOPPING_BEACON:
6810 if (mBeaconPlayingRefCount > 0) {
6811 mBeaconPlayingRefCount--;
6812 }
6813 break;
6814 }
6815
6816 if (mBeaconMuteRefCount > 0) {
6817 // any playback causes beacon to be muted
6818 return setBeaconMute(true);
6819 } else {
6820 // no other playback: unmute when beacon starts playing, mute when it stops
6821 return setBeaconMute(mBeaconPlayingRefCount == 0);
6822 }
6823}
6824
6825uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6826 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6827 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6828 // keep track of muted state to avoid repeating mute/unmute operations
6829 if (mBeaconMuted != mute) {
6830 // mute/unmute AUDIO_STREAM_TTS on all outputs
6831 ALOGV("\t muting %d", mute);
6832 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006833 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6834 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6835 ALOGV("\t no tts volume source available");
6836 return 0;
6837 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006838 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006839 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006840 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006841 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006842 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006843 maxLatency = latency;
6844 }
6845 }
6846 mBeaconMuted = mute;
6847 return maxLatency;
6848 }
6849 return 0;
6850}
6851
Eric Laurente0720872014-03-11 09:30:41 -07006852void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006853{
François Gaffiec005e562018-11-06 15:04:49 +01006854 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006855 mPreviousOutputs = mOutputs;
6856}
6857
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006858uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006859 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006860 uint32_t delayMs)
6861{
6862 // mute/unmute strategies using an incompatible device combination
6863 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6864 // if unmuting, unmute only after the specified delay
6865 if (outputDesc->isDuplicated()) {
6866 return 0;
6867 }
6868
6869 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006870 DeviceVector devices = outputDesc->devices();
6871 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006872
François Gaffiec005e562018-11-06 15:04:49 +01006873 auto productStrategies = mEngine->getOrderedProductStrategies();
6874 for (const auto &productStrategy : productStrategies) {
6875 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6876 DeviceVector curDevices =
6877 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6878 curDevices = curDevices.filter(outputDesc->supportedDevices());
6879 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006880 bool doMute = false;
6881
François Gaffiec005e562018-11-06 15:04:49 +01006882 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006883 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006884 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6885 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006886 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006887 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006888 }
Eric Laurent99401132014-05-07 19:48:15 -07006889 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006890 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006891 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006892 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006893 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006894 continue;
6895 }
François Gaffiec005e562018-11-06 15:04:49 +01006896 ALOGVV("%s() %s (curDevice %s)", __func__,
6897 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6898 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6899 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006900 if (mute) {
6901 // FIXME: should not need to double latency if volume could be applied
6902 // immediately by the audioflinger mixer. We must account for the delay
6903 // between now and the next time the audioflinger thread for this output
6904 // will process a buffer (which corresponds to one buffer size,
6905 // usually 1/2 or 1/4 of the latency).
6906 if (muteWaitMs < desc->latency() * 2) {
6907 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006908 }
6909 }
6910 }
6911 }
6912 }
6913 }
6914
Eric Laurent99401132014-05-07 19:48:15 -07006915 // temporary mute output if device selection changes to avoid volume bursts due to
6916 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006917 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006918 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006919
Eric Laurentdc462862016-07-19 12:29:53 -07006920 if (muteWaitMs < tempMuteWaitMs) {
6921 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006922 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006923
6924 // If recommended duration is defined, replace temporary mute duration to avoid
6925 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6926 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6927 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6928 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6929 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6930
François Gaffieaaac0fd2018-11-22 17:56:39 +01006931 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6932 // make sure that we do not start the temporary mute period too early in case of
6933 // delayed device change
6934 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6935 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006936 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006937 }
6938 }
6939
Eric Laurente552edb2014-03-10 17:42:56 -07006940 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6941 if (muteWaitMs > delayMs) {
6942 muteWaitMs -= delayMs;
6943 usleep(muteWaitMs * 1000);
6944 return muteWaitMs;
6945 }
6946 return 0;
6947}
6948
François Gaffie11d30102018-11-02 16:09:09 +01006949uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6950 const DeviceVector &devices,
6951 bool force,
6952 int delayMs,
6953 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006954 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006955{
François Gaffie11d30102018-11-02 16:09:09 +01006956 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006957 uint32_t muteWaitMs;
6958
6959 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006960 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6961 nullptr /* patchHandle */, requiresMuteCheck);
6962 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6963 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006964 return muteWaitMs;
6965 }
Eric Laurente552edb2014-03-10 17:42:56 -07006966
6967 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006968 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006969 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006970 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006971
François Gaffie11d30102018-11-02 16:09:09 +01006972 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6973
6974 if (!filteredDevices.isEmpty()) {
6975 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006976 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006977
6978 // if the outputs are not materially active, there is no need to mute.
6979 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006980 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006981 } else {
6982 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6983 muteWaitMs = 0;
6984 }
Eric Laurente552edb2014-03-10 17:42:56 -07006985
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006986 bool outputRouted = outputDesc->isRouted();
6987
Eric Laurent79ea9582020-06-11 18:49:24 -07006988 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6989 // output profile or if new device is not supported AND previous device(s) is(are) still
6990 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006991 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006992 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6993 // restore previous device after evaluating strategy mute state
6994 outputDesc->setDevices(prevDevices);
6995 return muteWaitMs;
6996 }
6997
Eric Laurente552edb2014-03-10 17:42:56 -07006998 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006999 // the requested device is AUDIO_DEVICE_NONE
7000 // OR the requested device is the same as current device
7001 // AND force is not specified
7002 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007003 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007004 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007005 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7006 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007007 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7008 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7009 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7010 }
Eric Laurente552edb2014-03-10 17:42:56 -07007011 return muteWaitMs;
7012 }
7013
François Gaffie11d30102018-11-02 16:09:09 +01007014 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007015
Eric Laurente552edb2014-03-10 17:42:56 -07007016 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007017 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007018 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007019 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007020 PatchBuilder patchBuilder;
7021 patchBuilder.addSource(outputDesc);
7022 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7023 for (const auto &filteredDevice : filteredDevices) {
7024 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007025 }
7026
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007027 // Add half reported latency to delayMs when muteWaitMs is null in order
7028 // to avoid disordered sequence of muting volume and changing devices.
7029 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7030 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007031 }
Eric Laurente552edb2014-03-10 17:42:56 -07007032
7033 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007034 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007035
7036 return muteWaitMs;
7037}
7038
Eric Laurentc75307b2015-03-17 15:29:32 -07007039status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007040 int delayMs,
7041 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007042{
Eric Laurent6a94d692014-05-20 11:18:06 -07007043 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007044 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7045 return INVALID_OPERATION;
7046 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007047 if (patchHandle) {
7048 index = mAudioPatches.indexOfKey(*patchHandle);
7049 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007050 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007051 }
7052 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007053 return INVALID_OPERATION;
7054 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007055 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007056 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007057 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007058 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007059 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007060 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007061 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007062 return status;
7063}
7064
7065status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007066 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007067 bool force,
7068 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007069{
7070 status_t status = NO_ERROR;
7071
Eric Laurent1f2f2232014-06-02 12:01:23 -07007072 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007073 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7074 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007075
François Gaffie11d30102018-11-02 16:09:09 +01007076 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007077 PatchBuilder patchBuilder;
7078 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007079 // AUDIO_SOURCE_HOTWORD is for internal use only:
7080 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007081 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7082 auto result = usecase;
7083 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7084 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7085 }
7086 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007087 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007088 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007089 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007090 }
7091 }
7092 return status;
7093}
7094
Eric Laurent6a94d692014-05-20 11:18:06 -07007095status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7096 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007097{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007098 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007099 ssize_t index;
7100 if (patchHandle) {
7101 index = mAudioPatches.indexOfKey(*patchHandle);
7102 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007103 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007104 }
7105 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007106 return INVALID_OPERATION;
7107 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007108 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007109 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007110 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007111 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007112 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007113 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007114 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007115 return status;
7116}
7117
François Gaffie11d30102018-11-02 16:09:09 +01007118sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007119 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007120 audio_format_t& format,
7121 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007122 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007123{
7124 // Choose an input profile based on the requested capture parameters: select the first available
7125 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007126 //
7127 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7128 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007129
Glenn Kasten730b9262018-03-29 15:01:26 -07007130 sp<IOProfile> firstInexact;
7131 uint32_t updatedSamplingRate = 0;
7132 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7133 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007134 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007135 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007136 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007137 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007138 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007139 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007140 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007141 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007142 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007143 &channelMask /*updatedChannelMask*/,
7144 // FIXME ugly cast
7145 (audio_output_flags_t) flags,
7146 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007147 return profile;
7148 }
François Gaffie11d30102018-11-02 16:09:09 +01007149 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007150 samplingRate,
7151 &updatedSamplingRate,
7152 format,
7153 &updatedFormat,
7154 channelMask,
7155 &updatedChannelMask,
7156 // FIXME ugly cast
7157 (audio_output_flags_t) flags,
7158 false /*exactMatchRequiredForInputFlags*/)) {
7159 firstInexact = profile;
7160 }
7161
Eric Laurente552edb2014-03-10 17:42:56 -07007162 }
7163 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007164 if (firstInexact != nullptr) {
7165 samplingRate = updatedSamplingRate;
7166 format = updatedFormat;
7167 channelMask = updatedChannelMask;
7168 return firstInexact;
7169 }
Eric Laurente552edb2014-03-10 17:42:56 -07007170 return NULL;
7171}
7172
François Gaffieaaac0fd2018-11-22 17:56:39 +01007173float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7174 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007175 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007176 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007177{
jiabin9a3361e2019-10-01 09:38:30 -07007178 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007179
7180 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7181 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7182 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7183 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007184 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7185 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7186 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7187 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7188 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007189
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007190 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007191 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7192 mOutputs.isActive(ringVolumeSrc, 0)) {
7193 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007194 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007195 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007196 }
7197
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007198 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007199 if ((volumeSource != callVolumeSrc && (isInCall() ||
7200 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007201 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007202 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7203 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007204 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7205 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7206 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007207 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007208 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007209 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007210 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007211 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007212 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007213 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7214 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7215 // programmatically muted.
7216 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7217 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7218 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007219 bool exemptFromCapping =
7220 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7221 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007222 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7223 volumeSource, volumeDb);
7224 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007225 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7226 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7227 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007228 }
7229 }
Eric Laurente552edb2014-03-10 17:42:56 -07007230 // if a headset is connected, apply the following rules to ring tones and notifications
7231 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007232 // - always attenuate notifications volume by 6dB
7233 // - attenuate ring tones volume by 6dB unless music is not playing and
7234 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007235 // - if music is playing, always limit the volume to current music volume,
7236 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007237 if (!Intersection(deviceTypes,
7238 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7239 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007240 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7241 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007242 ((volumeSource == alarmVolumeSrc ||
7243 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007244 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7245 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7246 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007247 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7248 curves.canBeMuted()) {
7249
Eric Laurente552edb2014-03-10 17:42:56 -07007250 // when the phone is ringing we must consider that music could have been paused just before
7251 // by the music application and behave as if music was active if the last music track was
7252 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007253 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007254 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007255 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007256 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007257 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7258 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007259 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007260 float musicVolDb = computeVolume(musicCurves,
7261 musicVolumeSrc,
7262 musicCurves.getVolumeIndex(musicDevice),
7263 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007264 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7265 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7266 if (volumeDb > minVolDb) {
7267 volumeDb = minVolDb;
7268 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007269 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007270 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7271 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7272 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007273 // on A2DP, also ensure notification volume is not too low compared to media when
7274 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007275 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007276 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007277 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7278 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007279 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7280 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007281 }
7282 }
jiabin9a3361e2019-10-01 09:38:30 -07007283 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007284 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007285 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007286 }
7287 }
7288
François Gaffie43c73442018-11-08 08:21:55 +01007289 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007290}
7291
Eric Laurent3839bc02018-07-10 18:33:34 -07007292int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007293 VolumeSource fromVolumeSource,
7294 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007295{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007296 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007297 return srcIndex;
7298 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007299 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7300 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007301 float minSrc = (float)srcCurves.getVolumeIndexMin();
7302 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7303 float minDst = (float)dstCurves.getVolumeIndexMin();
7304 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007305
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007306 // preserve mute request or correct range
7307 if (srcIndex < minSrc) {
7308 if (srcIndex == 0) {
7309 return 0;
7310 }
7311 srcIndex = minSrc;
7312 } else if (srcIndex > maxSrc) {
7313 srcIndex = maxSrc;
7314 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007315 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7316}
7317
François Gaffieaaac0fd2018-11-22 17:56:39 +01007318status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7319 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007320 int index,
7321 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007322 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007323 int delayMs,
7324 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007325{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007326 // do not change actual attributes volume if the attributes is muted
7327 if (outputDesc->isMuted(volumeSource)) {
7328 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7329 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007330 return NO_ERROR;
7331 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007332 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7333 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7334 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7335 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007336
Eric Laurent2517af32020-11-25 15:31:27 +01007337 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007338 bool isHAUsed = isHearingAidUsedForComm();
7339
Eric Laurente552edb2014-03-10 17:42:56 -07007340 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007341 // if sco and call follow same curves, bypass forceUseForComm
7342 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007343 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007344 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007345 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007346 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007347 // Do not return an error here as AudioService will always set both voice call
7348 // and bluetooth SCO volumes due to stream aliasing.
7349 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007350 }
jiabin9a3361e2019-10-01 09:38:30 -07007351 if (deviceTypes.empty()) {
7352 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007353 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007354
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007355 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7356 ALOGE("invalid volume index range");
7357 return BAD_VALUE;
7358 }
7359
jiabin9a3361e2019-10-01 09:38:30 -07007360 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7361 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007362 // Force VoIP volume to max for bluetooth SCO device except if muted
7363 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007364 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007365 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007366 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007367 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007368 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007369 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007370
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007371 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007372 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007373 // 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 +01007374 if (isVoiceVolSrc) {
7375 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007376 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007377 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007378 }
Eric Laurent18fba842016-03-31 14:41:26 -07007379 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007380 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7381 mLastVoiceVolume = voiceVolume;
7382 }
7383 }
Eric Laurente552edb2014-03-10 17:42:56 -07007384 return NO_ERROR;
7385}
7386
Eric Laurentc75307b2015-03-17 15:29:32 -07007387void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007388 const DeviceTypeSet& deviceTypes,
7389 int delayMs,
7390 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007391{
jiabincd510522020-01-22 09:40:55 -08007392 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007393 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7394 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7395 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007396 curves.getVolumeIndex(deviceTypes),
7397 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007398 }
7399}
7400
François Gaffiec005e562018-11-06 15:04:49 +01007401void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7402 bool on,
7403 const sp<AudioOutputDescriptor>& outputDesc,
7404 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007405 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007406{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007407 std::vector<VolumeSource> sourcesToMute;
7408 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7409 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7410 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007411 VolumeSource source = toVolumeSource(attributes, false);
7412 if ((source != VOLUME_SOURCE_NONE) &&
7413 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7414 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007415 sourcesToMute.push_back(source);
7416 }
Eric Laurente552edb2014-03-10 17:42:56 -07007417 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007418 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007419 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007420 }
7421
Eric Laurente552edb2014-03-10 17:42:56 -07007422}
7423
François Gaffieaaac0fd2018-11-22 17:56:39 +01007424void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7425 bool on,
7426 const sp<AudioOutputDescriptor>& outputDesc,
7427 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007428 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007429{
jiabin9a3361e2019-10-01 09:38:30 -07007430 if (deviceTypes.empty()) {
7431 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007432 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007433 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007434 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007435 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007436 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007437 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007438 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7439 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007440 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007441 }
7442 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007443 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7444 // ignored
7445 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007446 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007447 if (!outputDesc->isMuted(volumeSource)) {
7448 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007449 return;
7450 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007451 if (outputDesc->decMuteCount(volumeSource) == 0) {
7452 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007453 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007454 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007455 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007456 delayMs);
7457 }
7458 }
7459}
7460
François Gaffie53615e22015-03-19 09:24:12 +01007461bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7462{
François Gaffiec005e562018-11-06 15:04:49 +01007463 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007464 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7465 return true;
7466 }
7467
7468 // has known usage?
7469 switch (paa->usage) {
7470 case AUDIO_USAGE_UNKNOWN:
7471 case AUDIO_USAGE_MEDIA:
7472 case AUDIO_USAGE_VOICE_COMMUNICATION:
7473 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7474 case AUDIO_USAGE_ALARM:
7475 case AUDIO_USAGE_NOTIFICATION:
7476 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7477 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7478 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7479 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7480 case AUDIO_USAGE_NOTIFICATION_EVENT:
7481 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7482 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7483 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7484 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007485 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007486 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007487 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007488 case AUDIO_USAGE_EMERGENCY:
7489 case AUDIO_USAGE_SAFETY:
7490 case AUDIO_USAGE_VEHICLE_STATUS:
7491 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007492 break;
7493 default:
7494 return false;
7495 }
7496 return true;
7497}
7498
François Gaffie2110e042015-03-24 08:41:51 +01007499audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7500{
7501 return mEngine->getForceUse(usage);
7502}
7503
Eric Laurent96d1dda2022-03-14 17:14:19 +01007504bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007505 return isStateInCall(mEngine->getPhoneState());
7506}
7507
Eric Laurent96d1dda2022-03-14 17:14:19 +01007508bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007509 return is_state_in_call(state);
7510}
7511
Eric Laurent74b71512019-11-06 17:21:57 -08007512bool AudioPolicyManager::isCallAudioAccessible()
7513{
7514 audio_mode_t mode = mEngine->getPhoneState();
7515 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007516 || (mode == AUDIO_MODE_CALL_SCREEN)
7517 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007518}
7519
Eric Laurentd60560a2015-04-10 11:31:20 -07007520void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7521{
7522 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007523 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007524 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007525 sourceDesc->sinkDevice()->equals(deviceDesc))
7526 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007527 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007528 }
7529 }
7530
7531 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7532 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7533 bool release = false;
7534 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7535 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7536 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7537 source->ext.device.type == deviceDesc->type()) {
7538 release = true;
7539 }
7540 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007541 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007542 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7543 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7544 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007545 sink->ext.device.type == deviceDesc->type() &&
7546 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7547 || strncmp(sink->ext.device.address, address,
7548 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007549 release = true;
7550 }
7551 }
7552 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007553 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7554 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007555 }
7556 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007557
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007558 mInputs.clearSessionRoutesForDevice(deviceDesc);
7559
Francois Gaffie716e1432019-01-14 16:58:59 +01007560 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007561}
7562
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007563void AudioPolicyManager::modifySurroundFormats(
7564 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007565 std::unordered_set<audio_format_t> enforcedSurround(
7566 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007567 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7568 for (const auto& pair : mConfig.getSurroundFormats()) {
7569 allSurround.insert(pair.first);
7570 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7571 }
Phil Burk09bc4612016-02-24 15:58:15 -08007572
7573 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7574 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007575 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007576 // This is the resulting set of formats depending on the surround mode:
7577 // 'all surround' = allSurround
7578 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7579 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7580 // 'manual surround' = mManualSurroundFormats
7581 // AUTO: formats v 'enforced surround'
7582 // ALWAYS: formats v 'all surround' v 'enforced surround'
7583 // NEVER: formats ^ 'non-surround'
7584 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007585
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007586 std::unordered_set<audio_format_t> formatSet;
7587 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7588 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007589 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007590 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007591 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007592 formatSet.insert(*formatIter);
7593 }
7594 }
7595 } else {
7596 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7597 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007598 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007599
jiabin81772902018-04-02 17:52:27 -07007600 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007601 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007602 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7603 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7604 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007605 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007606 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7607 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7608 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007609 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007610 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007611 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007612 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007613 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007614 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007615}
7616
jiabin06e4bab2019-07-29 10:13:34 -07007617void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7618 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007619 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7620 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7621
7622 // If NEVER, then remove support for channelMasks > stereo.
7623 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007624 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7625 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007626 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007627 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007628 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007629 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007630 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007631 }
7632 }
jiabin81772902018-04-02 17:52:27 -07007633 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7634 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7635 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007636 bool supports5dot1 = false;
7637 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007638 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007639 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7640 supports5dot1 = true;
7641 break;
7642 }
7643 }
7644 // If not then add 5.1 support.
7645 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007646 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007647 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007648 }
Phil Burk09bc4612016-02-24 15:58:15 -08007649 }
7650}
7651
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007652void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007653 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007654 AudioProfileVector &profiles)
7655{
7656 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007657 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007658
François Gaffie112b0af2015-11-19 16:13:25 +01007659 // Format MUST be checked first to update the list of AudioProfile
7660 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007661 reply = mpClientInterface->getParameters(
7662 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007663 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007664 AudioParameter repliedParameters(reply);
7665 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007666 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007667 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7668 return;
7669 }
Phil Burk09bc4612016-02-24 15:58:15 -08007670 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007671 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007672 if (device == AUDIO_DEVICE_OUT_HDMI
7673 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007674 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007675 }
jiabin3e277cc2019-09-10 14:27:34 -07007676 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007677 }
François Gaffie112b0af2015-11-19 16:13:25 +01007678
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007679 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007680 ChannelMaskSet channelMasks;
7681 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007682 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007683 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007684
7685 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007686 reply = mpClientInterface->getParameters(
7687 ioHandle,
7688 requestedParameters.toString() + ";" +
7689 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007690 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007691 AudioParameter repliedParameters(reply);
7692 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007693 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007694 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007695 }
7696 }
7697 if (profiles.hasDynamicChannelsFor(format)) {
7698 reply = mpClientInterface->getParameters(ioHandle,
7699 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007700 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007701 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007702 AudioParameter repliedParameters(reply);
7703 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007704 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007705 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007706 if (device == AUDIO_DEVICE_OUT_HDMI
7707 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007708 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007709 }
François Gaffie112b0af2015-11-19 16:13:25 +01007710 }
7711 }
jiabin3e277cc2019-09-10 14:27:34 -07007712 addDynamicAudioProfileAndSort(
7713 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007714 }
7715}
Eric Laurentd60560a2015-04-10 11:31:20 -07007716
Mikhail Naganovdc769682018-05-04 15:34:08 -07007717status_t AudioPolicyManager::installPatch(const char *caller,
7718 audio_patch_handle_t *patchHandle,
7719 AudioIODescriptorInterface *ioDescriptor,
7720 const struct audio_patch *patch,
7721 int delayMs)
7722{
7723 ssize_t index = mAudioPatches.indexOfKey(
7724 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7725 *patchHandle : ioDescriptor->getPatchHandle());
7726 sp<AudioPatch> patchDesc;
7727 status_t status = installPatch(
7728 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7729 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007730 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007731 }
7732 return status;
7733}
7734
7735status_t AudioPolicyManager::installPatch(const char *caller,
7736 ssize_t index,
7737 audio_patch_handle_t *patchHandle,
7738 const struct audio_patch *patch,
7739 int delayMs,
7740 uid_t uid,
7741 sp<AudioPatch> *patchDescPtr)
7742{
7743 sp<AudioPatch> patchDesc;
7744 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7745 if (index >= 0) {
7746 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007747 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007748 }
7749
7750 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7751 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7752 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7753 if (status == NO_ERROR) {
7754 if (index < 0) {
7755 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007756 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007757 } else {
7758 patchDesc->mPatch = *patch;
7759 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007760 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007761 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007762 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007763 }
7764 nextAudioPortGeneration();
7765 mpClientInterface->onAudioPatchListUpdate();
7766 }
7767 if (patchDescPtr) *patchDescPtr = patchDesc;
7768 return status;
7769}
7770
jiabinbce0c1d2020-10-05 11:20:18 -07007771bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7772{
7773 const TrackClientVector activeClients = output->getActiveClients();
7774 if (activeClients.empty()) {
7775 return true;
7776 }
7777 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7778 if (index < 0) {
7779 ALOGE("%s, no audio patch found while there are active clients on output %d",
7780 __func__, output->getId());
7781 return false;
7782 }
7783 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7784 DeviceVector routedDevices;
7785 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7786 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7787 patchDesc->mPatch.sinks[i].id);
7788 if (device == nullptr) {
7789 ALOGE("%s, no audio device found with id(%d)",
7790 __func__, patchDesc->mPatch.sinks[i].id);
7791 return false;
7792 }
7793 routedDevices.add(device);
7794 }
7795 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007796 if (client->isInvalid()) {
7797 // No need to take care about invalidated clients.
7798 continue;
7799 }
jiabinbce0c1d2020-10-05 11:20:18 -07007800 sp<DeviceDescriptor> preferredDevice =
7801 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7802 if (mEngine->getOutputDevicesForAttributes(
7803 client->attributes(), preferredDevice, false) == routedDevices) {
7804 return false;
7805 }
7806 }
7807 return true;
7808}
7809
7810sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007811 const sp<IOProfile>& profile, const DeviceVector& devices,
7812 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007813{
7814 for (const auto& device : devices) {
7815 // TODO: This should be checking if the profile supports the device combo.
7816 if (!profile->supportsDevice(device)) {
7817 return nullptr;
7818 }
7819 }
7820 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7821 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007822 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007823 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7824 if (status != NO_ERROR) {
7825 return nullptr;
7826 }
7827
7828 // Here is where the out_set_parameters() for card & device gets called
7829 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7830 const audio_devices_t deviceType = device->type();
7831 const String8 &address = String8(device->address().c_str());
7832 if (!address.isEmpty()) {
7833 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7834 mpClientInterface->setParameters(output, String8(param));
7835 free(param);
7836 }
7837 updateAudioProfiles(device, output, profile->getAudioProfiles());
7838 if (!profile->hasValidAudioProfile()) {
7839 ALOGW("%s() missing param", __func__);
7840 desc->close();
7841 return nullptr;
7842 } else if (profile->hasDynamicAudioProfile()) {
7843 desc->close();
7844 output = AUDIO_IO_HANDLE_NONE;
7845 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7846 profile->pickAudioProfile(
7847 config.sample_rate, config.channel_mask, config.format);
7848 config.offload_info.sample_rate = config.sample_rate;
7849 config.offload_info.channel_mask = config.channel_mask;
7850 config.offload_info.format = config.format;
7851
Eric Laurentb4f42a92022-01-17 17:37:31 +01007852 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007853 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7854 if (status != NO_ERROR) {
7855 return nullptr;
7856 }
7857 }
7858
7859 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007860
baek.kim -61c20122022-07-27 10:05:32 +00007861 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7862 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7863
jiabinbce0c1d2020-10-05 11:20:18 -07007864 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7865 sp<AudioPolicyMix> policyMix;
7866 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7867 policyMix->setOutput(desc);
7868 desc->mPolicyMix = policyMix;
7869 } else {
7870 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7871 address.string());
7872 }
7873
baek.kim -61c20122022-07-27 10:05:32 +00007874 } else if (hasPrimaryOutput() && speaker != nullptr
7875 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007876 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7877 // no duplicated output for:
7878 // - direct outputs
7879 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007880 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007881 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7882
7883 //TODO: configure audio effect output stage here
7884
7885 // open a duplicating output thread for the new output and the primary output
7886 sp<SwAudioOutputDescriptor> dupOutputDesc =
7887 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7888 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7889 if (status == NO_ERROR) {
7890 // add duplicated output descriptor
7891 addOutput(duplicatedOutput, dupOutputDesc);
7892 } else {
7893 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7894 mPrimaryOutput->mIoHandle, output);
7895 desc->close();
7896 removeOutput(output);
7897 nextAudioPortGeneration();
7898 return nullptr;
7899 }
7900 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007901 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7902 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7903 mPrimaryOutput = desc;
7904 }
jiabinbce0c1d2020-10-05 11:20:18 -07007905 return desc;
7906}
7907
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007908} // namespace android