blob: 340a6b61415050369fdd218ef56b03d2b6bdadc5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
jiabin06e4bab2019-07-29 10:13:34 -070071template <typename T>
72bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
73{
74 if (left.size() != right.size()) {
75 return false;
76 }
77 for (size_t index = 0; index < right.size(); index++) {
78 if (left[index] != right[index]) {
79 return false;
80 }
81 }
82 return true;
83}
84
85template <typename T>
86bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 return !(left == right);
89}
90
Eric Laurente552edb2014-03-10 17:42:56 -070091// ----------------------------------------------------------------------------
92// AudioPolicyInterface implementation
93// ----------------------------------------------------------------------------
94
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010095status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
96 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
97 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -080098 nextAudioPortGeneration();
99 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800100}
101
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100102status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
103 audio_policy_dev_state_t state,
104 const char* device_address,
105 const char* device_name,
106 audio_format_t encodedFormat) {
Atneya Nairc18e9a12022-12-18 16:45:15 -0800107 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100108 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
109 status == OK) {
110 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
111 } else {
112 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
113 return status;
114 }
115}
116
François Gaffie11d30102018-11-02 16:09:09 +0100117void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
118 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200119{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000120 audio_port_v7 devicePort;
121 device->toAudioPort(&devicePort);
122 if (status_t status = mpClientInterface->setDeviceConnectedState(
123 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
124 status != OK) {
125 ALOGE("Error %d while setting connected state for device %s", status,
126 device->getDeviceTypeAddr().toString(false).c_str());
127 }
François Gaffie44481e72016-04-20 07:49:57 +0200128}
129
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100130status_t AudioPolicyManager::setDeviceConnectionStateInt(
131 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
132 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133 if (port.ext.getTag() != AudioPortExt::device) {
134 return BAD_VALUE;
135 }
136 audio_devices_t device_type;
137 std::string device_address;
138 if (status_t status = aidl2legacy_AudioDevice_audio_device(
139 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
140 status != OK) {
141 return status;
142 };
143 const char* device_name = port.name.c_str();
144 // connect/disconnect only 1 device at a time
145 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
146 return BAD_VALUE;
147
148 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
149 device_type, device_address.c_str(), device_name, encodedFormat,
150 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganov0566bac2022-06-11 00:47:52 +0000151 if (device == nullptr) {
152 return INVALID_OPERATION;
153 }
154 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
155 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
156 }
157 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100158}
159
François Gaffie11d30102018-11-02 16:09:09 +0100160status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800161 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100162 const char* device_address,
163 const char* device_name,
164 audio_format_t encodedFormat) {
Atneya Nairc18e9a12022-12-18 16:45:15 -0800165 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
167 status == OK) {
168 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
169 } else {
170 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
171 return status;
172 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700173}
Paul McLeane743a472015-01-28 11:07:31 -0800174
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700175status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
176 audio_policy_dev_state_t state)
177{
Eric Laurente552edb2014-03-10 17:42:56 -0700178 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700180 SortedVector <audio_io_handle_t> outputs;
181
François Gaffie11d30102018-11-02 16:09:09 +0100182 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700183
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // save a copy of the opened output descriptors before any output is opened or closed
185 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
186 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100187
188 bool wasLeUnicastActive = isLeUnicastActive();
189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 switch (state)
191 {
192 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800193 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100195 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700196 return INVALID_OPERATION;
197 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800198 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700199 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700200
Eric Laurente552edb2014-03-10 17:42:56 -0700201 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200202 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700204 }
205
François Gaffie44481e72016-04-20 07:49:57 +0200206 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
207 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100208 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200209
François Gaffie11d30102018-11-02 16:09:09 +0100210 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
211 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200212
Francois Gaffie716e1432019-01-14 16:58:59 +0100213 mHwModules.cleanUpForDevice(device);
214
François Gaffie11d30102018-11-02 16:09:09 +0100215 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700216 return INVALID_OPERATION;
217 }
François Gaffie2110e042015-03-24 08:41:51 +0100218
jiabin1c4794b2020-05-05 10:08:05 -0700219 // Populate encapsulation information when a output device is connected.
220 device->setEncapsulationInfoFromHal(mpClientInterface);
221
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 // outputs should never be empty here
223 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
224 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100225 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800226
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700229 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700230 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700232 return INVALID_OPERATION;
233 }
234
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700236
Paul McLeane743a472015-01-28 11:07:31 -0800237 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100238 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Eric Laurente552edb2014-03-10 17:42:56 -0700240 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100241 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700242
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100243 mOutputs.clearSessionRoutesForDevice(device);
244
François Gaffie11d30102018-11-02 16:09:09 +0100245 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100246
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800247 // Reset active device codec
248 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
249
Kriti Dangef6be8f2020-11-05 11:58:19 +0100250 // remove device from mReportedFormatsMap cache
251 mReportedFormatsMap.erase(device);
252
Eric Laurente552edb2014-03-10 17:42:56 -0700253 } break;
254
255 default:
François Gaffie11d30102018-11-02 16:09:09 +0100256 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700257 return BAD_VALUE;
258 }
259
Eric Laurent736a1022019-03-27 18:28:46 -0700260 // Propagate device availability to Engine
261 setEngineDeviceConnectionState(device, state);
262
Eric Laurentae970022019-01-29 14:25:04 -0800263 // No need to evaluate playback routing when connecting a remote submix
264 // output device used by a dynamic policy of type recorder as no
265 // playback use case is affected.
266 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700267 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800268 for (audio_io_handle_t output : outputs) {
269 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800270 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
271 if (policyMix != nullptr
272 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700273 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800274 doCheckForDeviceAndOutputChanges = false;
275 break;
276 }
277 }
278 }
279
280 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700281 // outputs must be closed after checkOutputForAllStrategies() is executed
282 if (!outputs.isEmpty()) {
283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100285 // close unused outputs after device disconnection or direct outputs that have
286 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200287 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200288 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
289 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200290 (desc->mDirectOpenCount == 0))
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
292 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent96d1dda2022-03-14 17:14:19 +0100356 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
357
Eric Laurent72aa32f2014-05-30 18:51:48 -0700358 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700359 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700360 } // end if is output device
361
Eric Laurente552edb2014-03-10 17:42:56 -0700362 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700363 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100364 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700365 switch (state)
366 {
367 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700368 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700369 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700371 return INVALID_OPERATION;
372 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700373
374 if (mAvailableInputDevices.add(device) < 0) {
375 return NO_MEMORY;
376 }
377
François Gaffie44481e72016-04-20 07:49:57 +0200378 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
379 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100380 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200381
Eric Laurent0dd51852019-04-19 18:18:58 -0700382 if (checkInputsForDevice(device, state) != NO_ERROR) {
383 mAvailableInputDevices.remove(device);
384
François Gaffie11d30102018-11-02 16:09:09 +0100385 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100386
387 mHwModules.cleanUpForDevice(device);
388
Eric Laurentd4692962014-05-05 18:13:44 -0700389 return INVALID_OPERATION;
390 }
391
Eric Laurentd4692962014-05-05 18:13:44 -0700392 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700393
394 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700395 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700396 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100397 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700398 return INVALID_OPERATION;
399 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700402
403 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100404 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700405
François Gaffie11d30102018-11-02 16:09:09 +0100406 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700407
408 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100409
410 // remove device from mReportedFormatsMap cache
411 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700412 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700413
414 default:
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return BAD_VALUE;
417 }
418
Eric Laurent736a1022019-03-27 18:28:46 -0700419 // Propagate device availability to Engine
420 setEngineDeviceConnectionState(device, state);
421
Eric Laurent0dd51852019-04-19 18:18:58 -0700422 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700423 // As the input device list can impact the output device selection, update
424 // getDeviceForStrategy() cache
425 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700426
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100427 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200428 // Reconnect Audio Source
429 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
430 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
431 checkAudioSourceForAttributes(attributes);
432 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100434 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700435 }
436
Eric Laurentb52c1522014-05-20 11:27:36 -0700437 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700439 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700440
François Gaffie11d30102018-11-02 16:09:09 +0100441 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700442 return BAD_VALUE;
443}
444
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100445status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
446 const char* device_name,
Atneya Nairc18e9a12022-12-18 16:45:15 -0800447 media::AudioPortFw* aidlPort) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100448 DeviceDescriptorBase devDescr(device, device_address);
449 devDescr.setName(device_name);
450 return devDescr.writeToParcelable(aidlPort);
451}
452
Eric Laurent736a1022019-03-27 18:28:46 -0700453void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
454 audio_policy_dev_state_t state) {
455
456 // the Engine does not have to know about remote submix devices used by dynamic audio policies
457 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
458 return;
459 }
460 mEngine->setDeviceConnectionState(device, state);
461}
462
463
Eric Laurente0720872014-03-11 09:30:41 -0700464audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100465 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700466{
Eric Laurent634b7142016-04-20 13:48:02 -0700467 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800468 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
469 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700470 (strlen(device_address) != 0)/*matchAddress*/);
471
472 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100473 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700474 device, device_address);
475 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
476 }
François Gaffie53615e22015-03-19 09:24:12 +0100477
Eric Laurent3a4311c2014-03-17 12:00:47 -0700478 DeviceVector *deviceVector;
479
Eric Laurente552edb2014-03-10 17:42:56 -0700480 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700482 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700483 deviceVector = &mAvailableInputDevices;
484 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100485 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700486 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700487 }
Eric Laurent634b7142016-04-20 13:48:02 -0700488
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800489 return (deviceVector->getDevice(
490 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700491 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800492}
493
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800494status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
495 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800496 const char *device_name,
497 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800498{
499 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700500 String8 reply;
501 AudioParameter param;
502 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800503
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800504 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
505 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800506
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800507 // connect/disconnect only 1 device at a time
508 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
509
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700511 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513 // Nothing to do: device is not connected
514 return NO_ERROR;
515 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700518 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 // configure codecs.
520 // Handle two specific cases by sending a set parameter to
521 // configure A2DP codecs. No need to toggle device state.
522 // Case 1: A2DP active device switches from primary to primary
523 // module
524 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200525 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700526 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
528 if (availablePrimaryOutputDevices().contains(devDesc) &&
529 (module != 0 && module->getHandle() == primaryHandle)) {
530 reply = mpClientInterface->getParameters(
531 AUDIO_IO_HANDLE_NONE,
532 String8(AudioParameter::keyReconfigA2dpSupported));
533 AudioParameter repliedParameters(reply);
534 repliedParameters.getInt(
535 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
536 if (isReconfigA2dpSupported) {
537 const String8 key(AudioParameter::keyReconfigA2dp);
538 param.add(key, String8("true"));
539 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
540 devDesc->setEncodedFormat(encodedFormat);
541 return NO_ERROR;
542 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700543 }
544 }
cnx421bd2dcc42020-07-11 14:58:44 +0800545 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
546 for (size_t i = 0; i < mOutputs.size(); i++) {
547 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
548 // mute media strategies and delay device switch by the largest
549 // This avoid sending the music tail into the earpiece or headset.
550 setStrategyMute(musicStrategy, true, desc);
551 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
552 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
553 nullptr, true /*fromCache*/).types());
554 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800555 // Toggle the device state: UNAVAILABLE -> AVAILABLE
556 // This will force reading again the device configuration
557 status = setDeviceConnectionState(device,
558 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800559 device_address, device_name,
560 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561 if (status != NO_ERROR) {
562 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
563 status);
564 return status;
565 }
566
567 status = setDeviceConnectionState(device,
568 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800569 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 if (status != NO_ERROR) {
571 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
572 status);
573 return status;
574 }
575
576 return NO_ERROR;
577}
578
Pattydd807582021-11-04 21:01:03 +0800579status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
580 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581{
Pattydd807582021-11-04 21:01:03 +0800582 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800583 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800584 std::unordered_set<audio_format_t> formatSet;
585 sp<HwModule> primaryModule =
586 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700587 if (primaryModule == nullptr) {
588 ALOGE("%s() unable to get primary module", __func__);
589 return NO_INIT;
590 }
Pattydd807582021-11-04 21:01:03 +0800591
592 DeviceTypeSet audioDeviceSet;
593
594 switch(device) {
595 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
596 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
597 break;
598 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huangf5082dd2022-07-06 00:14:12 +0800599 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
600 break;
601 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
602 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800603 break;
604 default:
605 ALOGE("%s() device type 0x%08x not supported", __func__, device);
606 return BAD_VALUE;
607 }
608
jiabin9a3361e2019-10-01 09:38:30 -0700609 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800610 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800611 for (const auto& device : declaredDevices) {
612 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800613 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800615 return status;
616}
617
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100618DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
619{
620 DeviceVector rxSinkdevices{};
621 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
622 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
623 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
624 auto rxSinkDevice = rxSinkdevices.itemAt(0);
625 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
626 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
627 // retrieve Rx Source device descriptor
628 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
630
631 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
632 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
633 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
634 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
635 return DeviceVector(rxSinkDevice);
636 }
637 }
638 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
639 // the device returned is not necessarily reachable via this output
640 // (filter later by setOutputDevices())
641 return getNewOutputDevices(mPrimaryOutput, fromCache);
642}
643
644status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
645{
646 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
647 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
648 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
649 }
650 return INVALID_OPERATION;
651}
652
653status_t AudioPolicyManager::updateCallRoutingInternal(
654 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700655{
656 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100657 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700658 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700659 if(!hasPrimaryOutput() ||
660 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100661 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700662 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100664
Francois Gaffie716e1432019-01-14 16:58:59 +0100665 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100666 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100668
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100669 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100670 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671
Francois Gaffie601801d2021-06-22 13:27:39 +0200672 disconnectTelephonyAudioSource(mCallRxSourceClient);
673 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
François Gaffie9eb18552018-11-05 10:33:26 +0100675 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700676 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100677 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700678 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100679 // retrieve Rx Source and Tx Sink device descriptors
680 sp<DeviceDescriptor> rxSourceDevice =
681 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
682 String8(),
683 AUDIO_FORMAT_DEFAULT);
684 sp<DeviceDescriptor> txSinkDevice =
685 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
686 String8(),
687 AUDIO_FORMAT_DEFAULT);
688
689 // RX and TX Telephony device are declared by Primary Audio HAL
690 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
691 (telephonyRxModule->getHalVersionMajor() >= 3)) {
692 if (rxSourceDevice == 0 || txSinkDevice == 0) {
693 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGE("%s() no telephony Tx and/or RX device", __func__);
695 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100696 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100697 // createAudioPatchInternal now supports both HW / SW bridging
698 createRxPatch = true;
699 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100700 } else {
701 // If the RX device is on the primary HW module, then use legacy routing method for
702 // voice calls via setOutputDevice() on primary output.
703 // Otherwise, create two audio patches for TX and RX path.
704 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
705 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700706 // If the TX device is also on the primary HW module, setOutputDevice() will take care
707 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100708 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
709 (txSinkDevice != 0);
710 }
711 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
712 // Otherwise, create two audio patches for TX and RX path.
713 if (!createRxPatch) {
714 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700715 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200716 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800717 // If the TX device is on the primary HW module but RX device is
718 // on other HW module, SinkMetaData of telephony input should handle it
719 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700720 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700721 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100722 // terminate active capture if on the same HW module as the call TX source device
723 // FIXME: would be better to refine to only inputs whose profile connects to the
724 // call TX device but this information is not in the audio patch and logic here must be
725 // symmetric to the one in startInput()
726 for (const auto& activeDesc : mInputs.getActiveInputs()) {
727 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
728 closeActiveClients(activeDesc);
729 }
730 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200731 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800732 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100733 if (waitMs != nullptr) {
734 *waitMs = muteWaitMs;
735 }
736 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800737}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738
Mikhail Naganov100f0122018-11-29 11:22:16 -0800739bool AudioPolicyManager::isDeviceOfModule(
740 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
741 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
742 if (module != 0) {
743 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
744 .indexOf(devDesc) != NAME_NOT_FOUND
745 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
746 .indexOf(devDesc) != NAME_NOT_FOUND;
747 }
748 return false;
749}
750
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200751void AudioPolicyManager::connectTelephonyRxAudioSource()
752{
Francois Gaffie601801d2021-06-22 13:27:39 +0200753 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754 const struct audio_port_config source = {
755 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
756 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
757 };
758 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200759 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
760 ALOGE_IF(mCallRxSourceClient == nullptr,
761 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200762}
763
Francois Gaffie601801d2021-06-22 13:27:39 +0200764void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765{
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 if (clientDesc == nullptr) {
767 return;
768 }
769 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
770 "%s error stopping audio source", __func__);
771 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200772}
773
774void AudioPolicyManager::connectTelephonyTxAudioSource(
775 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
776 uint32_t delayMs)
777{
Francois Gaffie601801d2021-06-22 13:27:39 +0200778 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779 if (srcDevice == nullptr || sinkDevice == nullptr) {
780 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
781 return;
782 }
783 PatchBuilder patchBuilder;
784 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
785 ALOGV("%s between source %s and sink %s", __func__,
786 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200787 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200788 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
789
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200790 struct audio_port_config source = {};
791 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 mCallTxSourceClient = new InternalSourceClientDescriptor(
793 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200794 mCommunnicationStrategy, toVolumeSource(aa));
795 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
796 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
798 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200799 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
800 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200801 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200802 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200803}
804
Eric Laurente0720872014-03-11 09:30:41 -0700805void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700806{
807 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100808 // store previous phone state for management of sonification strategy below
809 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100810 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100811
812 if (mEngine->setPhoneState(state) != NO_ERROR) {
813 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700814 return;
815 }
François Gaffie2110e042015-03-24 08:41:51 +0100816 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700817 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700818 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700819 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800820 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 }
822
François Gaffie2110e042015-03-24 08:41:51 +0100823 /**
824 * Switching to or from incall state or switching between telephony and VoIP lead to force
825 * routing command.
826 */
Eric Laurent74b71512019-11-06 17:21:57 -0800827 bool force = ((isStateInCall(oldState) != isStateInCall(state))
828 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700829
830 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700831 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700832
Eric Laurente552edb2014-03-10 17:42:56 -0700833 int delayMs = 0;
834 if (isStateInCall(state)) {
835 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100836 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
837 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700838 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700839 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 // mute media and sonification strategies and delay device switch by the largest
841 // latency of any output where either strategy is active.
842 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100843 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
844 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
845 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700846 (delayMs < (int)desc->latency()*2)) {
847 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700848 }
François Gaffiec005e562018-11-06 15:04:49 +0100849 setStrategyMute(musicStrategy, true, desc);
850 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
851 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
852 nullptr, true /*fromCache*/).types());
853 setStrategyMute(sonificationStrategy, true, desc);
854 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
855 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
856 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700857 }
858 }
859
Eric Laurent87ffa392015-05-22 10:32:38 -0700860 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700861 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100862 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700863 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100864 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
865 // force routing command to audio hardware when ending call
866 // even if no device change is needed
867 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
868 rxDevices = mPrimaryOutput->devices();
869 }
870 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200871 disconnectTelephonyAudioSource(mCallRxSourceClient);
872 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100873 }
François Gaffie11d30102018-11-02 16:09:09 +0100874 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700875 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700876 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700877
878 // reevaluate routing on all outputs in case tracks have been started during the call
879 for (size_t i = 0; i < mOutputs.size(); i++) {
880 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100881 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200882 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
883 bool forceRouting = !newDevices.isEmpty();
884 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
885 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700886 }
887 }
888
Eric Laurent96d1dda2022-03-14 17:14:19 +0100889 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
890
Eric Laurente552edb2014-03-10 17:42:56 -0700891 if (isStateInCall(state)) {
892 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700893 // force reevaluating accessibility routing when call starts
894 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700895 }
896
897 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100898 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
899 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700900}
901
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700902audio_mode_t AudioPolicyManager::getPhoneState() {
903 return mEngine->getPhoneState();
904}
905
Eric Laurente0720872014-03-11 09:30:41 -0700906void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100907 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700908{
François Gaffie2110e042015-03-24 08:41:51 +0100909 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700910 if (config == mEngine->getForceUse(usage)) {
911 return;
912 }
Eric Laurente552edb2014-03-10 17:42:56 -0700913
François Gaffie2110e042015-03-24 08:41:51 +0100914 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
915 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
916 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700917 }
François Gaffie2110e042015-03-24 08:41:51 +0100918 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
919 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
920 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700921
922 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700923 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800924
Eric Laurent22fcda22019-05-17 16:28:47 -0700925 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
926 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
927 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
928 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
929 }
930
Eric Laurentdc462862016-07-19 12:29:53 -0700931 //FIXME: workaround for truncated touch sounds
932 // to be removed when the problem is handled by system UI
933 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700934 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
935 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
936 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700937
938 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100939 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700940}
941
Eric Laurente0720872014-03-11 09:30:41 -0700942void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700943{
944 ALOGV("setSystemProperty() property %s, value %s", property, value);
945}
946
Dorin Drimusecc9f422022-03-09 17:57:40 +0100947// Find an MSD output profile compatible with the parameters passed.
948// When "directOnly" is set, restrict search to profiles for direct outputs.
949sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
950 const DeviceVector& devices,
951 uint32_t samplingRate,
952 audio_format_t format,
953 audio_channel_mask_t channelMask,
954 audio_output_flags_t flags,
955 bool directOnly)
956{
957 flags = getRelevantFlags(flags, directOnly);
958
959 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
960 if (msdModule != nullptr) {
961 // for the msd module check if there are patches to the output devices
962 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
963 HwModuleCollection modules;
964 modules.add(msdModule);
965 return searchCompatibleProfileHwModules(
966 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
967 flags, directOnly);
968 }
969 }
970 return nullptr;
971}
972
Michael Chana94fbb22018-04-24 14:31:19 +1000973// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
974// search to profiles for direct outputs.
975sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100976 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000977 uint32_t samplingRate,
978 audio_format_t format,
979 audio_channel_mask_t channelMask,
980 audio_output_flags_t flags,
981 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700982{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100983 flags = getRelevantFlags(flags, directOnly);
984
985 return searchCompatibleProfileHwModules(
986 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
987}
988
989audio_output_flags_t AudioPolicyManager::getRelevantFlags (
990 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000991 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100992 // only retain flags that will drive the direct output profile selection
993 // if explicitly requested
994 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000995 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100996 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
997 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000998 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100999 return flags;
1000}
Eric Laurent861a6282015-05-18 15:40:16 -07001001
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1003 const HwModuleCollection& hwModules,
1004 const DeviceVector& devices,
1005 uint32_t samplingRate,
1006 audio_format_t format,
1007 audio_channel_mask_t channelMask,
1008 audio_output_flags_t flags,
1009 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001010 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001011 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001012 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001013 if (!curProfile->isCompatibleProfile(devices,
1014 samplingRate, NULL /*updatedSamplingRate*/,
1015 format, NULL /*updatedFormat*/,
1016 channelMask, NULL /*updatedChannelMask*/,
1017 flags)) {
1018 continue;
1019 }
1020 // reject profiles not corresponding to a device currently available
1021 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1022 continue;
1023 }
1024 // reject profiles if connected device does not support codec
1025 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1026 continue;
1027 }
1028 if (!directOnly) {
1029 return curProfile;
1030 }
1031
1032 // when searching for direct outputs, if several profiles are compatible, give priority
1033 // to one with offload capability
Patty Huangf5082dd2022-07-06 00:14:12 +08001034 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001035 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001036 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 }
1038 profile = curProfile;
1039 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1040 break;
1041 }
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
1043 }
Eric Laurent861a6282015-05-18 15:40:16 -07001044 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001045}
1046
Eric Laurentfa0f6742021-08-17 18:39:44 +02001047sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001048 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001049{
1050 for (const auto& hwModule : mHwModules) {
1051 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001052 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001053 continue;
1054 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001055 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001056 // reject profiles not corresponding to a device currently available
1057 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1058 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1059 continue;
1060 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001061 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1062 != devices.size()) {
1063 continue;
1064 }
1065 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001066 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1067 return curProfile;
1068 }
1069 }
1070 return nullptr;
1071}
1072
Eric Laurentf4e63452017-11-06 19:31:46 +00001073audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001074{
François Gaffiec005e562018-11-06 15:04:49 +01001075 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001076
1077 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1078 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1079 // format, flags, etc. This may result in some discrepancy for functions that utilize
1080 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1081 // and AudioSystem::getOutputSamplingRate().
1082
François Gaffie11d30102018-11-02 16:09:09 +01001083 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001084 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001085
François Gaffie11d30102018-11-02 16:09:09 +01001086 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1087 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001088 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001089}
1090
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001091status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1092 const audio_attributes_t *srcAttr,
1093 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001094{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001095 if (srcAttr != NULL) {
1096 if (!isValidAttributes(srcAttr)) {
1097 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1098 __func__,
1099 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1100 srcAttr->tags);
1101 return BAD_VALUE;
1102 }
1103 *dstAttr = *srcAttr;
1104 } else {
1105 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1106 ALOGE("%s: invalid stream type", __func__);
1107 return BAD_VALUE;
1108 }
François Gaffiec005e562018-11-06 15:04:49 +01001109 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001111
1112 // Only honor audibility enforced when required. The client will be
1113 // forced to reconnect if the forced usage changes.
1114 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001115 dstAttr->flags = static_cast<audio_flags_mask_t>(
1116 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001117 }
1118
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001119 return NO_ERROR;
1120}
1121
Kevin Rocard153f92d2018-12-18 18:33:28 -08001122status_t AudioPolicyManager::getOutputForAttrInt(
1123 audio_attributes_t *resultAttr,
1124 audio_io_handle_t *output,
1125 audio_session_t session,
1126 const audio_attributes_t *attr,
1127 audio_stream_type_t *stream,
1128 uid_t uid,
1129 const audio_config_t *config,
1130 audio_output_flags_t *flags,
1131 audio_port_handle_t *selectedDeviceId,
1132 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001133 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001134 output_type_t *outputType,
1135 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136{
François Gaffiec005e562018-11-06 15:04:49 +01001137 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001138 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001139 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001140 const sp<DeviceDescriptor> requestedDevice =
1141 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1142
Eric Laurent8a1095a2019-11-08 14:44:16 -08001143 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001144 *isSpatialized = false;
1145
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001146 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1147 if (status != NO_ERROR) {
1148 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001149 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001150 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001151 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001152 }
François Gaffiec005e562018-11-06 15:04:49 +01001153 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001154
François Gaffiec005e562018-11-06 15:04:49 +01001155 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1156 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001157
Kevin Rocard153f92d2018-12-18 18:33:28 -08001158 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1159 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1160 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001161 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001162 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1163 .channel_mask = config->channel_mask,
1164 .format = config->format,
1165 };
1166 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1167 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001168 if (status != OK) {
1169 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001170 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001171
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001174
1175 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001176 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1177 && !audio_is_linear_pcm(config->format)) {
1178 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001179 return BAD_VALUE;
1180 }
1181 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001182 sp<DeviceDescriptor> deviceDesc =
1183 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1184 primaryMix->mDeviceAddress,
1185 AUDIO_FORMAT_DEFAULT);
1186 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001187 bool tryDirectForFlags = policyDesc == nullptr ||
1188 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1189 // if a direct output can be opened to deliver the track's multi-channel content to the
1190 // output rather than being downmixed by the primary output, then use this direct
1191 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1192 // mix.
1193 bool tryDirectForChannelMask = policyDesc != nullptr
1194 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1195 audio_channel_count_from_out_mask(config->channel_mask));
1196 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001197 audio_io_handle_t newOutput;
1198 status = openDirectOutput(
1199 *stream, session, config,
1200 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1201 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001202 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 policyDesc = mOutputs.valueFor(newOutput);
1204 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001205 } else if (tryDirectForFlags) {
1206 policyDesc = nullptr;
1207 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 }
1209 if (policyDesc != nullptr) {
1210 policyDesc->mPolicyMix = primaryMix;
1211 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001212 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001213
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001214 ALOGV("getOutputForAttr() returns output %d", *output);
1215 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1216 *outputType = API_OUT_MIX_PLAYBACK;
1217 } else {
1218 *outputType = API_OUTPUT_LEGACY;
1219 }
1220 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001221 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001222 }
François Gaffiec005e562018-11-06 15:04:49 +01001223 // Virtual sources must always be dynamicaly or explicitly routed
1224 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1225 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1226 return BAD_VALUE;
1227 }
1228 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1229 // in order to let the choice of the order to future vendor engine
1230 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001231
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001232 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001233 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001234 }
1235
Nadav Barb2f18162018-07-18 13:01:53 +03001236 // Set incall music only if device was explicitly set, and fallback to the device which is
1237 // chosen by the engine if not.
1238 // FIXME: provide a more generic approach which is not device specific and move this back
1239 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001240 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001241 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001242 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001243 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001244 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001245 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001246 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001247 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001248 }
1249 }
1250
François Gaffiec005e562018-11-06 15:04:49 +01001251 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1252 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1253 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001254
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001255 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001256 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001257 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001258 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001259 ALOGV("%s() Using MSD devices %s instead of devices %s",
1260 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001261 } else {
1262 *output = AUDIO_IO_HANDLE_NONE;
1263 }
1264 }
1265 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001266 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001267 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001269 if (*output == AUDIO_IO_HANDLE_NONE) {
1270 return INVALID_OPERATION;
1271 }
Paul McLeanaa981192015-03-21 09:55:15 -07001272
François Gaffiec005e562018-11-06 15:04:49 +01001273 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001274 for (auto &outputDevice : outputDevices) {
1275 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1276 *selectedDeviceId = outputDevice->getId();
1277 break;
1278 }
1279 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001280
Eric Laurent8a1095a2019-11-08 14:44:16 -08001281 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1282 *outputType = API_OUTPUT_TELEPHONY_TX;
1283 } else {
1284 *outputType = API_OUTPUT_LEGACY;
1285 }
1286
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001287 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1288
1289 return NO_ERROR;
1290}
1291
1292status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1293 audio_io_handle_t *output,
1294 audio_session_t session,
1295 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001296 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001297 const audio_config_t *config,
1298 audio_output_flags_t *flags,
1299 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001300 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001301 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001302 output_type_t *outputType,
1303 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001304{
1305 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1306 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1307 return INVALID_OPERATION;
1308 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001309 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001310 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001311 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001312 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001313 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001314 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001315 const sp<DeviceDescriptor> requestedDevice =
1316 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1317
1318 // Prevent from storing invalid requested device id in clients
1319 const audio_port_handle_t sanitizedRequestedPortId =
1320 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1321 *selectedDeviceId = sanitizedRequestedPortId;
1322
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001324 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001325 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001326 if (status != NO_ERROR) {
1327 return status;
1328 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001329 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001330 if (secondaryOutputs != nullptr) {
1331 for (auto &secondaryMix : secondaryMixes) {
1332 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1333 if (outputDesc != nullptr &&
1334 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1335 secondaryOutputs->push_back(outputDesc->mIoHandle);
1336 weakSecondaryOutputDescs.push_back(outputDesc);
1337 }
1338 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001339 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001340
Eric Laurent8fc147b2018-07-22 19:13:55 -07001341 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001342 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001343 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001344 };
jiabin4ef93452019-09-10 14:29:54 -07001345 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001346
Eric Laurentc209fe42020-06-05 18:11:23 -07001347 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001348 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001349 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001350 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001351 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001352 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001353 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001354 std::move(weakSecondaryOutputDescs),
1355 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001356 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001357
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001358 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1359 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001360
Eric Laurente83b55d2014-11-14 10:06:21 -08001361 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001362}
1363
Eric Laurentc529cf62020-04-17 18:19:10 -07001364status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1365 audio_session_t session,
1366 const audio_config_t *config,
1367 audio_output_flags_t flags,
1368 const DeviceVector &devices,
1369 audio_io_handle_t *output) {
1370
1371 *output = AUDIO_IO_HANDLE_NONE;
1372
1373 // skip direct output selection if the request can obviously be attached to a mixed output
1374 // and not explicitly requested
1375 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1376 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1377 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1378 return NAME_NOT_FOUND;
1379 }
1380
1381 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1382 // This prevents creating an offloaded track and tearing it down immediately after start
1383 // when audioflinger detects there is an active non offloadable effect.
1384 // FIXME: We should check the audio session here but we do not have it in this context.
1385 // This may prevent offloading in rare situations where effects are left active by apps
1386 // in the background.
1387 sp<IOProfile> profile;
1388 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1389 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1390 profile = getProfileForOutput(
1391 devices, config->sample_rate, config->format, config->channel_mask,
1392 flags, true /* directOnly */);
1393 }
1394
1395 if (profile == nullptr) {
1396 return NAME_NOT_FOUND;
1397 }
1398
1399 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1400 for (size_t i = 0; i < mOutputs.size(); i++) {
1401 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1402 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1403 // reuse direct output if currently open by the same client
1404 // and configured with same parameters
1405 if ((config->sample_rate == desc->getSamplingRate()) &&
1406 (config->format == desc->getFormat()) &&
1407 (config->channel_mask == desc->getChannelMask()) &&
1408 (session == desc->mDirectClientSession)) {
1409 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001410 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001411 mOutputs.keyAt(i), session);
1412 *output = mOutputs.keyAt(i);
1413 return NO_ERROR;
1414 }
1415 }
1416 }
1417
1418 if (!profile->canOpenNewIo()) {
1419 return NAME_NOT_FOUND;
1420 }
1421
1422 sp<SwAudioOutputDescriptor> outputDesc =
1423 new SwAudioOutputDescriptor(profile, mpClientInterface);
1424
Michael Chan6fb34492020-12-08 15:44:49 +11001425 // An MSD patch may be using the only output stream that can service this request. Release
1426 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001427 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001428
Eric Laurentf1f22e72021-07-13 14:04:14 +02001429 status_t status =
1430 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001431
1432 // only accept an output with the requested parameters
1433 if (status != NO_ERROR ||
1434 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1435 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1436 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1437 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1438 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1439 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1440 config->channel_mask, outputDesc->getChannelMask());
1441 if (*output != AUDIO_IO_HANDLE_NONE) {
1442 outputDesc->close();
1443 }
1444 // fall back to mixer output if possible when the direct output could not be open
1445 if (audio_is_linear_pcm(config->format) &&
1446 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1447 return NAME_NOT_FOUND;
1448 }
1449 *output = AUDIO_IO_HANDLE_NONE;
1450 return BAD_VALUE;
1451 }
1452 outputDesc->mDirectOpenCount = 1;
1453 outputDesc->mDirectClientSession = session;
1454
1455 addOutput(*output, outputDesc);
1456 mPreviousOutputs = mOutputs;
1457 ALOGV("%s returns new direct output %d", __func__, *output);
1458 mpClientInterface->onAudioPortListUpdate();
1459 return NO_ERROR;
1460}
1461
François Gaffie11d30102018-11-02 16:09:09 +01001462audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1463 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001464 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001465 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001466 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001467 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001468 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001469 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001470{
Andy Hungc88b0642018-04-27 15:42:35 -07001471 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001472
jiabine375d412019-02-26 12:54:53 -08001473 // Discard haptic channel mask when forcing muting haptic channels.
1474 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001475 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1476 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001477
Eric Laurente552edb2014-03-10 17:42:56 -07001478 // open a direct output if required by specified parameters
1479 //force direct flag if offload flag is set: offloading implies a direct output stream
1480 // and all common behaviors are driven by checking only the direct flag
1481 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001482 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1483 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001484 }
Nadav Bar766fb022018-01-07 12:18:03 +02001485 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1486 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001487 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001488
1489 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1490
Eric Laurente83b55d2014-11-14 10:06:21 -08001491 // only allow deep buffering for music stream type
1492 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001493 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001494 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001495 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001496 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1497 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001498 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001499 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001500 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001501 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001502 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001503 audio_is_linear_pcm(config->format) &&
1504 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001505 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001506 AUDIO_OUTPUT_FLAG_DIRECT);
1507 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001508 }
Eric Laurente552edb2014-03-10 17:42:56 -07001509
Carter Hsua3abb402021-10-26 11:11:20 +08001510 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1511 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1512 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1513 }
1514
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001515 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001516 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001517 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001518 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001519 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001520 }
1521
Eric Laurentc529cf62020-04-17 18:19:10 -07001522 audio_config_t directConfig = *config;
1523 directConfig.channel_mask = channelMask;
1524 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1525 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001526 return output;
1527 }
1528
Eric Laurent14cbfca2016-03-17 09:42:16 -07001529 // A request for HW A/V sync cannot fallback to a mixed output because time
1530 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001531 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001532 return AUDIO_IO_HANDLE_NONE;
1533 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001534 // A request for Tuner cannot fallback to a mixed output
1535 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1536 return AUDIO_IO_HANDLE_NONE;
1537 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001538
Eric Laurente552edb2014-03-10 17:42:56 -07001539 // ignoring channel mask due to downmix capability in mixer
1540
1541 // open a non direct output
1542
1543 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001544 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001545 // get which output is suitable for the specified stream. The actual
1546 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001547 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001548
Eric Laurent8838a382014-09-08 16:44:28 -07001549 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001550 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001551 output = selectOutput(
1552 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001553 }
François Gaffie11d30102018-11-02 16:09:09 +01001554 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001555 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001556 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001557
Eric Laurente552edb2014-03-10 17:42:56 -07001558 return output;
1559}
1560
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001561sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001562 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1563 mAvailableInputDevices);
1564 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1565}
1566
1567DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1568 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1569 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001570}
1571
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001572const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001573 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001574 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1575 if (msdModule != 0) {
1576 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1577 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1578 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1579 const struct audio_port_config *source = &patch->mPatch.sources[j];
1580 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1581 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001582 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001583 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001584 }
1585 }
1586 }
1587 return msdPatches;
1588}
1589
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001590bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1591 ssize_t index = mAudioPatches.indexOfKey(handle);
1592 if (index < 0) {
1593 return false;
1594 }
1595 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1596 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1597 if (msdModule == nullptr) {
1598 return false;
1599 }
1600 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1601 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1602 return true;
1603 }
1604 index = getMsdOutputPatches().indexOfKey(handle);
1605 if (index < 0) {
1606 return false;
1607 }
1608 return true;
1609}
1610
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001611status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1612 const InputProfileCollection &inputProfiles,
1613 const OutputProfileCollection &outputProfiles,
1614 const sp<DeviceDescriptor> &sourceDevice,
1615 const sp<DeviceDescriptor> &sinkDevice,
1616 AudioProfileVector& sourceProfiles,
1617 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001618 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001619 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001620 return NO_INIT;
1621 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 return NO_INIT;
1625 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001627 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1628 inProfile->supportsDevice(sourceDevice)) {
1629 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 }
1631 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001633 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001634 outProfile->supportsDevice(sinkDevice)) {
1635 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 }
1637 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001638 return NO_ERROR;
1639}
1640
1641status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1642 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1643 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1644{
Dean Wheatley16809da2022-12-09 14:55:46 +11001645 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1646 static const std::vector<audio_format_t> formatsOrder = {{
1647 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1648 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1649 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1650 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1651 // preferred).
1652 std::vector<audio_channel_mask_t> masks = {{
1653 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1654 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1655 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1656 // insert index masks (higher counts most preferred) as preferred over position masks
1657 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1658 masks.insert(
1659 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1660 }
1661 return masks;
1662 }();
1663
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001664 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001665 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1666 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001667 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001668 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1669 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001670 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001671 }
1672 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1673 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1674 sinkConfig->format = bestSinkConfig.format;
1675 // For encoded streams force direct flag to prevent downstream mixing.
1676 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1677 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001678 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1679 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001681 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1682 // raw and IEC61937 framed streams.
1683 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1684 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1685 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001686 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1687 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001688 sourceConfig->channel_mask =
1689 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1690 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1691 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 sourceConfig->format = bestSinkConfig.format;
1693 // Copy input stream directly without any processing (e.g. resampling).
1694 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1695 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1696 if (hwAvSync) {
1697 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1698 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1699 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1700 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1701 }
1702 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1703 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1704 sinkConfig->config_mask |= config_mask;
1705 sourceConfig->config_mask |= config_mask;
1706 return NO_ERROR;
1707}
1708
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001709PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1710 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711{
1712 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1714 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1715 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1716 if (deviceModule == nullptr) {
1717 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1718 return patchBuilder;
1719 }
1720 const InputProfileCollection inputProfiles = msdIsSource ?
1721 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1722 const OutputProfileCollection outputProfiles = msdIsSource ?
1723 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1724
1725 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1726 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1727 device : getMsdAudioOutDevices().itemAt(0);
1728 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1729
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1731 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001732 AudioProfileVector sourceProfiles;
1733 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1735 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001736 for (auto hwAvSync : { true, false }) {
1737 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1738 sourceProfiles, sinkProfiles) != NO_ERROR) {
1739 continue;
1740 }
1741 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1742 &sinkConfig) == NO_ERROR) {
1743 // Found a matching config. Re-create PatchBuilder with this config.
1744 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1745 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001747 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748 " supporting PCM format conversion.", __func__);
1749 return patchBuilder;
1750}
1751
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001752status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001753 DeviceVector devices;
1754 if (outputDevices != nullptr && outputDevices->size() > 0) {
1755 devices.add(*outputDevices);
1756 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001757 // Use media strategy for unspecified output device. This should only
1758 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1759 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001760 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001761 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001762 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001763 }
Michael Chan6fb34492020-12-08 15:44:49 +11001764 std::vector<PatchBuilder> patchesToCreate;
1765 for (auto i = 0u; i < devices.size(); ++i) {
1766 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001767 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001768 }
1769 // Retain only the MSD patches associated with outputDevices request.
1770 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001771 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001772 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1773 auto retainedPatch = false;
1774 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1775 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1776 patchesToRemove.removeItemsAt(i);
1777 retainedPatch = true;
1778 break;
1779 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001780 }
Michael Chan6fb34492020-12-08 15:44:49 +11001781 if (retainedPatch) {
1782 it = patchesToCreate.erase(it);
1783 continue;
1784 }
1785 ++it;
1786 }
1787 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1788 return NO_ERROR;
1789 }
1790 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1791 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001792 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001793 }
Michael Chan6fb34492020-12-08 15:44:49 +11001794 status_t status = NO_ERROR;
1795 for (const auto &p : patchesToCreate) {
1796 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1797 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1798 char message[256];
1799 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1800 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1801 currStatus == NO_ERROR ? "Success" : "Error",
1802 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1803 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1804 if (currStatus == NO_ERROR) {
1805 ALOGD("%s", message);
1806 } else {
1807 ALOGE("%s", message);
1808 if (status == NO_ERROR) {
1809 status = currStatus;
1810 }
1811 }
1812 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001813 return status;
1814}
1815
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001816void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1817 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001818 for (size_t i = 0; i < msdPatches.size(); i++) {
1819 const auto& patch = msdPatches[i];
1820 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1821 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1822 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1823 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1824 releaseAudioPatch(patch->getHandle(), mUidCached);
1825 break;
1826 }
1827 }
1828 }
1829}
1830
Dorin Drimus94d94412022-02-02 09:05:02 +01001831bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1832 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1833 AudioPatchCollection msdPatches = getMsdOutputPatches();
1834 for (size_t i = 0; i < msdPatches.size(); i++) {
1835 const auto& patch = msdPatches[i];
1836 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1837 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1838 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1839 const auto& foundDevice = devicesToCheck.getDevice(
1840 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1841 if (foundDevice != nullptr) {
1842 devicesToCheck.remove(foundDevice);
1843 if (devicesToCheck.isEmpty()) {
1844 return true;
1845 }
1846 }
1847 }
1848 }
1849 }
1850 return false;
1851}
1852
Eric Laurente0720872014-03-11 09:30:41 -07001853audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001854 audio_output_flags_t flags,
1855 audio_format_t format,
1856 audio_channel_mask_t channelMask,
1857 uint32_t samplingRate,
1858 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001859{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001860 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1861 "%s called with format %#x", __func__, format);
1862
jiabinebb6af42020-06-09 17:31:17 -07001863 // Return the output that haptic-generating attached to when 1) session id is specified,
1864 // 2) haptic-generating effect exists for given session id and 3) the output that
1865 // haptic-generating effect attached to is in given outputs.
1866 if (sessionId != AUDIO_SESSION_NONE) {
1867 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1868 sessionId, FX_IID_HAPTICGENERATOR);
1869 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1870 return hapticGeneratingOutput;
1871 }
1872 }
1873
Eric Laurent16c66dd2019-05-01 17:54:10 -07001874 // Flags disqualifying an output: the match must happen before calling selectOutput()
1875 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1876 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1877
1878 // Flags expressing a functional request: must be honored in priority over
1879 // other criteria
1880 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1881 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001882 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1883 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001884 // Flags expressing a performance request: have lower priority than serving
1885 // requested sampling rate or channel mask
1886 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1887 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1888 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1889
1890 const audio_output_flags_t functionalFlags =
1891 (audio_output_flags_t)(flags & kFunctionalFlags);
1892 const audio_output_flags_t performanceFlags =
1893 (audio_output_flags_t)(flags & kPerformanceFlags);
1894
1895 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1896
Eric Laurente552edb2014-03-10 17:42:56 -07001897 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001898 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001899 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001900 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001901 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001902 // with tiebreak preferring the minimum number of extra functional flags
1903 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001904 // 3: the output supporting the exact channel mask
1905 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001906 // 5: the output with the highest sampling rate if the requested sample rate is
1907 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001908 // 6: the output with the highest number of requested performance flags
1909 // 7: the output with the bit depth the closest to the requested one
1910 // 8: the primary output
1911 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001912
Eric Laurent16c66dd2019-05-01 17:54:10 -07001913 // matching criteria values in priority order for best matching output so far
1914 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001915
Eric Laurent16c66dd2019-05-01 17:54:10 -07001916 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1917 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1918 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001919
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001920 for (audio_io_handle_t output : outputs) {
1921 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001922 // matching criteria values in priority order for current output
1923 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001924
Eric Laurent16c66dd2019-05-01 17:54:10 -07001925 if (outputDesc->isDuplicated()) {
1926 continue;
1927 }
1928 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1929 continue;
1930 }
Eric Laurent8838a382014-09-08 16:44:28 -07001931
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932 // If haptic channel is specified, use the haptic output if present.
1933 // When using haptic output, same audio format and sample rate are required.
1934 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001935 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001936 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1937 continue;
1938 }
1939 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001940 && format == outputDesc->getFormat()
1941 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001942 currentMatchCriteria[0] = outputHapticChannelCount;
1943 }
1944
1945 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001946 const int matchingFunctionalFlags =
1947 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1948 const int totalFunctionalFlags =
1949 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1950 // Prefer matching functional flags, but subtract unnecessary functional flags.
1951 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001952
1953 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001954 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1955 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1957 channelCount <= outputChannelCount) {
1958 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001959 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1960 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001961 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001962 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001963 currentMatchCriteria[3] = outputChannelCount;
1964 }
1965
1966 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001967 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001968 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 }
1970
1971 // performance flags match
1972 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1973
1974 // format match
1975 if (format != AUDIO_FORMAT_INVALID) {
1976 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001977 PolicyAudioPort::kFormatDistanceMax -
1978 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001979 }
1980
1981 // primary output match
1982 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1983
1984 // compare match criteria by priority then value
1985 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1986 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1987 bestMatchCriteria = currentMatchCriteria;
1988 bestOutput = output;
1989
1990 std::stringstream result;
1991 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1992 std::ostream_iterator<int>(result, " "));
1993 ALOGV("%s new bestOutput %d criteria %s",
1994 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001995 }
1996 }
1997
Eric Laurent16c66dd2019-05-01 17:54:10 -07001998 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001999}
2000
Eric Laurent8fc147b2018-07-22 19:13:55 -07002001status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002002{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002003 ALOGV("%s portId %d", __FUNCTION__, portId);
2004
2005 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2006 if (outputDesc == 0) {
2007 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002008 return BAD_VALUE;
2009 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002010 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002011
Eric Laurent8fc147b2018-07-22 19:13:55 -07002012 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002013 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002014
Eric Laurent733ce942017-12-07 12:18:25 -08002015 status_t status = outputDesc->start();
2016 if (status != NO_ERROR) {
2017 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002018 }
2019
Eric Laurent97ac8712018-07-27 18:59:02 -07002020 uint32_t delayMs;
2021 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002022
2023 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002024 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002025 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002026 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002027 if (delayMs != 0) {
2028 usleep(delayMs * 1000);
2029 }
2030
2031 return status;
2032}
2033
Eric Laurent96d1dda2022-03-14 17:14:19 +01002034bool AudioPolicyManager::isLeUnicastActive() const {
2035 if (isInCall()) {
2036 return true;
2037 }
2038 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2039}
2040
2041bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2042 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2043 return false;
2044 }
2045 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2046 ALOGV("%s active %d", __func__, active);
2047 return active;
2048}
2049
Eric Laurent97ac8712018-07-27 18:59:02 -07002050status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2051 const sp<TrackClientDescriptor>& client,
2052 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002053{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002054 // cannot start playback of STREAM_TTS if any other output is being used
2055 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002056
2057 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002058 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002059 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002060 auto clientStrategy = client->strategy();
2061 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002062 if (stream == AUDIO_STREAM_TTS) {
2063 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002064 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002065 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002066 return INVALID_OPERATION;
2067 } else {
2068 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2069 }
2070 } else {
2071 // some playback other than beacon starts
2072 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2073 }
2074
Eric Laurent77305a62016-07-25 16:39:22 -07002075 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002076 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002077 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002078
François Gaffie11d30102018-11-02 16:09:09 +01002079 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002080 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002081 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002082 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002083 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002084 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002085 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002086 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002087 } else {
2088 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002089 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002090 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2091 AUDIO_FORMAT_DEFAULT);
2092 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2093 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002094 }
2095
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002096 // requiresMuteCheck is false when we can bypass mute strategy.
2097 // It covers a common case when there is no materially active audio
2098 // and muting would result in unnecessary delay and dropped audio.
2099 const uint32_t outputLatencyMs = outputDesc->latency();
2100 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002101 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002102
Eric Laurente552edb2014-03-10 17:42:56 -07002103 // increment usage count for this stream on the requested output:
2104 // NOTE that the usage count is the same for duplicated output and hardware output which is
2105 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002106 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002107
2108 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002109 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2110 client->isPreferredDeviceForExclusiveUse()) {
2111 // Preferred device may be exclusive, use only if no other active clients on this output
2112 devices = DeviceVector(
2113 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2114 } else {
2115 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2116 }
François Gaffie11d30102018-11-02 16:09:09 +01002117 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002118 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002119 }
2120 }
Eric Laurente552edb2014-03-10 17:42:56 -07002121
François Gaffiec005e562018-11-06 15:04:49 +01002122 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002123 selectOutputForMusicEffects();
2124 }
2125
François Gaffie1c878552018-11-22 16:53:21 +01002126 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002127 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002128 if (devices.isEmpty()) {
2129 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002130 }
François Gaffiec005e562018-11-06 15:04:49 +01002131 bool shouldWait =
2132 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2133 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2134 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002135 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002136 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002137 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002138 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002139 // An output has a shared device if
2140 // - managed by the same hw module
2141 // - supports the currently selected device
2142 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002143 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002144
Eric Laurent77305a62016-07-25 16:39:22 -07002145 // force a device change if any other output is:
2146 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002147 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002148 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002149 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002150 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002151 // change the device currently selected by the other output.
2152 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002153 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002154 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002155 force = true;
2156 }
2157 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002158 // a notification so that audio focus effect can propagate, or that a mute/unmute
2159 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002160 const uint32_t latencyMs = desc->latency();
2161 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2162
2163 if (shouldWait && isActive && (waitMs < latencyMs)) {
2164 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002165 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002166
2167 // Require mute check if another output is on a shared device
2168 // and currently active to have proper drain and avoid pops.
2169 // Note restoring AudioTracks onto this output needs to invoke
2170 // a volume ramp if there is no mute.
2171 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002172 }
2173 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002174
2175 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002176 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002177
Eric Laurente552edb2014-03-10 17:42:56 -07002178 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002179 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002180 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002181 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002182 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002183 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002184 outputDesc->useHwGain() /*force*/)) {
2185 // request AudioService to reinitialize the volume curves asynchronously
2186 ALOGE("checkAndSetVolume failed, requesting volume range init");
2187 mpClientInterface->onVolumeRangeInitRequest();
2188 };
Eric Laurente552edb2014-03-10 17:42:56 -07002189
2190 // update the outputs if starting an output with a stream that can affect notification
2191 // routing
2192 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002193
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002194 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002195 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002196 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2197 }
Eric Laurentdc462862016-07-19 12:29:53 -07002198
2199 if (waitMs > muteWaitMs) {
2200 *delayMs = waitMs - muteWaitMs;
2201 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002202
2203 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2204 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2205 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2206 // change occurs after the MixerThread starts and causes a stream volume
2207 // glitch.
2208 //
2209 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002210 }
Eric Laurentdc462862016-07-19 12:29:53 -07002211
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002212 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002213 mEngine->getForceUse(
2214 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002215 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002216 }
2217
Eric Laurent97ac8712018-07-27 18:59:02 -07002218 // Automatically enable the remote submix input when output is started on a re routing mix
2219 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002220 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2221 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002222 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2224 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002225 "remote-submix",
2226 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002227 }
2228
Eric Laurent96d1dda2022-03-14 17:14:19 +01002229 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2230
Eric Laurente552edb2014-03-10 17:42:56 -07002231 return NO_ERROR;
2232}
2233
Eric Laurent96d1dda2022-03-14 17:14:19 +01002234void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2235 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2236 bool isUnicastActive = isLeUnicastActive();
2237
2238 if (wasUnicastActive != isUnicastActive) {
2239 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2240 for (size_t i = 0; i < mOutputs.size(); i++) {
2241 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2242 if (desc != ignoredOutput && desc->isActive()
2243 && ((isUnicastActive &&
2244 !desc->devices().
2245 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2246 || (wasUnicastActive &&
2247 !desc->devices().getDevicesFromTypes(
2248 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2249 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2250 bool force = desc->devices() != newDevices;
2251 setOutputDevices(desc, newDevices, force, delayMs);
2252 // re-apply device specific volume if not done by setOutputDevice()
2253 if (!force) {
2254 applyStreamVolumes(desc, newDevices.types(), delayMs);
2255 }
2256 }
2257 }
2258 }
2259}
2260
Eric Laurent8fc147b2018-07-22 19:13:55 -07002261status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002262{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002263 ALOGV("%s portId %d", __FUNCTION__, portId);
2264
2265 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2266 if (outputDesc == 0) {
2267 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002268 return BAD_VALUE;
2269 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002270 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002271
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 ALOGV("stopOutput() output %d, stream %d, session %d",
2273 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002274
Eric Laurent97ac8712018-07-27 18:59:02 -07002275 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002276
Eric Laurent733ce942017-12-07 12:18:25 -08002277 if (status == NO_ERROR ) {
2278 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002279 }
2280 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002281}
2282
Eric Laurent97ac8712018-07-27 18:59:02 -07002283status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2284 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002285{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002286 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002287 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002288 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002289 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002290
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002291 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2292
François Gaffie1c878552018-11-22 16:53:21 +01002293 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2294 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002295 // Automatically disable the remote submix input when output is stopped on a
2296 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002297 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002298 if (isSingleDeviceType(
2299 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002300 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002301 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002302 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2303 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002304 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002305 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002306 }
2307 }
2308 bool forceDeviceUpdate = false;
2309 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002310 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002311 forceDeviceUpdate = true;
2312 }
2313
Eric Laurente552edb2014-03-10 17:42:56 -07002314 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002315 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002316
Eric Laurente552edb2014-03-10 17:42:56 -07002317 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002318 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002319 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002320 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002321
2322 // If the routing does not change, if an output is routed on a device using HwGain
2323 // (aka setAudioPortConfig) and there are still active clients following different
2324 // volume group(s), force reapply volume
2325 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2326 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2327
Eric Laurente552edb2014-03-10 17:42:56 -07002328 // delay the device switch by twice the latency because stopOutput() is executed when
2329 // the track stop() command is received and at that time the audio track buffer can
2330 // still contain data that needs to be drained. The latency only covers the audio HAL
2331 // and kernel buffers. Also the latency does not always include additional delay in the
2332 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002333 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2334 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002335
2336 // force restoring the device selection on other active outputs if it differs from the
2337 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002338 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002339 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002341 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002342 desc->isActive() &&
2343 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002344 (newDevices != desc->devices())) {
2345 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2346 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002347
François Gaffie11d30102018-11-02 16:09:09 +01002348 setOutputDevices(desc, newDevices2, force, delayMs);
2349
Eric Laurent57de36c2016-09-28 16:59:11 -07002350 // re-apply device specific volume if not done by setOutputDevice()
2351 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002352 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002353 }
Eric Laurente552edb2014-03-10 17:42:56 -07002354 }
2355 }
2356 // update the outputs if stopping one with a stream that can affect notification routing
2357 handleNotificationRoutingForStream(stream);
2358 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002359
2360 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2361 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002362 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002363 }
2364
François Gaffiec005e562018-11-06 15:04:49 +01002365 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002366 selectOutputForMusicEffects();
2367 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002368
2369 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2370
Eric Laurente552edb2014-03-10 17:42:56 -07002371 return NO_ERROR;
2372 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002373 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002374 return INVALID_OPERATION;
2375 }
2376}
2377
jiabinbce0c1d2020-10-05 11:20:18 -07002378bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002379{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002380 ALOGV("%s portId %d", __FUNCTION__, portId);
2381
2382 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2383 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002384 // If an output descriptor is closed due to a device routing change,
2385 // then there are race conditions with releaseOutput from tracks
2386 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2387 // destroyed shortly thereafter.
2388 //
2389 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002390 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002391 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002392 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002393
2394 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002395
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302396 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2397 if (outputDesc->isClientActive(client)) {
2398 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2399 stopOutput(portId);
2400 }
2401
Eric Laurent8fc147b2018-07-22 19:13:55 -07002402 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2403 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002404 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002405 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002406 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002407 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002408 if (--outputDesc->mDirectOpenCount == 0) {
2409 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002410 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002411 }
2412 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302413
Andy Hung39efb7a2018-09-26 15:39:28 -07002414 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002415 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2416 // The output is pending reopened to query dynamic profiles and
2417 // there is no active clients
2418 closeOutput(outputDesc->mIoHandle);
2419 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2420 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2421 if (newOutputDesc == nullptr) {
2422 ALOGE("%s failed to open output", __func__);
2423 }
2424 return true;
2425 }
2426 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002427}
2428
Eric Laurentcaf7f482014-11-25 17:50:47 -08002429status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2430 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002431 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002432 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002433 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002434 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002435 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002436 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002437 input_type_t *inputType,
2438 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002439{
François Gaffiec005e562018-11-06 15:04:49 +01002440 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002441 "flags %#x attributes=%s requested device ID %d",
2442 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2443 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002444
Eric Laurentad2e7b92017-09-14 20:06:42 -07002445 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002446 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002447 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002448 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002449 sp<AudioInputDescriptor> inputDesc;
2450 sp<RecordClientDescriptor> clientDesc;
2451 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002452 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002453 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002454
2455 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2456 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2457 return INVALID_OPERATION;
2458 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002459
Francois Gaffie716e1432019-01-14 16:58:59 +01002460 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2461 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002462 }
2463
Paul McLean466dc8e2015-04-17 13:15:36 -06002464 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002465 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002466 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002467
Eric Laurentad2e7b92017-09-14 20:06:42 -07002468 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2469 // possible
2470 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2471 *input != AUDIO_IO_HANDLE_NONE) {
2472 ssize_t index = mInputs.indexOfKey(*input);
2473 if (index < 0) {
2474 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2475 status = BAD_VALUE;
2476 goto error;
2477 }
2478 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002479 RecordClientVector clients = inputDesc->getClientsForSession(session);
2480 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002481 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2482 status = BAD_VALUE;
2483 goto error;
2484 }
2485 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2486 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002487 // corresponds to a new client and is only permitted from the same UID.
2488 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002489 if (clients.size() > 1) {
2490 for (const auto& client : clients) {
2491 // The client map is ordered by key values (portId) and portIds are allocated
2492 // incrementaly. So the first client in this list is the one opened by audio flinger
2493 // when the mmap stream is created and should be ignored as it does not correspond
2494 // to an actual client
2495 if (client == *clients.cbegin()) {
2496 continue;
2497 }
2498 if (uid != client->uid() && !client->isSilenced()) {
2499 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2500 uid, client->portId(), client->uid());
2501 status = INVALID_OPERATION;
2502 goto error;
2503 }
Eric Laurent331679c2018-04-16 17:03:16 -07002504 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002505 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002506 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002507 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002508
Eric Laurentfecbceb2021-02-09 14:46:43 +01002509 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002510 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002511 }
2512
2513 *input = AUDIO_IO_HANDLE_NONE;
2514 *inputType = API_INPUT_INVALID;
2515
Francois Gaffie716e1432019-01-14 16:58:59 +01002516 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2517 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2518 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002519 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002520 ALOGW("%s could not find input mix for attr %s",
2521 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002522 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002523 }
jiabinc1de2df2019-05-07 14:26:40 -07002524 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2525 String8(attr->tags + strlen("addr=")),
2526 AUDIO_FORMAT_DEFAULT);
2527 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002528 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002529 __func__, attributes.source, attributes.tags);
2530 status = BAD_VALUE;
2531 goto error;
2532 }
2533
Kevin Rocard25f9b052019-02-27 15:08:54 -08002534 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2535 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2536 } else {
2537 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2538 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002539 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002540 if (explicitRoutingDevice != nullptr) {
2541 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002542 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002543 // Prevent from storing invalid requested device id in clients
2544 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002545 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002546 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2547 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002548 }
François Gaffie11d30102018-11-02 16:09:09 +01002549 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002550 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002551 status = BAD_VALUE;
2552 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002553 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002554 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2555 *inputType = API_INPUT_MIX_CAPTURE;
2556 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002557 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2558 // there is an external policy, but this input is attached to a mix of recorders,
2559 // meaning it receives audio injected into the framework, so the recorder doesn't
2560 // know about it and is therefore considered "legacy"
2561 *inputType = API_INPUT_LEGACY;
2562 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002563 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002564 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002565 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002566 } else {
2567 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002568 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002569
Eric Laurent599c7582015-12-07 18:05:55 -08002570 }
2571
François Gaffiec005e562018-11-06 15:04:49 +01002572 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002573 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002574 status = INVALID_OPERATION;
2575 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002576 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002577
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578exit:
2579
François Gaffiec005e562018-11-06 15:04:49 +01002580 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2581 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002582
Francois Gaffie716e1432019-01-14 16:58:59 +01002583 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002584 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002585 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002586
Mikhail Naganov2996f672019-04-18 12:29:59 -07002587 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002588 requestedDeviceId, attributes.source, flags,
2589 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002590 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002591 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002592
2593 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2594 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002595
Eric Laurent599c7582015-12-07 18:05:55 -08002596 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002597
2598error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002599 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002600}
2601
2602
François Gaffie11d30102018-11-02 16:09:09 +01002603audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002604 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002605 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002606 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002607 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002608 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002609{
2610 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002611 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002612 bool isSoundTrigger = false;
2613
François Gaffiec005e562018-11-06 15:04:49 +01002614 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002615 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2616 if (index >= 0) {
2617 input = mSoundTriggerSessions.valueFor(session);
2618 isSoundTrigger = true;
2619 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2620 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2621 } else {
2622 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002623 }
François Gaffiec005e562018-11-06 15:04:49 +01002624 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002625 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002626 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002627 }
2628
Carter Hsua3abb402021-10-26 11:11:20 +08002629 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2630 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2631 }
2632
Andy Hungf129b032015-04-07 13:45:50 -07002633 // find a compatible input profile (not necessarily identical in parameters)
2634 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002635 // sampling rate and flags may be updated by getInputProfile
2636 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2637 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002638 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002639 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002640 audio_input_flags_t profileFlags = flags;
2641 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002642 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002643 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002644 profileFlags);
2645 if (profile != 0) {
2646 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002647 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2648 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002649 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002650 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2651 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002652 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002653 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002654 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002655 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002656 }
Eric Laurente552edb2014-03-10 17:42:56 -07002657 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002658 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002659 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002660 if (samplingRate == 0) {
2661 samplingRate = profileSamplingRate;
2662 }
Eric Laurente552edb2014-03-10 17:42:56 -07002663
Eric Laurent322b4d22015-04-03 15:57:54 -07002664 if (profile->getModuleHandle() == 0) {
2665 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002666 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002667 }
2668
Eric Laurentec376dc2021-04-08 20:41:22 +02002669 // Reuse an already opened input if a client with the same session ID already exists
2670 // on that input
2671 for (size_t i = 0; i < mInputs.size(); i++) {
2672 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2673 if (desc->mProfile != profile) {
2674 continue;
2675 }
2676 RecordClientVector clients = desc->clientsList();
2677 for (const auto &client : clients) {
2678 if (session == client->session()) {
2679 return desc->mIoHandle;
2680 }
2681 }
2682 }
2683
Eric Laurent3974e3b2017-12-07 17:58:43 -08002684 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002685 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002686 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002687 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002688 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002689 continue;
2690 }
2691 // if sound trigger, reuse input if used by other sound trigger on same session
2692 // else
2693 // reuse input if active client app is not in IDLE state
2694 //
2695 RecordClientVector clients = desc->clientsList();
2696 bool doClose = false;
2697 for (const auto& client : clients) {
2698 if (isSoundTrigger != client->isSoundTrigger()) {
2699 continue;
2700 }
2701 if (client->isSoundTrigger()) {
2702 if (session == client->session()) {
2703 return desc->mIoHandle;
2704 }
2705 continue;
2706 }
2707 if (client->active() && client->appState() != APP_STATE_IDLE) {
2708 return desc->mIoHandle;
2709 }
2710 doClose = true;
2711 }
2712 if (doClose) {
2713 closeInput(desc->mIoHandle);
2714 } else {
2715 i++;
2716 }
2717 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002718 }
2719
Eric Laurentfe231122017-11-17 17:48:06 -08002720 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002721
Eric Laurentfe231122017-11-17 17:48:06 -08002722 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2723 lConfig.sample_rate = profileSamplingRate;
2724 lConfig.channel_mask = profileChannelMask;
2725 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002726
François Gaffie11d30102018-11-02 16:09:09 +01002727 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002728
2729 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002730 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002731 (profileSamplingRate != lConfig.sample_rate) ||
2732 !audio_formats_match(profileFormat, lConfig.format) ||
2733 (profileChannelMask != lConfig.channel_mask)) {
2734 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002735 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002736 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002737 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002738 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002739 }
Eric Laurent599c7582015-12-07 18:05:55 -08002740 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002741 }
2742
Eric Laurentc722f302014-12-10 11:21:49 -08002743 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002744
Eric Laurent599c7582015-12-07 18:05:55 -08002745 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002746 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002747
Eric Laurent599c7582015-12-07 18:05:55 -08002748 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002749}
2750
Eric Laurent4eb58f12018-12-07 16:41:02 -08002751status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002752{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002753 ALOGV("%s portId %d", __FUNCTION__, portId);
2754
2755 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2756 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002757 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002758 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002759 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002760 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002761 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002762 if (client->active()) {
2763 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2764 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002765 }
2766
Eric Laurent8f42ea12018-08-08 09:08:25 -07002767 audio_session_t session = client->session();
2768
Eric Laurent4eb58f12018-12-07 16:41:02 -08002769 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770
Eric Laurent4eb58f12018-12-07 16:41:02 -08002771 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002772
Eric Laurent4eb58f12018-12-07 16:41:02 -08002773 status_t status = inputDesc->start();
2774 if (status != NO_ERROR) {
2775 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002776 }
Eric Laurente552edb2014-03-10 17:42:56 -07002777
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002778 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002779 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002781
Eric Laurent8f42ea12018-08-08 09:08:25 -07002782 // indicate active capture to sound trigger service if starting capture from a mic on
2783 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002784 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002785 if (device != nullptr) {
2786 status = setInputDevice(input, device, true /* force */);
2787 } else {
2788 ALOGW("%s no new input device can be found for descriptor %d",
2789 __FUNCTION__, inputDesc->getId());
2790 status = BAD_VALUE;
2791 }
Eric Laurente552edb2014-03-10 17:42:56 -07002792
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002793 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002794 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002796 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002797 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2798 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002799 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002800 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002801
François Gaffie11d30102018-11-02 16:09:09 +01002802 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2803 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002804 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002805 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002806 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002807
Eric Laurent8f42ea12018-08-08 09:08:25 -07002808 // automatically enable the remote submix output when input is started if not
2809 // used by a policy mix of type MIX_TYPE_RECORDERS
2810 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002811 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002812 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002813 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002814 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002815 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2816 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002817 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002818 if (address != "") {
2819 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2820 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002821 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002822 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002823 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002824 } else if (status != NO_ERROR) {
2825 // Restore client activity state.
2826 inputDesc->setClientActive(client, false);
2827 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002828 }
2829
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002830 ALOGV("%s input %d source = %d status = %d exit",
2831 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002832
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002833 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002834}
2835
Eric Laurent8fc147b2018-07-22 19:13:55 -07002836status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002837{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002838 ALOGV("%s portId %d", __FUNCTION__, portId);
2839
2840 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2841 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002843 return BAD_VALUE;
2844 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002845 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002846 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002847 if (!client->active()) {
2848 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002849 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002850 }
Carter Hsue6139d52021-07-08 10:30:20 +08002851 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002852 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002853
Eric Laurent8f42ea12018-08-08 09:08:25 -07002854 inputDesc->stop();
2855 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002856 auto current_source = inputDesc->source();
2857 setInputDevice(input, getNewInputDevice(inputDesc),
2858 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002860 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002861 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002862 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002863 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2864 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002866 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002867
2868 // automatically disable the remote submix output when input is stopped if not
2869 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002870 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002871 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002872 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002874 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2875 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002876 }
2877 if (address != "") {
2878 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2879 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002880 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 }
2882 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883 resetInputDevice(input);
2884
2885 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2886 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002887 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2888 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002890 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 }
2892 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002893 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002894 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002895}
2896
Eric Laurent8fc147b2018-07-22 19:13:55 -07002897void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002898{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002899 ALOGV("%s portId %d", __FUNCTION__, portId);
2900
2901 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2902 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002903 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002904 return;
2905 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002906 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 audio_io_handle_t input = inputDesc->mIoHandle;
2908
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002910
Andy Hung39efb7a2018-09-26 15:39:28 -07002911 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002912
Andy Hung39efb7a2018-09-26 15:39:28 -07002913 if (inputDesc->getClientCount() > 0) {
2914 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002915 return;
2916 }
2917
Eric Laurent05b90f82014-08-27 15:32:29 -07002918 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002919 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002920 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002921}
2922
Eric Laurent8f42ea12018-08-08 09:08:25 -07002923void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002924{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002925 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002926
2927 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002928 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002929 }
2930}
2931
Eric Laurent8f42ea12018-08-08 09:08:25 -07002932void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2933{
2934 stopInput(portId);
2935 releaseInput(portId);
2936}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002937
Eric Laurent0dd51852019-04-19 18:18:58 -07002938void AudioPolicyManager::checkCloseInputs() {
2939 // After connecting or disconnecting an input device, close input if:
2940 // - it has no client (was just opened to check profile) OR
2941 // - none of its supported devices are connected anymore OR
2942 // - one of its clients cannot be routed to one of its supported
2943 // devices anymore. Otherwise update device selection
2944 std::vector<audio_io_handle_t> inputsToClose;
2945 for (size_t i = 0; i < mInputs.size(); i++) {
2946 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2947 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002948 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002949 inputsToClose.push_back(mInputs.keyAt(i));
2950 } else {
2951 bool close = false;
2952 for (const auto& client : input->clientsList()) {
2953 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002954 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002955 if (!input->supportedDevices().contains(device)) {
2956 close = true;
2957 break;
2958 }
2959 }
2960 if (close) {
2961 inputsToClose.push_back(mInputs.keyAt(i));
2962 } else {
2963 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2964 }
2965 }
2966 }
2967
2968 for (const audio_io_handle_t handle : inputsToClose) {
2969 ALOGV("%s closing input %d", __func__, handle);
2970 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002971 }
Eric Laurentd4692962014-05-05 18:13:44 -07002972}
2973
François Gaffie251c7f02018-11-07 10:41:08 +01002974void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002975{
2976 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002977 if (indexMin < 0 || indexMax < 0) {
2978 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2979 return;
2980 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002981 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002982
2983 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002984 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2985 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002986 continue;
2987 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002988 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002989 }
Eric Laurente552edb2014-03-10 17:42:56 -07002990}
2991
Eric Laurente0720872014-03-11 09:30:41 -07002992status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002993 int index,
2994 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002995{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002996 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002997 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2998 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2999 return NO_ERROR;
3000 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003001 ALOGV("%s: stream %s attributes=%s", __func__,
3002 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003003 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003004}
3005
Eric Laurente0720872014-03-11 09:30:41 -07003006status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003007 int *index,
3008 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003009{
François Gaffiec005e562018-11-06 15:04:49 +01003010 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3011 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003012 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003013 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003014 deviceTypes = mEngine->getOutputDevicesForStream(
3015 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003016 }
jiabin9a3361e2019-10-01 09:38:30 -07003017 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003018}
3019
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003020status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003021 int index,
3022 audio_devices_t device)
3023{
3024 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003025 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3026 if (group == VOLUME_GROUP_NONE) {
3027 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003028 return BAD_VALUE;
3029 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003030 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003031 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003032 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003033 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003034 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3035 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3036 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3037 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003038 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3039
3040 status = setVolumeCurveIndex(index, device, curves);
3041 if (status != NO_ERROR) {
3042 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3043 return status;
3044 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003045
jiabin9a3361e2019-10-01 09:38:30 -07003046 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003047 auto curCurvAttrs = curves.getAttributes();
3048 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3049 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003050 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003051 } else if (!curves.getStreamTypes().empty()) {
3052 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003053 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003054 } else {
3055 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3056 return BAD_VALUE;
3057 }
jiabin9a3361e2019-10-01 09:38:30 -07003058 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3059 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003060
François Gaffiecfe17322018-11-07 13:41:29 +01003061 // update volume on all outputs and streams matching the following:
3062 // - The requested stream (or a stream matching for volume control) is active on the output
3063 // - The device (or devices) selected by the engine for this stream includes
3064 // the requested device
3065 // - For non default requested device, currently selected device on the output is either the
3066 // requested device or one of the devices selected by the engine for this stream
3067 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3068 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003069 for (size_t i = 0; i < mOutputs.size(); i++) {
3070 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003071 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003072
jiabin9a3361e2019-10-01 09:38:30 -07003073 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3074 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003075 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003076
3077 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003078 continue;
3079 }
3080 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3081 curDevices.find(device) == curDevices.end()) {
3082 continue;
3083 }
3084 bool applyVolume = false;
3085 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3086 curSrcDevices.insert(device);
3087 applyVolume = (curSrcDevices.find(
3088 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3089 } else {
3090 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3091 }
3092 if (!applyVolume) {
3093 continue; // next output
3094 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003095 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3096 // If a higher priority strategy is active, and the output is routed to a device with a
3097 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003098 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003099 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003100 // If the volume source is active with higher priority source, ensure at least Sw Muted
3101 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003102 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3103 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3104 false /*preferredDevice*/);
3105 if (activeClients.empty()) {
3106 continue;
3107 }
3108 bool isPreempted = false;
3109 bool isHigherPriority = productStrategy < strategy;
3110 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003111 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003112 ALOGV("%s: Strategy=%d (\nrequester:\n"
3113 " group %d, volumeGroup=%d attributes=%s)\n"
3114 " higher priority source active:\n"
3115 " volumeGroup=%d attributes=%s) \n"
3116 " on output %zu, bailing out", __func__, productStrategy,
3117 group, group, toString(attributes).c_str(),
3118 client->volumeSource(), toString(client->attributes()).c_str(), i);
3119 applyVolume = false;
3120 isPreempted = true;
3121 break;
3122 }
3123 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003124 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003125 applyVolume = true;
3126 }
3127 }
3128 if (isPreempted || applyVolume) {
3129 break;
3130 }
3131 }
3132 if (!applyVolume) {
3133 continue; // next output
3134 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135 }
François Gaffieed91f582020-01-31 10:35:37 +01003136 //FIXME: workaround for truncated touch sounds
3137 // delayed volume change for system stream to be removed when the problem is
3138 // handled by system UI
3139 status_t volStatus = checkAndSetVolume(
3140 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003141 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003142 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3143 if (volStatus != NO_ERROR) {
3144 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003145 }
3146 }
François Gaffiecfe17322018-11-07 13:41:29 +01003147 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3148 return status;
3149}
3150
François Gaffieaaac0fd2018-11-22 17:56:39 +01003151status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003152 audio_devices_t device,
3153 IVolumeCurves &volumeCurves)
3154{
3155 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3156 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003157 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3158 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003159 (index > volumeCurves.getVolumeIndexMax())) {
3160 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3161 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3162 return BAD_VALUE;
3163 }
3164 if (!audio_is_output_device(device)) {
3165 return BAD_VALUE;
3166 }
3167
3168 // Force max volume if stream cannot be muted
3169 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3170
François Gaffieaaac0fd2018-11-22 17:56:39 +01003171 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003172 volumeCurves.addCurrentVolumeIndex(device, index);
3173 return NO_ERROR;
3174}
3175
3176status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3177 int &index,
3178 audio_devices_t device)
3179{
3180 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3181 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003182 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003183 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003184 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003185 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003186 }
jiabin9a3361e2019-10-01 09:38:30 -07003187 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003188}
3189
3190status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3191 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003192 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003193{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003194 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003195 return BAD_VALUE;
3196 }
jiabin9a3361e2019-10-01 09:38:30 -07003197 index = curves.getVolumeIndex(deviceTypes);
3198 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003199 return NO_ERROR;
3200}
3201
3202status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3203 int &index)
3204{
3205 index = getVolumeCurves(attr).getVolumeIndexMin();
3206 return NO_ERROR;
3207}
3208
3209status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3210 int &index)
3211{
3212 index = getVolumeCurves(attr).getVolumeIndexMax();
3213 return NO_ERROR;
3214}
3215
Eric Laurent36829f92017-04-07 19:04:42 -07003216audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003217{
3218 // select one output among several suitable for global effects.
3219 // The priority is as follows:
3220 // 1: An offloaded output. If the effect ends up not being offloadable,
3221 // AudioFlinger will invalidate the track and the offloaded output
3222 // will be closed causing the effect to be moved to a PCM output.
3223 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003224 // 3: The primary output
3225 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003226
François Gaffiec005e562018-11-06 15:04:49 +01003227 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3228 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003229 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003230
Eric Laurent36829f92017-04-07 19:04:42 -07003231 if (outputs.size() == 0) {
3232 return AUDIO_IO_HANDLE_NONE;
3233 }
Eric Laurente552edb2014-03-10 17:42:56 -07003234
Eric Laurent36829f92017-04-07 19:04:42 -07003235 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3236 bool activeOnly = true;
3237
3238 while (output == AUDIO_IO_HANDLE_NONE) {
3239 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3240 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3241 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3242
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003243 for (audio_io_handle_t output : outputs) {
3244 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003245 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003246 continue;
3247 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003248 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3249 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003250 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003251 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003252 }
3253 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003254 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003255 }
3256 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003257 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003258 }
3259 }
3260 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3261 output = outputOffloaded;
3262 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3263 output = outputDeepBuffer;
3264 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3265 output = outputPrimary;
3266 } else {
3267 output = outputs[0];
3268 }
3269 activeOnly = false;
3270 }
3271
3272 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003273 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003274 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3275 mMusicEffectOutput = output;
3276 }
3277
3278 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003279 return output;
3280}
3281
Eric Laurent36829f92017-04-07 19:04:42 -07003282audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3283{
3284 return selectOutputForMusicEffects();
3285}
3286
Eric Laurente0720872014-03-11 09:30:41 -07003287status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003288 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003289 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003290 int session,
3291 int id)
3292{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003293 if (session != AUDIO_SESSION_DEVICE) {
3294 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003295 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003296 index = mInputs.indexOfKey(io);
3297 if (index < 0) {
3298 ALOGW("registerEffect() unknown io %d", io);
3299 return INVALID_OPERATION;
3300 }
Eric Laurente552edb2014-03-10 17:42:56 -07003301 }
3302 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003303 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3304 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3305 || strategy == PRODUCT_STRATEGY_NONE));
3306 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003307}
3308
Eric Laurentc241b0d2018-11-28 09:08:49 -08003309status_t AudioPolicyManager::unregisterEffect(int id)
3310{
3311 if (mEffects.getEffect(id) == nullptr) {
3312 return INVALID_OPERATION;
3313 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003314 if (mEffects.isEffectEnabled(id)) {
3315 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3316 setEffectEnabled(id, false);
3317 }
3318 return mEffects.unregisterEffect(id);
3319}
3320
3321status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3322{
3323 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3324 if (effect == nullptr) {
3325 return INVALID_OPERATION;
3326 }
3327
3328 status_t status = mEffects.setEffectEnabled(id, enabled);
3329 if (status == NO_ERROR) {
3330 mInputs.trackEffectEnabled(effect, enabled);
3331 }
3332 return status;
3333}
3334
Eric Laurent6c796322019-04-09 14:13:17 -07003335
3336status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3337{
3338 mEffects.moveEffects(ids, io);
3339 return NO_ERROR;
3340}
3341
Eric Laurentc75307b2015-03-17 15:29:32 -07003342bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3343{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003344 auto vs = toVolumeSource(stream, false);
3345 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003346}
3347
3348bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3349{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003350 auto vs = toVolumeSource(stream, false);
3351 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003352}
3353
Eric Laurente0720872014-03-11 09:30:41 -07003354bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003355{
3356 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003357 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003358 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003359 return true;
3360 }
3361 }
3362 return false;
3363}
3364
Eric Laurent275e8e92014-11-30 15:14:47 -08003365// Register a list of custom mixes with their attributes and format.
3366// When a mix is registered, corresponding input and output profiles are
3367// added to the remote submix hw module. The profile contains only the
3368// parameters (sampling rate, format...) specified by the mix.
3369// The corresponding input remote submix device is also connected.
3370//
3371// When a remote submix device is connected, the address is checked to select the
3372// appropriate profile and the corresponding input or output stream is opened.
3373//
3374// When capture starts, getInputForAttr() will:
3375// - 1 look for a mix matching the address passed in attribtutes tags if any
3376// - 2 if none found, getDeviceForInputSource() will:
3377// - 2.1 look for a mix matching the attributes source
3378// - 2.2 if none found, default to device selection by policy rules
3379// At this time, the corresponding output remote submix device is also connected
3380// and active playback use cases can be transferred to this mix if needed when reconnecting
3381// after AudioTracks are invalidated
3382//
3383// When playback starts, getOutputForAttr() will:
3384// - 1 look for a mix matching the address passed in attribtutes tags if any
3385// - 2 if none found, look for a mix matching the attributes usage
3386// - 3 if none found, default to device and output selection by policy rules.
3387
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003388status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003389{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003390 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3391 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003392 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003393 sp<HwModule> rSubmixModule;
3394 // examine each mix's route type
3395 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003396 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003397 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3398 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3399 ALOGE("Unsupported Policy Mix %zu of %zu: "
3400 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3401 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003402 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003403 break;
3404 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003405 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3406 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003407 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003408 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3409 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003410 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003411 rSubmixModule = mHwModules.getModuleFromName(
3412 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3413 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003414 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003415 i);
3416 res = INVALID_OPERATION;
3417 break;
3418 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003419 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003420
Eric Laurent97ac8712018-07-27 18:59:02 -07003421 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003422 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003423 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003424 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003425 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3426 } else {
3427 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3428 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003429 }
François Gaffie036e1e92015-03-19 10:16:24 +01003430
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003431 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003432 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003433 res = INVALID_OPERATION;
3434 break;
3435 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003436 audio_config_t outputConfig = mix.mFormat;
3437 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003438 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3439 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003440 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3441 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003442 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003443 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003444 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003445 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003446
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003447 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003448 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3449 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3450 ALOGE("Failed to set remote submix device available, type %u, address %s",
3451 mix.mDeviceType, address.string());
3452 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003453 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003454 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3455 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003456 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003457 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003458 i, mixes.size(), type, address.string());
3459
3460 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3461 mix.mDeviceType, mix.mDeviceAddress,
3462 String8(), AUDIO_FORMAT_DEFAULT);
3463 if (device == nullptr) {
3464 res = INVALID_OPERATION;
3465 break;
3466 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003468 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003469 // First try to find an already opened output supporting the device
3470 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003471 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003472
Eric Laurentc529cf62020-04-17 18:19:10 -07003473 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003474 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003475 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3476 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003477 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003478 } else {
3479 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003480 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003481 }
3482 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003483 // If no output found, try to find a direct output profile supporting the device
3484 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3485 sp<HwModule> module = mHwModules[i];
3486 for (size_t j = 0;
3487 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3488 j++) {
3489 sp<IOProfile> profile = module->getOutputProfiles()[j];
3490 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3491 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3492 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3493 address.string());
3494 res = INVALID_OPERATION;
3495 } else {
3496 foundOutput = true;
3497 }
3498 }
3499 }
3500 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003501 if (res != NO_ERROR) {
3502 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003503 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003504 res = INVALID_OPERATION;
3505 break;
3506 } else if (!foundOutput) {
3507 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003508 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003509 res = INVALID_OPERATION;
3510 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003511 } else {
3512 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003513 }
Eric Laurentc722f302014-12-10 11:21:49 -08003514 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003515 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003516 if (res != NO_ERROR) {
3517 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003518 } else if (checkOutputs) {
3519 checkForDeviceAndOutputChanges();
3520 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003521 }
3522 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003523}
3524
3525status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3526{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003527 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003528 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003529 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003530 sp<HwModule> rSubmixModule;
3531 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003532 for (const auto& mix : mixes) {
3533 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003534
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003535 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003536 rSubmixModule = mHwModules.getModuleFromName(
3537 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3538 if (rSubmixModule == 0) {
3539 res = INVALID_OPERATION;
3540 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003541 }
3542 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003543
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003544 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003545
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003546 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003547 res = INVALID_OPERATION;
3548 continue;
3549 }
3550
Kevin Rocard04ed0462019-05-02 17:53:24 -07003551 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3552 if (getDeviceConnectionState(device, address.string()) ==
3553 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3554 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3555 address.string(), "remote-submix",
3556 AUDIO_FORMAT_DEFAULT);
3557 if (res != OK) {
3558 ALOGE("Error making RemoteSubmix device unavailable for mix "
3559 "with type %d, address %s", device, address.string());
3560 }
3561 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003562 }
jiabin5740f082019-08-19 15:08:30 -07003563 rSubmixModule->removeOutputProfile(address.c_str());
3564 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003565
Kevin Rocard153f92d2018-12-18 18:33:28 -08003566 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003567 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003568 res = INVALID_OPERATION;
3569 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003570 } else {
3571 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003572 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003573 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003574 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003575 if (res == NO_ERROR && checkOutputs) {
3576 checkForDeviceAndOutputChanges();
3577 updateCallAndOutputRouting();
3578 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003579 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003580}
3581
Mikhail Naganov100f0122018-11-29 11:22:16 -08003582void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3583{
3584 size_t i = 0;
3585 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3586 for (const auto& fmt : mManualSurroundFormats) {
3587 if (i++ != 0) dst->append(", ");
3588 std::string sfmt;
3589 FormatConverter::toString(fmt, sfmt);
3590 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3591 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3592 }
3593}
3594
Eric Laurentc529cf62020-04-17 18:19:10 -07003595// Returns true if all devices types match the predicate and are supported by one HW module
3596bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003597 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003598 std::function<bool(audio_devices_t)> predicate,
3599 const char *context) {
3600 for (size_t i = 0; i < devices.size(); i++) {
3601 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003602 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003603 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003604 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003605 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003606 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003607 return false;
3608 }
3609 }
3610 return true;
3611}
3612
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003613status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003614 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003615 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003616 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3617 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003618 }
3619 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003620 if (res != NO_ERROR) {
3621 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3622 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003623 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003624
3625 checkForDeviceAndOutputChanges();
3626 updateCallAndOutputRouting();
3627
3628 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003629}
3630
3631status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3632 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003633 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3634 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003635 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003636 __FUNCTION__, uid);
3637 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003638 }
3639
Eric Laurentc529cf62020-04-17 18:19:10 -07003640 checkForDeviceAndOutputChanges();
3641 updateCallAndOutputRouting();
3642
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003643 return res;
3644}
3645
Eric Laurent2517af32020-11-25 15:31:27 +01003646
jiabin0a488932020-08-07 17:32:40 -07003647status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3648 device_role_t role,
3649 const AudioDeviceTypeAddrVector &devices) {
3650 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3651 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003652
Eric Laurentc529cf62020-04-17 18:19:10 -07003653 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003654 return BAD_VALUE;
3655 }
jiabin0a488932020-08-07 17:32:40 -07003656 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003657 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003658 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3659 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003660 return status;
3661 }
3662
3663 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003664
3665 bool forceVolumeReeval = false;
3666 // FIXME: workaround for truncated touch sounds
3667 // to be removed when the problem is handled by system UI
3668 uint32_t delayMs = 0;
3669 if (strategy == mCommunnicationStrategy) {
3670 forceVolumeReeval = true;
3671 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3672 updateInputRouting();
3673 }
3674 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003675
3676 return NO_ERROR;
3677}
3678
3679void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3680{
3681 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003682 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003683 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003684 // Only apply special touch sound delay once
3685 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003686 }
3687 for (size_t i = 0; i < mOutputs.size(); i++) {
3688 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3689 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003690 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3691 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003692 // As done in setDeviceConnectionState, we could also fix default device issue by
3693 // preventing the force re-routing in case of default dev that distinguishes on address.
3694 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003695 bool forceRouting = !newDevices.isEmpty();
3696 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3697 true /*requiresMuteCheck*/,
3698 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003699 // Only apply special touch sound delay once
3700 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003701 }
3702 if (forceVolumeReeval && !newDevices.isEmpty()) {
3703 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3704 }
3705 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003706 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003707}
3708
Eric Laurent2517af32020-11-25 15:31:27 +01003709void AudioPolicyManager::updateInputRouting() {
3710 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303711 // Skip for hotword recording as the input device switch
3712 // is handled within sound trigger HAL
3713 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3714 continue;
3715 }
Eric Laurent2517af32020-11-25 15:31:27 +01003716 auto newDevice = getNewInputDevice(activeDesc);
3717 // Force new input selection if the new device can not be reached via current input
3718 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3719 setInputDevice(activeDesc->mIoHandle, newDevice);
3720 } else {
3721 closeInput(activeDesc->mIoHandle);
3722 }
3723 }
3724}
3725
jiabin0a488932020-08-07 17:32:40 -07003726status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3727 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003728{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003729 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003730
jiabin0a488932020-08-07 17:32:40 -07003731 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003732 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003733 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3734 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003735 return status;
3736 }
3737
3738 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003739
3740 bool forceVolumeReeval = false;
3741 // FIXME: workaround for truncated touch sounds
3742 // to be removed when the problem is handled by system UI
3743 uint32_t delayMs = 0;
3744 if (strategy == mCommunnicationStrategy) {
3745 forceVolumeReeval = true;
3746 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3747 updateInputRouting();
3748 }
3749 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003750
3751 return NO_ERROR;
3752}
3753
jiabin0a488932020-08-07 17:32:40 -07003754status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3755 device_role_t role,
3756 AudioDeviceTypeAddrVector &devices) {
3757 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003758}
3759
Jiabin Huang3b98d322020-09-03 17:54:16 +00003760status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3761 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3762 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3763 dumpAudioDeviceTypeAddrVector(devices).c_str());
3764
Mikhail Naganov55773032020-10-01 15:08:13 -07003765 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003766 return BAD_VALUE;
3767 }
3768 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3769 ALOGW_IF(status != NO_ERROR,
3770 "Engine could not set preferred devices %s for audio source %d role %d",
3771 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3772
3773 return status;
3774}
3775
3776status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3777 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3778 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3779 dumpAudioDeviceTypeAddrVector(devices).c_str());
3780
Mikhail Naganov55773032020-10-01 15:08:13 -07003781 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003782 return BAD_VALUE;
3783 }
3784 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3785 ALOGW_IF(status != NO_ERROR,
3786 "Engine could not add preferred devices %s for audio source %d role %d",
3787 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3788
Eric Laurent2517af32020-11-25 15:31:27 +01003789 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003790 return status;
3791}
3792
3793status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3794 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3795{
3796 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3797 dumpAudioDeviceTypeAddrVector(devices).c_str());
3798
Mikhail Naganov55773032020-10-01 15:08:13 -07003799 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003800 return BAD_VALUE;
3801 }
3802
3803 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3804 audioSource, role, devices);
3805 ALOGW_IF(status != NO_ERROR,
3806 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3807
Eric Laurent2517af32020-11-25 15:31:27 +01003808 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003809 return status;
3810}
3811
3812status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3813 device_role_t role) {
3814 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3815
3816 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3817 ALOGW_IF(status != NO_ERROR,
3818 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3819
Eric Laurent2517af32020-11-25 15:31:27 +01003820 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003821 return status;
3822}
3823
3824status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3825 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3826 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3827}
3828
Oscar Azucena90e77632019-11-27 17:12:28 -08003829status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003830 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003831 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003832 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3833 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003834 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003835 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3836 if (status != NO_ERROR) {
3837 ALOGE("%s() could not set device affinity for userId %d",
3838 __FUNCTION__, userId);
3839 return status;
3840 }
3841
3842 // reevaluate outputs for all devices
3843 checkForDeviceAndOutputChanges();
3844 updateCallAndOutputRouting();
3845
3846 return NO_ERROR;
3847}
3848
3849status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003850 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003851 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3852 if (status != NO_ERROR) {
3853 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3854 __FUNCTION__, userId);
3855 return status;
3856 }
3857
3858 // reevaluate outputs for all devices
3859 checkForDeviceAndOutputChanges();
3860 updateCallAndOutputRouting();
3861
3862 return NO_ERROR;
3863}
3864
Andy Hungc29d82b2018-10-05 12:23:17 -07003865void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003866{
Andy Hungc29d82b2018-10-05 12:23:17 -07003867 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003868 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003869 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003870 std::string stateLiteral;
3871 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003872 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003873 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3874 "communications", "media", "record", "dock", "system",
3875 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3876 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3877 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003878 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3879 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3880 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3881 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3882 dst->append(" (MANUAL: ");
3883 dumpManualSurroundFormats(dst);
3884 dst->append(")");
3885 }
3886 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003887 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003888 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3889 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003890 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003891 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003892
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003893 dst->append("\n");
3894 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3895 dst->append("\n");
3896 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003897 mHwModulesAll.dump(dst);
3898 mOutputs.dump(dst);
3899 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003900 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003901 mAudioPatches.dump(dst);
3902 mPolicyMixes.dump(dst);
3903 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003904
Kevin Rocardb99cc752019-03-21 20:52:24 -07003905 dst->appendFormat(" AllowedCapturePolicies:\n");
3906 for (auto& policy : mAllowedCapturePolicies) {
3907 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3908 }
3909
François Gaffiec005e562018-11-06 15:04:49 +01003910 dst->appendFormat("\nPolicy Engine dump:\n");
3911 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003912}
3913
3914status_t AudioPolicyManager::dump(int fd)
3915{
3916 String8 result;
3917 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003918 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003919 return NO_ERROR;
3920}
3921
Kevin Rocardb99cc752019-03-21 20:52:24 -07003922status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3923{
3924 mAllowedCapturePolicies[uid] = capturePolicy;
3925 return NO_ERROR;
3926}
3927
Eric Laurente552edb2014-03-10 17:42:56 -07003928// This function checks for the parameters which can be offloaded.
3929// This can be enhanced depending on the capability of the DSP and policy
3930// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003931audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003932{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003933 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003934 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003935 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003936 offloadInfo.format,
3937 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3938 offloadInfo.has_video);
3939
jiabin2b9d5a12021-12-10 01:06:29 +00003940 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003941 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003942 }
3943
3944 // See if there is a profile to support this.
3945 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003946 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003947 offloadInfo.sample_rate,
3948 offloadInfo.format,
3949 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003950 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3951 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003952 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3953 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3954 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003955 if (profile == nullptr) {
3956 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3957 }
3958 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3959 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3960 }
3961 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003962}
3963
Michael Chana94fbb22018-04-24 14:31:19 +10003964bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3965 const audio_attributes_t& attributes) {
3966 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003967 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003968 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3969 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003970 config.sample_rate,
3971 config.format,
3972 config.channel_mask,
3973 output_flags,
3974 true /* directOnly */);
3975 ALOGV("%s() profile %sfound with name: %s, "
3976 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3977 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003978 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003979 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003980
3981 // also try the MSD module if compatible profile not found
3982 if (profile == nullptr) {
3983 profile = getMsdProfileForOutput(outputDevices,
3984 config.sample_rate,
3985 config.format,
3986 config.channel_mask,
3987 output_flags,
3988 true /* directOnly */);
3989 ALOGV("%s() MSD profile %sfound with name: %s, "
3990 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3991 __FUNCTION__, profile != 0 ? "" : "NOT ",
3992 (profile != 0 ? profile->getTagName().c_str() : "null"),
3993 config.sample_rate, config.format, config.channel_mask, output_flags);
3994 }
3995 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003996}
3997
jiabin2b9d5a12021-12-10 01:06:29 +00003998bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3999 bool durationIgnored) {
4000 if (mMasterMono) {
4001 return false; // no offloading if mono is set.
4002 }
4003
4004 // Check if offload has been disabled
4005 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4006 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4007 return false;
4008 }
4009
4010 // Check if stream type is music, then only allow offload as of now.
4011 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4012 {
4013 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4014 return false;
4015 }
4016
4017 //TODO: enable audio offloading with video when ready
4018 const bool allowOffloadWithVideo =
4019 property_get_bool("audio.offload.video", false /* default_value */);
4020 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4021 ALOGV("%s: has_video == true, returning false", __func__);
4022 return false;
4023 }
4024
4025 //If duration is less than minimum value defined in property, return false
4026 const int min_duration_secs = property_get_int32(
4027 "audio.offload.min.duration.secs", -1 /* default_value */);
4028 if (!durationIgnored) {
4029 if (min_duration_secs >= 0) {
4030 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4031 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4032 __func__, min_duration_secs);
4033 return false;
4034 }
4035 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4036 ALOGV("%s: Offload denied by duration < default min(=%u)",
4037 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4038 return false;
4039 }
4040 }
4041
4042 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4043 // creating an offloaded track and tearing it down immediately after start when audioflinger
4044 // detects there is an active non offloadable effect.
4045 // FIXME: We should check the audio session here but we do not have it in this context.
4046 // This may prevent offloading in rare situations where effects are left active by apps
4047 // in the background.
4048 if (mEffects.isNonOffloadableEffectEnabled()) {
4049 return false;
4050 }
4051
4052 return true;
4053}
4054
4055audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4056 const audio_config_t *config) {
4057 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4058 offloadInfo.format = config->format;
4059 offloadInfo.sample_rate = config->sample_rate;
4060 offloadInfo.channel_mask = config->channel_mask;
4061 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4062 offloadInfo.has_video = false;
4063 offloadInfo.is_streaming = false;
4064 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4065
4066 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4067 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4068 audio_flags_to_audio_output_flags(attr->flags, &flags);
4069 // only retain flags that will drive compressed offload or passthrough
4070 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4071 if (offloadPossible) {
4072 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4073 }
4074 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4075
Dorin Drimusfae3c642022-03-17 18:36:30 +01004076 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004077 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004078 DeviceVector outputDevices = engineOutputDevices;
4079 // the MSD module checks for different conditions and output devices
4080 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4081 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4082 continue;
4083 }
4084 outputDevices = getMsdAudioOutDevices();
4085 }
jiabin2b9d5a12021-12-10 01:06:29 +00004086 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004087 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004088 config->sample_rate, nullptr /*updatedSamplingRate*/,
4089 config->format, nullptr /*updatedFormat*/,
4090 config->channel_mask, nullptr /*updatedChannelMask*/,
4091 flags)) {
4092 continue;
4093 }
4094 // reject profiles not corresponding to a device currently available
4095 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4096 continue;
4097 }
4098 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4099 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004100 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004101 != AUDIO_DIRECT_NOT_SUPPORTED) {
4102 // Already reports offload gapless supported. No need to report offload support.
4103 continue;
4104 }
4105 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4106 != AUDIO_OUTPUT_FLAG_NONE) {
4107 // If offload gapless is reported, no need to report offload support.
4108 directMode = (audio_direct_mode_t) ((directMode &
4109 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4110 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4111 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004112 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004113 }
4114 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004115 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004116 }
4117 }
4118 }
4119 return directMode;
4120}
4121
Dorin Drimusf2196d82022-01-03 12:11:18 +01004122status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4123 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004124 if (mEffects.isNonOffloadableEffectEnabled()) {
4125 return OK;
4126 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004127 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004128 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004129 if (status != OK) {
4130 return status;
4131 }
4132 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4133 if (devices.empty()) {
4134 return OK; // no output devices for the attributes
4135 }
4136
4137 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004138 // the MSD module checks for different conditions
4139 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4140 continue;
4141 }
4142 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4143 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004144 continue;
4145 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004146 // allow only profiles that support all the available and routed devices
4147 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004148 != devices.size()) {
4149 continue;
4150 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004151 audioProfilesVector.addAllValidProfiles(
4152 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004153 }
4154 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004155
4156 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4157 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4158 if (msdModule != nullptr) {
4159 if (msdHasPatchesToAllDevices(devices)) {
4160 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4161 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4162 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4163 continue;
4164 }
4165 audioProfilesVector.addAllValidProfiles(
4166 outputProfile->asAudioPort()->getAudioProfiles());
4167 }
4168 } else {
4169 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4170 }
4171 }
4172
Dorin Drimusf2196d82022-01-03 12:11:18 +01004173 return NO_ERROR;
4174}
4175
Eric Laurent6a94d692014-05-20 11:18:06 -07004176status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4177 audio_port_type_t type,
4178 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004179 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004180 unsigned int *generation)
4181{
jiabin19cdba52020-11-24 11:28:58 -08004182 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4183 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 return BAD_VALUE;
4185 }
4186 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004187 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004188 *num_ports = 0;
4189 }
4190
4191 size_t portsWritten = 0;
4192 size_t portsMax = *num_ports;
4193 *num_ports = 0;
4194 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004195 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4196 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004198 for (const auto& dev : mAvailableOutputDevices) {
4199 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004200 continue;
4201 }
4202 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004203 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004204 }
4205 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004206 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 }
4208 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004209 for (const auto& dev : mAvailableInputDevices) {
4210 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004211 continue;
4212 }
4213 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004214 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004215 }
4216 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004217 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 }
4219 }
4220 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4221 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4222 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4223 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4224 }
4225 *num_ports += mInputs.size();
4226 }
4227 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004228 size_t numOutputs = 0;
4229 for (size_t i = 0; i < mOutputs.size(); i++) {
4230 if (!mOutputs[i]->isDuplicated()) {
4231 numOutputs++;
4232 if (portsWritten < portsMax) {
4233 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4234 }
4235 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004236 }
Eric Laurent84c70242014-06-23 08:46:27 -07004237 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004238 }
4239 }
4240 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004241 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004242 return NO_ERROR;
4243}
4244
Mikhail Naganov15f46712023-03-23 14:52:15 -07004245status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4246 std::vector<media::AudioPortFw>* _aidl_return) {
4247 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4248 audio_port_v7 port;
4249 dev->toAudioPort(&port);
4250 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4251 _aidl_return->push_back(std::move(aidlPort));
4252 return OK;
4253 };
4254
4255 for (const auto& module : mHwModulesAll) {
4256 for (const auto& dev : module->getDeclaredDevices()) {
4257 if (role == media::AudioPortRole::NONE ||
4258 ((role == media::AudioPortRole::SOURCE)
4259 == audio_is_input_device(dev->type()))) {
4260 RETURN_STATUS_IF_ERROR(pushPort(dev));
4261 }
4262 }
4263 }
4264 return OK;
4265}
4266
jiabin19cdba52020-11-24 11:28:58 -08004267status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004268{
Eric Laurent99fcae42018-05-17 16:59:18 -07004269 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4270 return BAD_VALUE;
4271 }
4272 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4273 if (dev != 0) {
4274 dev->toAudioPort(port);
4275 return NO_ERROR;
4276 }
4277 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4278 if (dev != 0) {
4279 dev->toAudioPort(port);
4280 return NO_ERROR;
4281 }
4282 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4283 if (out != 0) {
4284 out->toAudioPort(port);
4285 return NO_ERROR;
4286 }
4287 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4288 if (in != 0) {
4289 in->toAudioPort(port);
4290 return NO_ERROR;
4291 }
4292 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004293}
4294
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004295status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4296 audio_patch_handle_t *handle,
4297 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004298{
François Gaffieafd4cea2019-11-18 15:50:22 +01004299 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004300 if (handle == NULL || patch == NULL) {
4301 return BAD_VALUE;
4302 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004303 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004304 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004305 return BAD_VALUE;
4306 }
4307 // only one source per audio patch supported for now
4308 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004309 return INVALID_OPERATION;
4310 }
Eric Laurent874c42872014-08-08 15:13:39 -07004311 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004312 return INVALID_OPERATION;
4313 }
Eric Laurent874c42872014-08-08 15:13:39 -07004314 for (size_t i = 0; i < patch->num_sinks; i++) {
4315 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4316 return INVALID_OPERATION;
4317 }
4318 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004319
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004320 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4321 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4322 if (srcDevice == nullptr || sinkDevice == nullptr) {
4323 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4324 return BAD_VALUE;
4325 }
4326 ALOGV("%s between source %s and sink %s", __func__,
4327 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4328 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4329 // Default attributes, default volume priority, not to infer with non raw audio patches.
4330 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4331 const struct audio_port_config *source = &patch->sources[0];
4332 sp<SourceClientDescriptor> sourceDesc =
4333 new InternalSourceClientDescriptor(
4334 portId, uid, attributes, *source, srcDevice, sinkDevice,
4335 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4336
4337 status_t status =
4338 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4339
4340 if (status != NO_ERROR) {
4341 return INVALID_OPERATION;
4342 }
4343 mAudioSources.add(portId, sourceDesc);
4344 return NO_ERROR;
4345}
4346
4347status_t AudioPolicyManager::connectAudioSourceToSink(
4348 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4349 const struct audio_patch *patch,
4350 audio_patch_handle_t &handle,
4351 uid_t uid, uint32_t delayMs)
4352{
4353 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4354 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4355 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4356 return INVALID_OPERATION;
4357 }
4358 sourceDesc->connect(handle, sinkDevice);
4359 if (isMsdPatch(handle)) {
4360 return NO_ERROR;
4361 }
4362 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4363 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4364 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4365 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4366 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4367 goto FailurePatchAdded;
4368 }
4369 status = swOutput->start();
4370 if (status != NO_ERROR) {
4371 goto FailureSourceAdded;
4372 }
4373 swOutput->addClient(sourceDesc);
4374 status = startSource(swOutput, sourceDesc, &delayMs);
4375 if (status != NO_ERROR) {
4376 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4377 goto FailureSourceActive;
4378 }
4379 if (delayMs != 0) {
4380 usleep(delayMs * 1000);
4381 }
4382 return NO_ERROR;
4383
4384FailureSourceActive:
4385 swOutput->stop();
4386 releaseOutput(sourceDesc->portId());
4387FailureSourceAdded:
4388 sourceDesc->setSwOutput(nullptr);
4389FailurePatchAdded:
4390 releaseAudioPatchInternal(handle);
4391 return INVALID_OPERATION;
4392}
4393
4394status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4395 audio_patch_handle_t *handle,
4396 uid_t uid, uint32_t delayMs,
4397 const sp<SourceClientDescriptor>& sourceDesc)
4398{
4399 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004400 sp<AudioPatch> patchDesc;
4401 ssize_t index = mAudioPatches.indexOfKey(*handle);
4402
François Gaffieafd4cea2019-11-18 15:50:22 +01004403 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4404 patch->sources[0].role,
4405 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004406#if LOG_NDEBUG == 0
4407 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004408 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4409 patch->sinks[i].role,
4410 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004411 }
4412#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004413
4414 if (index >= 0) {
4415 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004416 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4417 __func__, mUidCached, patchDesc->getUid(), uid);
4418 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 return INVALID_OPERATION;
4420 }
4421 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004422 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004423 }
4424
4425 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004426 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004427 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004428 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004429 return BAD_VALUE;
4430 }
Eric Laurent84c70242014-06-23 08:46:27 -07004431 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4432 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004433 if (patchDesc != 0) {
4434 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004435 ALOGV("%s source id differs for patch current id %d new id %d",
4436 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004437 return BAD_VALUE;
4438 }
4439 }
Eric Laurent874c42872014-08-08 15:13:39 -07004440 DeviceVector devices;
4441 for (size_t i = 0; i < patch->num_sinks; i++) {
4442 // Only support mix to devices connection
4443 // TODO add support for mix to mix connection
4444 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004445 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004446 return INVALID_OPERATION;
4447 }
4448 sp<DeviceDescriptor> devDesc =
4449 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4450 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004451 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004452 return BAD_VALUE;
4453 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004454
François Gaffie11d30102018-11-02 16:09:09 +01004455 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004456 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004457 NULL, // updatedSamplingRate
4458 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004459 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004460 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004461 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004462 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004463 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004464 return INVALID_OPERATION;
4465 }
4466 devices.add(devDesc);
4467 }
4468 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004469 return INVALID_OPERATION;
4470 }
Eric Laurent874c42872014-08-08 15:13:39 -07004471
Eric Laurent6a94d692014-05-20 11:18:06 -07004472 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004473 ALOGV("%s setting device %s on output %d",
4474 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004475 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004476 index = mAudioPatches.indexOfKey(*handle);
4477 if (index >= 0) {
4478 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004479 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004480 }
4481 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004482 patchDesc->setUid(uid);
4483 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004484 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004485 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004486 return INVALID_OPERATION;
4487 }
4488 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4489 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4490 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004491 // only one sink supported when connecting an input device to a mix
4492 if (patch->num_sinks > 1) {
4493 return INVALID_OPERATION;
4494 }
François Gaffie53615e22015-03-19 09:24:12 +01004495 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004496 if (inputDesc == NULL) {
4497 return BAD_VALUE;
4498 }
4499 if (patchDesc != 0) {
4500 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4501 return BAD_VALUE;
4502 }
4503 }
François Gaffie11d30102018-11-02 16:09:09 +01004504 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004506 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004507 return BAD_VALUE;
4508 }
4509
François Gaffie11d30102018-11-02 16:09:09 +01004510 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004511 patch->sinks[0].sample_rate,
4512 NULL, /*updatedSampleRate*/
4513 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004514 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004515 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004516 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004517 // FIXME for the parameter type,
4518 // and the NONE
4519 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004520 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004521 return INVALID_OPERATION;
4522 }
4523 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004524 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004525 device->toString().c_str(), inputDesc->mIoHandle);
4526 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004527 index = mAudioPatches.indexOfKey(*handle);
4528 if (index >= 0) {
4529 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004530 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004531 }
4532 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004533 patchDesc->setUid(uid);
4534 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004535 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004536 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004537 return INVALID_OPERATION;
4538 }
4539 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4540 // device to device connection
4541 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004542 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 return BAD_VALUE;
4544 }
4545 }
François Gaffie11d30102018-11-02 16:09:09 +01004546 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004547 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004548 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004549 return BAD_VALUE;
4550 }
Eric Laurent874c42872014-08-08 15:13:39 -07004551
Eric Laurent6a94d692014-05-20 11:18:06 -07004552 //update source and sink with our own data as the data passed in the patch may
4553 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004554 PatchBuilder patchBuilder;
4555 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004556
4557 // if first sink is to MSD, establish single MSD patch
4558 if (getMsdAudioOutDevices().contains(
4559 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4560 ALOGV("%s patching to MSD", __FUNCTION__);
4561 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4562 goto installPatch;
4563 }
4564
François Gaffieafd4cea2019-11-18 15:50:22 +01004565 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4566 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004567
Eric Laurent874c42872014-08-08 15:13:39 -07004568 for (size_t i = 0; i < patch->num_sinks; i++) {
4569 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004570 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004571 return INVALID_OPERATION;
4572 }
François Gaffie11d30102018-11-02 16:09:09 +01004573 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004574 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004575 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004576 return BAD_VALUE;
4577 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004578 audio_port_config sinkPortConfig = {};
4579 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4580 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004581
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004582 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4583 // volume management purpose (tracking activity)
4584 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4585 // in config XML to reach the sink so that is can be declared as available.
4586 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004587 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004588 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004589 // take care of dynamic routing for SwOutput selection,
4590 audio_attributes_t attributes = sourceDesc->attributes();
4591 audio_stream_type_t stream = sourceDesc->stream();
4592 audio_attributes_t resultAttr;
4593 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4594 config.sample_rate = sourceDesc->config().sample_rate;
4595 config.channel_mask = sourceDesc->config().channel_mask;
4596 config.format = sourceDesc->config().format;
4597 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4598 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4599 bool isRequestedDeviceForExclusiveUse = false;
4600 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004601 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004602 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4603 &stream, sourceDesc->uid(), &config, &flags,
4604 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004605 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004606 if (output == AUDIO_IO_HANDLE_NONE) {
4607 ALOGV("%s no output for device %s",
4608 __FUNCTION__, sinkDevice->toString().c_str());
4609 return INVALID_OPERATION;
4610 }
4611 outputDesc = mOutputs.valueFor(output);
4612 if (outputDesc->isDuplicated()) {
4613 ALOGE("%s output is duplicated", __func__);
4614 return INVALID_OPERATION;
4615 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004616 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4617 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004618 } else {
4619 // Same for "raw patches" aka created from createAudioPatch API
4620 SortedVector<audio_io_handle_t> outputs =
4621 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4622 // if the sink device is reachable via an opened output stream, request to
4623 // go via this output stream by adding a second source to the patch
4624 // description
4625 output = selectOutput(outputs);
4626 if (output == AUDIO_IO_HANDLE_NONE) {
4627 ALOGE("%s no output available for internal patch sink", __func__);
4628 return INVALID_OPERATION;
4629 }
4630 outputDesc = mOutputs.valueFor(output);
4631 if (outputDesc->isDuplicated()) {
4632 ALOGV("%s output for device %s is duplicated",
4633 __func__, sinkDevice->toString().c_str());
4634 return INVALID_OPERATION;
4635 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004636 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004637 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004638 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004639 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004640 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004641 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004642 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4643 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004644 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4645 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004646 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004647 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004648 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004649 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004650 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004651 return INVALID_OPERATION;
4652 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004653 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004654 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004655 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004656 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004657 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004658 srcMixPortConfig.ext.mix.usecase.stream =
4659 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004660 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4661 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004662 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004663 }
Eric Laurent83b88082014-06-20 18:31:16 -07004664 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004665 }
4666 // TODO: check from routing capabilities in config file and other conflicting patches
4667
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004668installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004669 status_t status = installPatch(
4670 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004671 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004672 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 return INVALID_OPERATION;
4674 }
4675 } else {
4676 return BAD_VALUE;
4677 }
4678 } else {
4679 return BAD_VALUE;
4680 }
4681 return NO_ERROR;
4682}
4683
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004684status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004685{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004686 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 ssize_t index = mAudioPatches.indexOfKey(handle);
4688
4689 if (index < 0) {
4690 return BAD_VALUE;
4691 }
4692 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004693 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4694 __func__, mUidCached, patchDesc->getUid(), uid);
4695 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 return INVALID_OPERATION;
4697 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004698 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4699 for (size_t i = 0; i < mAudioSources.size(); i++) {
4700 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4701 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4702 portId = sourceDesc->portId();
4703 break;
4704 }
4705 }
4706 return portId != AUDIO_PORT_HANDLE_NONE ?
4707 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004708}
Eric Laurent6a94d692014-05-20 11:18:06 -07004709
François Gaffieafd4cea2019-11-18 15:50:22 +01004710status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004711 uint32_t delayMs,
4712 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004713{
4714 ALOGV("%s patch %d", __func__, handle);
4715 if (mAudioPatches.indexOfKey(handle) < 0) {
4716 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4717 return BAD_VALUE;
4718 }
4719 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004720 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004721 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004722 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004723 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004724 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004725 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 return BAD_VALUE;
4727 }
4728
François Gaffie11d30102018-11-02 16:09:09 +01004729 setOutputDevices(outputDesc,
4730 getNewOutputDevices(outputDesc, true /*fromCache*/),
4731 true,
4732 0,
4733 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4735 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004736 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004738 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004739 return BAD_VALUE;
4740 }
4741 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004742 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 true,
4744 NULL);
4745 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004746 status_t status =
4747 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4748 ALOGV("%s patch panel returned %d patchHandle %d",
4749 __func__, status, patchDesc->getAfHandle());
4750 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004751 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004752 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004753 // SW or HW Bridge
4754 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4755 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004756 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004757 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4758 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4759 outputDesc = sourceDesc->swOutput().promote();
4760 }
4761 if (outputDesc == nullptr) {
4762 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4763 // releaseOutput has already called closeOutput in case of direct output
4764 return NO_ERROR;
4765 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004766 patchHandle = outputDesc->getPatchHandle();
4767 // When a Sw bridge is released, the mixer used by this bridge will release its
4768 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4769 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4770 // updating hal patch handle (prevent leaks).
4771 // While using a HwBridge, force reconsidering device only if not reusing an existing
4772 // output and no more activity on output (will force to close).
4773 bool force = sourceDesc->useSwBridge() ||
4774 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4775 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4776 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4777 // Reconsider device only for cases:
4778 // 1 / Active Output
4779 // 2 / Inactive Output previously hosting HwBridge
4780 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4781 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4782 sourceDesc->canCloseOutput();
4783 setOutputDevices(outputDesc,
4784 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4785 outputDesc->devices(),
4786 force,
4787 0,
4788 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004789 } else {
4790 return BAD_VALUE;
4791 }
4792 } else {
4793 return BAD_VALUE;
4794 }
4795 return NO_ERROR;
4796}
4797
4798status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4799 struct audio_patch *patches,
4800 unsigned int *generation)
4801{
François Gaffie53615e22015-03-19 09:24:12 +01004802 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 return BAD_VALUE;
4804 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004806 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004807}
4808
Eric Laurente1715a42014-05-20 11:30:42 -07004809status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004810{
Eric Laurente1715a42014-05-20 11:30:42 -07004811 ALOGV("setAudioPortConfig()");
4812
4813 if (config == NULL) {
4814 return BAD_VALUE;
4815 }
4816 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4817 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004818 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4819 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004820 }
4821
Eric Laurenta121f902014-06-03 13:32:54 -07004822 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004823 if (config->type == AUDIO_PORT_TYPE_MIX) {
4824 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004825 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004826 if (outputDesc == NULL) {
4827 return BAD_VALUE;
4828 }
Eric Laurent84c70242014-06-23 08:46:27 -07004829 ALOG_ASSERT(!outputDesc->isDuplicated(),
4830 "setAudioPortConfig() called on duplicated output %d",
4831 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004832 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004833 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004834 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004835 if (inputDesc == NULL) {
4836 return BAD_VALUE;
4837 }
Eric Laurenta121f902014-06-03 13:32:54 -07004838 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004839 } else {
4840 return BAD_VALUE;
4841 }
4842 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4843 sp<DeviceDescriptor> deviceDesc;
4844 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4845 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4846 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4847 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4848 } else {
4849 return BAD_VALUE;
4850 }
4851 if (deviceDesc == NULL) {
4852 return BAD_VALUE;
4853 }
Eric Laurenta121f902014-06-03 13:32:54 -07004854 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004855 } else {
4856 return BAD_VALUE;
4857 }
4858
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004859 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004860 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4861 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004862 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004863 audioPortConfig->toAudioPortConfig(&newConfig, config);
4864 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004865 }
Eric Laurenta121f902014-06-03 13:32:54 -07004866 if (status != NO_ERROR) {
4867 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004868 }
Eric Laurente1715a42014-05-20 11:30:42 -07004869
4870 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004871}
4872
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004873void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4874{
Eric Laurentd60560a2015-04-10 11:31:20 -07004875 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004876 clearAudioPatches(uid);
4877 clearSessionRoutes(uid);
4878}
4879
Eric Laurent6a94d692014-05-20 11:18:06 -07004880void AudioPolicyManager::clearAudioPatches(uid_t uid)
4881{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004882 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004884 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004885 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 }
4887 }
4888}
4889
François Gaffiec005e562018-11-06 15:04:49 +01004890void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004891{
François Gaffiec005e562018-11-06 15:04:49 +01004892 // Take the first attributes following the product strategy as it is used to retrieve the routed
4893 // device. All attributes wihin a strategy follows the same "routing strategy"
4894 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4895 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004896 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004897 for (size_t j = 0; j < mOutputs.size(); j++) {
4898 if (mOutputs.keyAt(j) == ouptutToSkip) {
4899 continue;
4900 }
4901 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004902 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004903 continue;
4904 }
4905 // If the default device for this strategy is on another output mix,
4906 // invalidate all tracks in this strategy to force re connection.
4907 // Otherwise select new device on the output mix.
4908 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004909 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4910 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004911 }
4912 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004913 setOutputDevices(
4914 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004915 }
4916 }
4917}
4918
4919void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4920{
4921 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004922 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004923 for (size_t i = 0; i < mOutputs.size(); i++) {
4924 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004925 for (const auto& client : outputDesc->getClientIterable()) {
4926 if (client->hasPreferredDevice() && client->uid() == uid) {
4927 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004928 auto clientStrategy = client->strategy();
4929 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4930 end(affectedStrategies)) {
4931 continue;
4932 }
4933 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004934 }
4935 }
4936 }
4937 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004938 for (const auto& strategy : affectedStrategies) {
4939 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004940 }
4941
4942 // remove input routes associated with this uid
4943 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004944 for (size_t i = 0; i < mInputs.size(); i++) {
4945 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004946 for (const auto& client : inputDesc->getClientIterable()) {
4947 if (client->hasPreferredDevice() && client->uid() == uid) {
4948 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4949 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004950 }
4951 }
4952 }
4953 // reroute inputs if necessary
4954 SortedVector<audio_io_handle_t> inputsToClose;
4955 for (size_t i = 0; i < mInputs.size(); i++) {
4956 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004957 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004958 inputsToClose.add(inputDesc->mIoHandle);
4959 }
4960 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004961 for (const auto& input : inputsToClose) {
4962 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004963 }
4964}
4965
Eric Laurentd60560a2015-04-10 11:31:20 -07004966void AudioPolicyManager::clearAudioSources(uid_t uid)
4967{
4968 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004969 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4970 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004971 stopAudioSource(mAudioSources.keyAt(i));
4972 }
4973 }
4974}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004975
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004976status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4977 audio_io_handle_t *ioHandle,
4978 audio_devices_t *device)
4979{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004980 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4981 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004982 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004983 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004984
François Gaffiedf372692015-03-19 10:43:27 +01004985 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004986}
4987
Eric Laurentd60560a2015-04-10 11:31:20 -07004988status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004989 const audio_attributes_t *attributes,
4990 audio_port_handle_t *portId,
4991 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004992{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004993 ALOGV("%s", __FUNCTION__);
4994 *portId = AUDIO_PORT_HANDLE_NONE;
4995
4996 if (source == NULL || attributes == NULL || portId == NULL) {
4997 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4998 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004999 return BAD_VALUE;
5000 }
5001
Eric Laurentd60560a2015-04-10 11:31:20 -07005002 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5003 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005004 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5005 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005006 return INVALID_OPERATION;
5007 }
5008
François Gaffie11d30102018-11-02 16:09:09 +01005009 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005010 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005011 String8(source->ext.device.address),
5012 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005013 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005014 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005015 return BAD_VALUE;
5016 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005017
jiabin4ef93452019-09-10 14:29:54 -07005018 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005019
François Gaffieaaac0fd2018-11-22 17:56:39 +01005020 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005021 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005022 mEngine->getStreamTypeForAttributes(*attributes),
5023 mEngine->getProductStrategyForAttributes(*attributes),
5024 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005025
5026 status_t status = connectAudioSource(sourceDesc);
5027 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005028 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005029 }
5030 return status;
5031}
5032
Francois Gaffie601801d2021-06-22 13:27:39 +02005033sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5034 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5035{
5036 ALOGV("%s", __FUNCTION__);
5037 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5038
5039 status_t status = startAudioSource(source, attributes, &portId, uid);
5040 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5041 return mAudioSources.valueFor(portId);
5042}
5043
5044
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005045status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005046{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005047 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005048
5049 // make sure we only have one patch per source.
5050 disconnectAudioSource(sourceDesc);
5051
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005052 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005053 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5054 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5055 sourceDesc->srcDevice()->type(),
5056 String8(sourceDesc->srcDevice()->address().c_str()),
5057 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005058 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005059 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005060 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005061 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005062 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5063 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5064 return INVALID_OPERATION;
5065 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005066 PatchBuilder patchBuilder;
5067 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5068 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005069
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005070 return connectAudioSourceToSink(
5071 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005072}
5073
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005074status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005075{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005076 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5077 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005078 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005079 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005080 return BAD_VALUE;
5081 }
5082 status_t status = disconnectAudioSource(sourceDesc);
5083
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005084 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005085 return status;
5086}
5087
Andy Hung2ddee192015-12-18 17:34:44 -08005088status_t AudioPolicyManager::setMasterMono(bool mono)
5089{
5090 if (mMasterMono == mono) {
5091 return NO_ERROR;
5092 }
5093 mMasterMono = mono;
5094 // if enabling mono we close all offloaded devices, which will invalidate the
5095 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5096 // for recreating the new AudioTrack as non-offloaded PCM.
5097 //
5098 // If disabling mono, we leave all tracks as is: we don't know which clients
5099 // and tracks are able to be recreated as offloaded. The next "song" should
5100 // play back offloaded.
5101 if (mMasterMono) {
5102 Vector<audio_io_handle_t> offloaded;
5103 for (size_t i = 0; i < mOutputs.size(); ++i) {
5104 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5105 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5106 offloaded.push(desc->mIoHandle);
5107 }
5108 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005109 for (const auto& handle : offloaded) {
5110 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005111 }
5112 }
5113 // update master mono for all remaining outputs
5114 for (size_t i = 0; i < mOutputs.size(); ++i) {
5115 updateMono(mOutputs.keyAt(i));
5116 }
5117 return NO_ERROR;
5118}
5119
5120status_t AudioPolicyManager::getMasterMono(bool *mono)
5121{
5122 *mono = mMasterMono;
5123 return NO_ERROR;
5124}
5125
Eric Laurentac9cef52017-06-09 15:46:26 -07005126float AudioPolicyManager::getStreamVolumeDB(
5127 audio_stream_type_t stream, int index, audio_devices_t device)
5128{
jiabin9a3361e2019-10-01 09:38:30 -07005129 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005130}
5131
jiabin81772902018-04-02 17:52:27 -07005132status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5133 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005134 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005135{
Kriti Dang6537def2021-03-02 13:46:59 +01005136 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5137 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005138 return BAD_VALUE;
5139 }
Kriti Dang6537def2021-03-02 13:46:59 +01005140 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5141 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005142
5143 size_t formatsWritten = 0;
5144 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005145
Kriti Dang6537def2021-03-02 13:46:59 +01005146 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005147 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5148 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005149 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005150 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005151 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005152 bool formatEnabled = true;
5153 switch (forceUse) {
5154 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005155 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005156 break;
5157 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5158 formatEnabled = false;
5159 break;
5160 default: // AUTO or ALWAYS => true
5161 break;
jiabin81772902018-04-02 17:52:27 -07005162 }
5163 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5164 }
jiabin81772902018-04-02 17:52:27 -07005165 }
5166 return NO_ERROR;
5167}
5168
Kriti Dang6537def2021-03-02 13:46:59 +01005169status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5170 audio_format_t *surroundFormats) {
5171 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5172 return BAD_VALUE;
5173 }
5174 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5175 __func__, *numSurroundFormats, surroundFormats);
5176
5177 size_t formatsWritten = 0;
5178 size_t formatsMax = *numSurroundFormats;
5179 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5180
5181 // Return formats from all device profiles that have already been resolved by
5182 // checkOutputsForDevice().
5183 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5184 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5185 audio_devices_t deviceType = device->type();
5186 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5187 // returns formats reported by HDMI devices.
5188 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5189 continue;
5190 }
5191 // Formats reported by sink devices
5192 std::unordered_set<audio_format_t> formatset;
5193 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5194 formatset.insert(it->second.begin(), it->second.end());
5195 }
5196
5197 // Formats hard-coded in the in policy configuration file (if any).
5198 FormatVector encodedFormats = device->encodedFormats();
5199 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5200 // Filter the formats which are supported by the vendor hardware.
5201 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5202 if (mConfig.getSurroundFormats().count(*it) != 0) {
5203 formats.insert(*it);
5204 } else {
5205 for (const auto& pair : mConfig.getSurroundFormats()) {
5206 if (pair.second.count(*it) != 0) {
5207 formats.insert(pair.first);
5208 break;
5209 }
5210 }
5211 }
5212 }
5213 }
5214 *numSurroundFormats = formats.size();
5215 for (const auto& format: formats) {
5216 if (formatsWritten < formatsMax) {
5217 surroundFormats[formatsWritten++] = format;
5218 }
5219 }
5220 return NO_ERROR;
5221}
5222
jiabin81772902018-04-02 17:52:27 -07005223status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5224{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005225 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005226 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5227 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005228 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005229 return BAD_VALUE;
5230 }
5231
Mikhail Naganov100f0122018-11-29 11:22:16 -08005232 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5233 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005234 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005235 return INVALID_OPERATION;
5236 }
5237
Mikhail Naganov100f0122018-11-29 11:22:16 -08005238 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005239 return NO_ERROR;
5240 }
5241
Mikhail Naganov100f0122018-11-29 11:22:16 -08005242 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005243 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005244 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005245 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005246 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005247 }
5248 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005249 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005250 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005251 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005252 }
5253 }
5254
5255 sp<SwAudioOutputDescriptor> outputDesc;
5256 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005257 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5258 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005259 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5260 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005261 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005262 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005263 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5264 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5265 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005266 name.c_str(),
5267 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005268 if (status != NO_ERROR) {
5269 continue;
5270 }
5271 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5272 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5273 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005274 name.c_str(),
5275 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005276 profileUpdated |= (status == NO_ERROR);
5277 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005278 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005279 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005280 AUDIO_DEVICE_IN_HDMI);
5281 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5282 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005283 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005284 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005285 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5286 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5287 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005288 name.c_str(),
5289 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005290 if (status != NO_ERROR) {
5291 continue;
5292 }
5293 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5294 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5295 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005296 name.c_str(),
5297 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005298 profileUpdated |= (status == NO_ERROR);
5299 }
5300
jiabin81772902018-04-02 17:52:27 -07005301 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005302 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005303 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005304 }
5305
5306 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5307}
5308
Eric Laurent5ada82e2019-08-29 17:53:54 -07005309void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005310{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005311 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005312 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005313 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005314 }
5315}
5316
jiabin6012f912018-11-02 17:06:30 -07005317bool AudioPolicyManager::isHapticPlaybackSupported()
5318{
5319 for (const auto& hwModule : mHwModules) {
5320 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5321 for (const auto &outProfile : outputProfiles) {
5322 struct audio_port audioPort;
5323 outProfile->toAudioPort(&audioPort);
5324 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5325 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5326 return true;
5327 }
5328 }
5329 }
5330 }
5331 return false;
5332}
5333
Carter Hsu325a8eb2022-01-19 19:56:51 +08005334bool AudioPolicyManager::isUltrasoundSupported()
5335{
5336 bool hasUltrasoundOutput = false;
5337 bool hasUltrasoundInput = false;
5338 for (const auto& hwModule : mHwModules) {
5339 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5340 if (!hasUltrasoundOutput) {
5341 for (const auto &outProfile : outputProfiles) {
5342 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5343 hasUltrasoundOutput = true;
5344 break;
5345 }
5346 }
5347 }
5348
5349 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5350 if (!hasUltrasoundInput) {
5351 for (const auto &inputProfile : inputProfiles) {
5352 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5353 hasUltrasoundInput = true;
5354 break;
5355 }
5356 }
5357 }
5358
5359 if (hasUltrasoundOutput && hasUltrasoundInput)
5360 return true;
5361 }
5362 return false;
5363}
5364
Eric Laurent8340e672019-11-06 11:01:08 -08005365bool AudioPolicyManager::isCallScreenModeSupported()
5366{
5367 return getConfig().isCallScreenModeSupported();
5368}
5369
5370
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005371status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005372{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005373 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005374 if (!sourceDesc->isConnected()) {
5375 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5376 return NO_ERROR;
5377 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005378 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5379 if (swOutput != 0) {
5380 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005381 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005382 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005383 }
jiabinbce0c1d2020-10-05 11:20:18 -07005384 if (releaseOutput(sourceDesc->portId())) {
5385 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5386 // no need to release audio patch here but just return NO_ERROR.
5387 return NO_ERROR;
5388 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005389 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005390 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005391 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005392 // close Hwoutput and remove from mHwOutputs
5393 } else {
5394 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5395 }
5396 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005397 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005398 sourceDesc->disconnect();
5399 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005400}
5401
François Gaffiec005e562018-11-06 15:04:49 +01005402sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5403 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005404{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005405 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005406 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005407 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005408 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005409 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5410 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005411 source = sourceDesc;
5412 break;
5413 }
5414 }
5415 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005416}
5417
Eric Laurentb4f42a92022-01-17 17:37:31 +01005418bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005419 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005420 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005421{
5422 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5423 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005424 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005425 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005426 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5427 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5428 return false;
5429 }
5430 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5431 return false;
5432 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005433 }
5434
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005435 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005436 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005437 if (profile == nullptr) {
5438 return false;
5439 }
5440
5441 // The caller can have the audio config criteria ignored by either passing a null ptr or
5442 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005443 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005444 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005445
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005446 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005447 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005448 return false;
5449 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005450 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005451 return true;
5452}
5453
5454void AudioPolicyManager::checkVirtualizerClientRoutes() {
5455 std::set<audio_stream_type_t> streamsToInvalidate;
5456 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005457 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5458 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005459 audio_attributes_t attr = client->attributes();
5460 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5461 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5462 audio_config_base_t clientConfig = client->config();
5463 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005464 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005465 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005466 streamsToInvalidate.insert(client->stream());
5467 }
5468 }
5469 }
5470
5471 for (audio_stream_type_t stream : streamsToInvalidate) {
5472 mpClientInterface->invalidateStream(stream);
5473 }
5474}
5475
Eric Laurente191d1b2022-04-15 11:59:25 +02005476
5477bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5478 const sp<SwAudioOutputDescriptor>& outputDesc) {
5479 if (outputDesc->isDuplicated()) {
5480 return false;
5481 }
5482 DeviceVector devices = outputDesc->supportedDevices();
5483 for (size_t i = 0; i < mOutputs.size(); i++) {
5484 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5485 if (desc == outputDesc || desc->isDuplicated()) {
5486 continue;
5487 }
5488 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5489 if (!sharedDevices.isEmpty()
5490 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5491 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5492 return false;
5493 }
5494 }
5495 return true;
5496}
5497
5498
Eric Laurentfa0f6742021-08-17 18:39:44 +02005499status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005500 const audio_attributes_t *attr,
5501 audio_io_handle_t *output) {
5502 *output = AUDIO_IO_HANDLE_NONE;
5503
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005504 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5505 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5506 audio_config_t *configPtr = nullptr;
5507 audio_config_t config;
5508 if (mixerConfig != nullptr) {
5509 config = audio_config_initializer(mixerConfig);
5510 configPtr = &config;
5511 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005512 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005513 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005514 return BAD_VALUE;
5515 }
5516
5517 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005518 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005519 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005520 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005521 return BAD_VALUE;
5522 }
5523
Eric Laurente191d1b2022-04-15 11:59:25 +02005524 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005525 for (size_t i = 0; i < mOutputs.size(); i++) {
5526 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005527 if (!desc->isDuplicated()
5528 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5529 spatializerOutputs.push_back(desc);
5530 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005531 }
5532 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005533 mSpatializerOutput.clear();
5534 bool outputsChanged = false;
5535 for (const auto& desc : spatializerOutputs) {
5536 if (desc->mProfile == profile
5537 && (configPtr == nullptr
5538 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5539 mSpatializerOutput = desc;
5540 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5541 } else {
5542 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5543 " and devices %s", __func__, desc->mIoHandle,
5544 configPtr != nullptr ? configPtr->channel_mask : 0,
5545 devices.toString().c_str());
5546 closeOutput(desc->mIoHandle);
5547 outputsChanged = true;
5548 }
Eric Laurent39095982021-08-24 18:29:27 +02005549 }
5550
Eric Laurente191d1b2022-04-15 11:59:25 +02005551 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005552 sp<SwAudioOutputDescriptor> desc =
5553 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005554 if (desc != nullptr) {
5555 mSpatializerOutput = desc;
5556 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005557 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005558 }
5559
5560 checkVirtualizerClientRoutes();
5561
Eric Laurente191d1b2022-04-15 11:59:25 +02005562 if (outputsChanged) {
5563 mPreviousOutputs = mOutputs;
5564 mpClientInterface->onAudioPortListUpdate();
5565 }
5566
5567 if (mSpatializerOutput == nullptr) {
5568 ALOGV("%s could not open spatializer output with requested config", __func__);
5569 return BAD_VALUE;
5570 }
Eric Laurent39095982021-08-24 18:29:27 +02005571 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005572 ALOGV("%s returning new spatializer output %d", __func__, *output);
5573 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005574}
5575
Eric Laurentfa0f6742021-08-17 18:39:44 +02005576status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5577 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005578 return INVALID_OPERATION;
5579 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005580 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005581 return BAD_VALUE;
5582 }
Eric Laurent39095982021-08-24 18:29:27 +02005583
Eric Laurente191d1b2022-04-15 11:59:25 +02005584 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5585 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5586 closeOutput(mSpatializerOutput->mIoHandle);
5587 //from now on mSpatializerOutput is null
5588 checkVirtualizerClientRoutes();
5589 }
Eric Laurent39095982021-08-24 18:29:27 +02005590
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005591 return NO_ERROR;
5592}
5593
Eric Laurente552edb2014-03-10 17:42:56 -07005594// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005595// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005596// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005597uint32_t AudioPolicyManager::nextAudioPortGeneration()
5598{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005599 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005600}
5601
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005602static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005603 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5604 !audioPolicyXmlConfigFile.empty()) {
5605 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5606 if (ret == NO_ERROR) {
5607 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005608 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005609 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005610 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005611 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005612}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005613
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005614AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5615 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005616 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005617 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005618 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005619 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005620 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005621 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005622 mAudioPortGeneration(1),
5623 mBeaconMuteRefCount(0),
5624 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005625 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005626 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005627 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005628 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005629{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005630}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005631
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005632AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5633 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5634{
5635 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005636}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005637
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005638void AudioPolicyManager::loadConfig() {
5639 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005640 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005641 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005642 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005643}
5644
5645status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005646 {
5647 auto engLib = EngineLibrary::load(
5648 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5649 if (!engLib) {
5650 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5651 return NO_INIT;
5652 }
5653 mEngine = engLib->createEngine();
5654 if (mEngine == nullptr) {
5655 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5656 return NO_INIT;
5657 }
François Gaffie2110e042015-03-24 08:41:51 +01005658 }
5659 mEngine->setObserver(this);
5660 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005661 if (status != NO_ERROR) {
5662 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5663 return status;
5664 }
François Gaffie2110e042015-03-24 08:41:51 +01005665
Mikhail Naganove93ae282023-02-02 15:28:26 -08005666 // If microphones address is empty, set it according to device type
5667 for (size_t i = 0; i < mInputDevicesAll.size(); i++) {
5668 if (mInputDevicesAll[i]->address().empty()) {
5669 if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
5670 mInputDevicesAll[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
5671 } else if (mInputDevicesAll[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
5672 mInputDevicesAll[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
5673 }
5674 }
5675 }
5676
jiabin76e829d2023-04-04 21:02:36 +00005677 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
5678 // at the end of this function.
5679 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005680 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5681 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5682
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005683 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005684 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005685 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005686
Eric Laurent3a4311c2014-03-17 12:00:47 -07005687 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005688 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5689 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5690 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005691 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005692 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005693 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005694
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005695 // Silence ALOGV statements
5696 property_set("log.tag." LOG_TAG, "D");
5697
Eric Laurente552edb2014-03-10 17:42:56 -07005698 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005699 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005700}
5701
Eric Laurente0720872014-03-11 09:30:41 -07005702AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005703{
Eric Laurente552edb2014-03-10 17:42:56 -07005704 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005705 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005706 }
5707 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005708 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005709 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005710 mAvailableOutputDevices.clear();
5711 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005712 mOutputs.clear();
5713 mInputs.clear();
5714 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005715 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005716 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005717}
5718
Eric Laurente0720872014-03-11 09:30:41 -07005719status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005720{
Eric Laurent87ffa392015-05-22 10:32:38 -07005721 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005722}
5723
Eric Laurente552edb2014-03-10 17:42:56 -07005724// ---
5725
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005726void AudioPolicyManager::onNewAudioModulesAvailable()
5727{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005728 DeviceVector newDevices;
5729 onNewAudioModulesAvailableInt(&newDevices);
5730 if (!newDevices.empty()) {
5731 nextAudioPortGeneration();
5732 mpClientInterface->onAudioPortListUpdate();
5733 }
5734}
5735
5736void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5737{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005738 for (const auto& hwModule : mHwModulesAll) {
5739 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5740 continue;
5741 }
5742 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5743 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5744 ALOGW("could not open HW module %s", hwModule->getName());
5745 continue;
5746 }
5747 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005748 // open all output streams needed to access attached devices.
5749 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005750 // This also validates mAvailableOutputDevices list
5751 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5752 if (!outProfile->canOpenNewIo()) {
5753 ALOGE("Invalid Output profile max open count %u for profile %s",
5754 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5755 continue;
5756 }
5757 if (!outProfile->hasSupportedDevices()) {
5758 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5759 continue;
5760 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005761 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5762 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005763 mTtsOutputAvailable = true;
5764 }
5765
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005766 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5767 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5768 sp<DeviceDescriptor> supportedDevice = 0;
5769 if (supportedDevices.contains(mDefaultOutputDevice)) {
5770 supportedDevice = mDefaultOutputDevice;
5771 } else {
5772 // choose first device present in profile's SupportedDevices also part of
5773 // mAvailableOutputDevices.
5774 if (availProfileDevices.isEmpty()) {
5775 continue;
5776 }
5777 supportedDevice = availProfileDevices.itemAt(0);
5778 }
5779 if (!mOutputDevicesAll.contains(supportedDevice)) {
5780 continue;
5781 }
5782 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5783 mpClientInterface);
5784 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005785 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5786 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005787 AUDIO_STREAM_DEFAULT,
5788 AUDIO_OUTPUT_FLAG_NONE, &output);
5789 if (status != NO_ERROR) {
5790 ALOGW("Cannot open output stream for devices %s on hw module %s",
5791 supportedDevice->toString().c_str(), hwModule->getName());
5792 continue;
5793 }
5794 for (const auto &device : availProfileDevices) {
5795 // give a valid ID to an attached device once confirmed it is reachable
5796 if (!device->isAttached()) {
5797 device->attach(hwModule);
5798 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005799 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005800 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005801 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5802 }
5803 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005804 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005805 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5806 mPrimaryOutput = outputDesc;
5807 }
Eric Laurent39095982021-08-24 18:29:27 +02005808 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005809 outputDesc->close();
5810 } else {
5811 addOutput(output, outputDesc);
5812 setOutputDevices(outputDesc,
5813 DeviceVector(supportedDevice),
5814 true,
5815 0,
5816 NULL);
5817 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005818 }
5819 // open input streams needed to access attached devices to validate
5820 // mAvailableInputDevices list
5821 for (const auto& inProfile : hwModule->getInputProfiles()) {
5822 if (!inProfile->canOpenNewIo()) {
5823 ALOGE("Invalid Input profile max open count %u for profile %s",
5824 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5825 continue;
5826 }
5827 if (!inProfile->hasSupportedDevices()) {
5828 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5829 continue;
5830 }
5831 // chose first device present in profile's SupportedDevices also part of
5832 // available input devices
5833 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5834 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5835 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005836 ALOGV("%s: Input device list is empty! for profile %s",
5837 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005838 continue;
5839 }
5840 sp<AudioInputDescriptor> inputDesc =
5841 new AudioInputDescriptor(inProfile, mpClientInterface);
5842
5843 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5844 status_t status = inputDesc->open(nullptr,
5845 availProfileDevices.itemAt(0),
5846 AUDIO_SOURCE_MIC,
5847 AUDIO_INPUT_FLAG_NONE,
5848 &input);
5849 if (status != NO_ERROR) {
5850 ALOGW("Cannot open input stream for device %s on hw module %s",
5851 availProfileDevices.toString().c_str(),
5852 hwModule->getName());
5853 continue;
5854 }
5855 for (const auto &device : availProfileDevices) {
5856 // give a valid ID to an attached device once confirmed it is reachable
5857 if (!device->isAttached()) {
5858 device->attach(hwModule);
5859 device->importAudioPortAndPickAudioProfile(inProfile, true);
5860 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005861 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005862 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5863 }
5864 }
5865 inputDesc->close();
5866 }
5867 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005868
5869 // Check if spatializer outputs can be closed until used.
5870 // mOutputs vector never contains duplicated outputs at this point.
5871 std::vector<audio_io_handle_t> outputsClosed;
5872 for (size_t i = 0; i < mOutputs.size(); i++) {
5873 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5874 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5875 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5876 outputsClosed.push_back(desc->mIoHandle);
5877 desc->close();
5878 }
5879 }
5880 for (auto output : outputsClosed) {
5881 removeOutput(output);
5882 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005883}
5884
Eric Laurent98e38192018-02-15 18:31:53 -08005885void AudioPolicyManager::addOutput(audio_io_handle_t output,
5886 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005887{
Eric Laurent1c333e22014-05-20 10:48:17 -07005888 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005889 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005890 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005891 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005892 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005893}
5894
François Gaffie53615e22015-03-19 09:24:12 +01005895void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5896{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005897 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5898 ALOGV("%s: removing primary output", __func__);
5899 mPrimaryOutput = nullptr;
5900 }
François Gaffie53615e22015-03-19 09:24:12 +01005901 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005902 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005903}
5904
Eric Laurent98e38192018-02-15 18:31:53 -08005905void AudioPolicyManager::addInput(audio_io_handle_t input,
5906 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005907{
Eric Laurent1c333e22014-05-20 10:48:17 -07005908 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005909 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005910}
Eric Laurente552edb2014-03-10 17:42:56 -07005911
François Gaffie11d30102018-11-02 16:09:09 +01005912status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005913 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005914 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005915{
François Gaffie11d30102018-11-02 16:09:09 +01005916 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005917 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005918 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005919
François Gaffie11d30102018-11-02 16:09:09 +01005920 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005921 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005922 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005923 }
Eric Laurente552edb2014-03-10 17:42:56 -07005924
Eric Laurent3b73df72014-03-11 09:06:29 -07005925 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005926 // first call getAudioPort to get the supported attributes from the HAL
5927 struct audio_port_v7 port = {};
5928 device->toAudioPort(&port);
5929 status_t status = mpClientInterface->getAudioPort(&port);
5930 if (status == NO_ERROR) {
5931 device->importAudioPort(port);
5932 }
5933
5934 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005935 for (size_t i = 0; i < mOutputs.size(); i++) {
5936 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005937 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005938 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005939 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5940 mOutputs.keyAt(i), device->toString().c_str());
5941 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005942 }
5943 }
5944 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005945 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005946 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005947 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5948 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005949 if (profile->supportsDevice(device)) {
5950 profiles.add(profile);
5951 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5952 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005953 }
5954 }
5955 }
5956
Eric Laurent7b279bb2015-12-14 10:18:23 -08005957 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005958
Eric Laurente552edb2014-03-10 17:42:56 -07005959 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005960 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005961 return BAD_VALUE;
5962 }
5963
5964 // open outputs for matching profiles if needed. Direct outputs are also opened to
5965 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5966 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005967 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005968
5969 // nothing to do if one output is already opened for this profile
5970 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005971 for (j = 0; j < outputs.size(); j++) {
5972 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005973 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005974 // matching profile: save the sample rates, format and channel masks supported
5975 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005976 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005977 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005978 }
Eric Laurente552edb2014-03-10 17:42:56 -07005979 break;
5980 }
5981 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005982 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005983 continue;
5984 }
5985
Eric Laurent3974e3b2017-12-07 17:58:43 -08005986 if (!profile->canOpenNewIo()) {
5987 ALOGW("Max Output number %u already opened for this profile %s",
5988 profile->maxOpenCount, profile->getTagName().c_str());
5989 continue;
5990 }
5991
Eric Laurent83efe1c2017-07-09 16:51:08 -07005992 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005993 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005994 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5995 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005996 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005997 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005998 profiles.removeAt(profile_index);
5999 profile_index--;
6000 } else {
6001 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006002 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006003 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006004 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6005 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006006 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006007 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006008
François Gaffie11d30102018-11-02 16:09:09 +01006009 if (device_distinguishes_on_address(deviceType)) {
6010 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6011 device->toString().c_str());
6012 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6013 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006014 }
Eric Laurente552edb2014-03-10 17:42:56 -07006015 ALOGV("checkOutputsForDevice(): adding output %d", output);
6016 }
6017 }
6018
6019 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006020 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006021 return BAD_VALUE;
6022 }
Eric Laurentd4692962014-05-05 18:13:44 -07006023 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006024 // check if one opened output is not needed any more after disconnecting one device
6025 for (size_t i = 0; i < mOutputs.size(); i++) {
6026 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006027 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006028 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006029 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006030 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006031 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006032 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006033 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6034 mOutputs.keyAt(i));
6035 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006036 }
Eric Laurente552edb2014-03-10 17:42:56 -07006037 }
6038 }
Eric Laurentd4692962014-05-05 18:13:44 -07006039 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006040 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006041 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6042 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006043 if (!profile->supportsDevice(device)) {
6044 continue;
6045 }
6046 ALOGV("checkOutputsForDevice(): "
6047 "clearing direct output profile %zu on module %s",
6048 j, hwModule->getName());
6049 profile->clearAudioProfiles();
6050 if (!profile->hasDynamicAudioProfile()) {
6051 continue;
6052 }
6053 // When a device is disconnected, if there is an IOProfile that contains dynamic
6054 // profiles and supports the disconnected device, call getAudioPort to repopulate
6055 // the capabilities of the devices that is supported by the IOProfile.
6056 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6057 if (supportedDevice == device ||
6058 !mAvailableOutputDevices.contains(supportedDevice)) {
6059 continue;
6060 }
6061 struct audio_port_v7 port;
6062 supportedDevice->toAudioPort(&port);
6063 status_t status = mpClientInterface->getAudioPort(&port);
6064 if (status == NO_ERROR) {
6065 supportedDevice->importAudioPort(port);
6066 }
Eric Laurente552edb2014-03-10 17:42:56 -07006067 }
6068 }
6069 }
6070 }
6071 return NO_ERROR;
6072}
6073
François Gaffie11d30102018-11-02 16:09:09 +01006074status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006075 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006076{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006077 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006078
François Gaffie11d30102018-11-02 16:09:09 +01006079 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006080 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006081 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006082 }
6083
Eric Laurentd4692962014-05-05 18:13:44 -07006084 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006085 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006086 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006087 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006088 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006089 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006090 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006091 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006092
François Gaffie11d30102018-11-02 16:09:09 +01006093 if (profile->supportsDevice(device)) {
6094 profiles.add(profile);
6095 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6096 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006097 }
6098 }
6099 }
6100
Eric Laurent0dd51852019-04-19 18:18:58 -07006101 if (profiles.isEmpty()) {
6102 ALOGW("%s: No input profile available for device %s",
6103 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006104 return BAD_VALUE;
6105 }
6106
6107 // open inputs for matching profiles if needed. Direct inputs are also opened to
6108 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6109 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6110
Eric Laurent1c333e22014-05-20 10:48:17 -07006111 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006112
Eric Laurentd4692962014-05-05 18:13:44 -07006113 // nothing to do if one input is already opened for this profile
6114 size_t input_index;
6115 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6116 desc = mInputs.valueAt(input_index);
6117 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006118 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006119 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006120 }
Eric Laurentd4692962014-05-05 18:13:44 -07006121 break;
6122 }
6123 }
6124 if (input_index != mInputs.size()) {
6125 continue;
6126 }
6127
Eric Laurent3974e3b2017-12-07 17:58:43 -08006128 if (!profile->canOpenNewIo()) {
6129 ALOGW("Max Input number %u already opened for this profile %s",
6130 profile->maxOpenCount, profile->getTagName().c_str());
6131 continue;
6132 }
6133
Eric Laurentfe231122017-11-17 17:48:06 -08006134 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006135 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006136 status_t status = desc->open(nullptr,
6137 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006138 AUDIO_SOURCE_MIC,
6139 AUDIO_INPUT_FLAG_NONE,
6140 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006141
Eric Laurentcf2c0212014-07-25 16:20:43 -07006142 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006143 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006144 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006145 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006146 mpClientInterface->setParameters(input, String8(param));
6147 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006148 }
François Gaffie11d30102018-11-02 16:09:09 +01006149 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006150 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006151 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006152 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006153 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006154 }
6155
Eric Laurent0dd51852019-04-19 18:18:58 -07006156 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006157 addInput(input, desc);
6158 }
6159 } // endif input != 0
6160
Eric Laurentcf2c0212014-07-25 16:20:43 -07006161 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006162 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006163 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006164 profiles.removeAt(profile_index);
6165 profile_index--;
6166 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006167 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006168 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006169 }
Eric Laurentd4692962014-05-05 18:13:44 -07006170 ALOGV("checkInputsForDevice(): adding input %d", input);
6171 }
6172 } // end scan profiles
6173
6174 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006175 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006176 return BAD_VALUE;
6177 }
6178 } else {
6179 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006180 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006181 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006182 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006183 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006184 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006185 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006186 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006187 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6188 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006189 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006190 }
6191 }
6192 }
6193 } // end disconnect
6194
6195 return NO_ERROR;
6196}
6197
6198
Eric Laurente0720872014-03-11 09:30:41 -07006199void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006200{
6201 ALOGV("closeOutput(%d)", output);
6202
François Gaffie1c878552018-11-22 16:53:21 +01006203 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6204 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006205 ALOGW("closeOutput() unknown output %d", output);
6206 return;
6207 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006208 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006209 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006210
Eric Laurente552edb2014-03-10 17:42:56 -07006211 // look for duplicated outputs connected to the output being removed.
6212 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006213 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6214 if (dupOutput->isDuplicated() &&
6215 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6216 sp<SwAudioOutputDescriptor> remainingOutput =
6217 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006218 // As all active tracks on duplicated output will be deleted,
6219 // and as they were also referenced on the other output, the reference
6220 // count for their stream type must be adjusted accordingly on
6221 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006222 const bool wasActive = remainingOutput->isActive();
6223 // Note: no-op on the closing output where all clients has already been set inactive
6224 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006225 // stop() will be a no op if the output is still active but is needed in case all
6226 // active streams refcounts where cleared above
6227 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006228 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006229 }
Eric Laurente552edb2014-03-10 17:42:56 -07006230 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6231 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6232
6233 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006234 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006235 }
6236 }
6237
Eric Laurent05b90f82014-08-27 15:32:29 -07006238 nextAudioPortGeneration();
6239
François Gaffie1c878552018-11-22 16:53:21 +01006240 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006241 if (index >= 0) {
6242 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006243 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6244 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006245 mAudioPatches.removeItemsAt(index);
6246 mpClientInterface->onAudioPatchListUpdate();
6247 }
6248
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006249 if (closingOutputWasActive) {
6250 closingOutput->stop();
6251 }
François Gaffie1c878552018-11-22 16:53:21 +01006252 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006253
François Gaffie53615e22015-03-19 09:24:12 +01006254 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006255 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006256 if (closingOutput == mSpatializerOutput) {
6257 mSpatializerOutput.clear();
6258 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006259
6260 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6261 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006262 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006263 bool directOutputOpen = false;
6264 for (size_t i = 0; i < mOutputs.size(); i++) {
6265 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6266 directOutputOpen = true;
6267 break;
6268 }
6269 }
6270 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006271 ALOGV("no direct outputs open, reset MSD patches");
6272 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6273 // how output devices for patching are resolved. Avoid by caching and reusing the
6274 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6275 // devices to patch to. This may be complicated by the fact that devices may become
6276 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006277 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006278 }
6279 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006280}
6281
6282void AudioPolicyManager::closeInput(audio_io_handle_t input)
6283{
6284 ALOGV("closeInput(%d)", input);
6285
6286 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6287 if (inputDesc == NULL) {
6288 ALOGW("closeInput() unknown input %d", input);
6289 return;
6290 }
6291
Eric Laurent6a94d692014-05-20 11:18:06 -07006292 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006293
François Gaffie11d30102018-11-02 16:09:09 +01006294 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006295 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006296 if (index >= 0) {
6297 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006298 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6299 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006300 mAudioPatches.removeItemsAt(index);
6301 mpClientInterface->onAudioPatchListUpdate();
6302 }
6303
Eric Laurentfe231122017-11-17 17:48:06 -08006304 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006305 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006306
François Gaffie11d30102018-11-02 16:09:09 +01006307 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6308 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006309 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006310 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006311 }
Eric Laurente552edb2014-03-10 17:42:56 -07006312}
6313
François Gaffie11d30102018-11-02 16:09:09 +01006314SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6315 const DeviceVector &devices,
6316 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006317{
6318 SortedVector<audio_io_handle_t> outputs;
6319
François Gaffie11d30102018-11-02 16:09:09 +01006320 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006321 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006322 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006323 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006324 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006325 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006326 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006327 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006328 outputs.add(openOutputs.keyAt(i));
6329 }
6330 }
6331 return outputs;
6332}
6333
Mikhail Naganov37977152018-07-11 15:54:44 -07006334void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6335{
6336 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6337 // output is suspended before any tracks are moved to it
6338 checkA2dpSuspend();
6339 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006340 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006341 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006342 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006343 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006344 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6345 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6346 // configuration changes will ultimately be rerouted correctly. We can still avoid
6347 // unnecessary rerouting by caching and reusing the arguments to
6348 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6349 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006350 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006351 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006352 // an event that changed routing likely occurred, inform upper layers
6353 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006354}
6355
François Gaffiec005e562018-11-06 15:04:49 +01006356bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6357 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006358{
François Gaffiec005e562018-11-06 15:04:49 +01006359 return mEngine->getProductStrategyForAttributes(lAttr) ==
6360 mEngine->getProductStrategyForAttributes(rAttr);
6361}
6362
Francois Gaffieff1eb522020-05-06 18:37:04 +02006363void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6364{
6365 for (size_t i = 0; i < mAudioSources.size(); i++) {
6366 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6367 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006368 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006369 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006370 connectAudioSource(sourceDesc);
6371 }
6372 }
6373}
6374
6375void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6376{
6377 for (size_t i = 0; i < mAudioSources.size(); i++) {
6378 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6379 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6380 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6381 disconnectAudioSource(sourceDesc);
6382 }
6383 }
6384}
6385
François Gaffiec005e562018-11-06 15:04:49 +01006386void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6387{
6388 auto psId = mEngine->getProductStrategyForAttributes(attr);
6389
6390 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6391 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006392
François Gaffie11d30102018-11-02 16:09:09 +01006393 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6394 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006395
Eric Laurentc209fe42020-06-05 18:11:23 -07006396 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006397 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006398 // take into account dynamic audio policies related changes: if a client is now associated
6399 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006400 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006401 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6402 if (desc->isDuplicated()) {
6403 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006404 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006405 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6406 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6407 continue;
6408 }
6409 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006410 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6411 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006412 if (status != OK) {
6413 continue;
6414 }
yucliuf4de36d2020-09-14 14:57:56 -07006415 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006416 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006417 maxLatency = desc->latency();
6418 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006419 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006420 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006421 }
6422 }
6423
Eric Laurent56ed8842022-11-15 16:04:41 +01006424 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006425 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6426 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006427 for (audio_io_handle_t srcOut : srcOutputs) {
6428 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006429 if (desc == nullptr) continue;
6430
6431 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006432 maxLatency = desc->latency();
6433 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006434
Eric Laurent56ed8842022-11-15 16:04:41 +01006435 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006436 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006437 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006438 // a client on a non direct outputs has necessarily a linear PCM format
6439 // so we can call selectOutput() safely
6440 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6441 client->flags(),
6442 client->config().format,
6443 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006444 client->config().sample_rate,
6445 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006446 if (newOutput != srcOut) {
6447 invalidate = true;
6448 break;
6449 }
6450 } else {
6451 sp<IOProfile> profile = getProfileForOutput(newDevices,
6452 client->config().sample_rate,
6453 client->config().format,
6454 client->config().channel_mask,
6455 client->flags(),
6456 true /* directOnly */);
6457 if (profile != desc->mProfile) {
6458 invalidate = true;
6459 break;
6460 }
6461 }
6462 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006463 // mute strategy while moving tracks from one output to another
6464 if (invalidate) {
6465 invalidatedOutputs.push_back(desc);
6466 if (desc->isStrategyActive(psId)) {
6467 setStrategyMute(psId, true, desc);
6468 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6469 newDevices.types());
6470 }
Eric Laurente552edb2014-03-10 17:42:56 -07006471 }
François Gaffiec005e562018-11-06 15:04:49 +01006472 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006473 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006474 connectAudioSource(source);
6475 }
Eric Laurente552edb2014-03-10 17:42:56 -07006476 }
6477
Eric Laurent56ed8842022-11-15 16:04:41 +01006478 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6479 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6480 std::to_string(srcOutputs[0]).c_str(),
6481 std::to_string(dstOutputs[0]).c_str());
6482
François Gaffiec005e562018-11-06 15:04:49 +01006483 // Move effects associated to this stream from previous output to new output
6484 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006485 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006486 }
François Gaffiec005e562018-11-06 15:04:49 +01006487 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006488 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006489 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6490 mpClientInterface->invalidateStream(stream);
6491 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006492 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006493 desc->setTracksInvalidatedStatusByStrategy(psId);
6494 }
Eric Laurente552edb2014-03-10 17:42:56 -07006495 }
6496 }
6497}
6498
Eric Laurente0720872014-03-11 09:30:41 -07006499void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006500{
François Gaffiec005e562018-11-06 15:04:49 +01006501 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6502 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6503 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006504 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006505 }
Eric Laurente552edb2014-03-10 17:42:56 -07006506}
6507
Kevin Rocard153f92d2018-12-18 18:33:28 -08006508void AudioPolicyManager::checkSecondaryOutputs() {
6509 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006510 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006511 for (size_t i = 0; i < mOutputs.size(); i++) {
6512 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6513 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006514 sp<AudioPolicyMix> primaryMix;
6515 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006516 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6517 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006518 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6519 for (auto &secondaryMix : secondaryMixes) {
6520 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6521 if (outputDesc != nullptr &&
6522 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6523 secondaryDescs.push_back(outputDesc);
6524 }
6525 }
6526
jiabin10a03f12021-05-07 23:46:28 +00006527 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006528 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006529 } else if (!std::equal(
6530 client->getSecondaryOutputs().begin(),
6531 client->getSecondaryOutputs().end(),
6532 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006533 if (!audio_is_linear_pcm(client->config().format)) {
6534 // If the format is not PCM, the tracks should be invalidated to get correct
6535 // behavior when the secondary output is changed.
6536 streamsToInvalidate.insert(client->stream());
6537 } else {
6538 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6539 std::vector<audio_io_handle_t> secondaryOutputIds;
6540 for (const auto &secondaryDesc: secondaryDescs) {
6541 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6542 weakSecondaryDescs.push_back(secondaryDesc);
6543 }
6544 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6545 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006546 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006547 }
6548 }
6549 }
jiabin10a03f12021-05-07 23:46:28 +00006550 if (!trackSecondaryOutputs.empty()) {
6551 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6552 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006553 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006554 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006555 mpClientInterface->invalidateStream(stream);
6556 }
6557}
6558
Eric Laurent2517af32020-11-25 15:31:27 +01006559bool AudioPolicyManager::isScoRequestedForComm() const {
6560 AudioDeviceTypeAddrVector devices;
6561 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6562 for (const auto &device : devices) {
6563 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6564 return true;
6565 }
6566 }
6567 return false;
6568}
6569
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006570bool AudioPolicyManager::isHearingAidUsedForComm() const {
6571 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6572 true /*fromCache*/);
6573 for (const auto &device : devices) {
6574 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6575 return true;
6576 }
6577 }
6578 return false;
6579}
6580
6581
Eric Laurente0720872014-03-11 09:30:41 -07006582void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006583{
François Gaffie53615e22015-03-19 09:24:12 +01006584 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006585 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006586 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006587 return;
6588 }
6589
Eric Laurent3a4311c2014-03-17 12:00:47 -07006590 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006591 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6592 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006593 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006594
6595 // if suspended, restore A2DP output if:
6596 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006597 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006598 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006599 //
Eric Laurentf732e072016-08-03 19:30:28 -07006600 // if not suspended, suspend A2DP output if:
6601 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006602 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006603 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006604 //
6605 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006606 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006607 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006608 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006609 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006610
6611 mpClientInterface->restoreOutput(a2dpOutput);
6612 mA2dpSuspended = false;
6613 }
6614 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006615 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006616 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006617 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006618 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006619
6620 mpClientInterface->suspendOutput(a2dpOutput);
6621 mA2dpSuspended = true;
6622 }
6623 }
6624}
6625
François Gaffie11d30102018-11-02 16:09:09 +01006626DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6627 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006628{
François Gaffie11d30102018-11-02 16:09:09 +01006629 DeviceVector devices;
6630
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006631 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006632 if (index >= 0) {
6633 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006634 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006635 ALOGV("%s device %s forced by patch %d", __func__,
6636 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6637 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006638 }
6639 }
6640
Dean Wheatley514b4312020-06-17 21:45:00 +10006641 // Do not retrieve engine device for outputs through MSD
6642 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6643 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6644 return outputDesc->devices();
6645 }
6646
Eric Laurent97ac8712018-07-27 18:59:02 -07006647 // Honor explicit routing requests only if no client using default routing is active on this
6648 // input: a specific app can not force routing for other apps by setting a preferred device.
6649 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006650 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006651 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006652 if (device != nullptr) {
6653 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006654 }
6655
François Gaffiea807ef92018-11-05 10:44:33 +01006656 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6657 // of setForceUse / Default Bus device here
6658 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6659 if (device != nullptr) {
6660 return DeviceVector(device);
6661 }
6662
François Gaffiec005e562018-11-06 15:04:49 +01006663 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6664 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6665 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306666 auto hasStreamActive = [&](auto stream) {
6667 return hasStream(streams, stream) && isStreamActive(stream, 0);
6668 };
Eric Laurent484e9272018-06-07 17:29:23 -07006669
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306670 auto doGetOutputDevicesForVoice = [&]() {
6671 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006672 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306673 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006674 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6675 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306676 };
6677
6678 // With low-latency playing on speaker, music on WFD, when the first low-latency
6679 // output is stopped, getNewOutputDevices checks for a product strategy
6680 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006681 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306682 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6683 // stream is associated to the output descriptor.
6684 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6685 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6686 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6687 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006688 // Retrieval of devices for voice DL is done on primary output profile, cannot
6689 // check the route (would force modifying configuration file for this profile)
6690 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6691 break;
6692 }
Eric Laurente552edb2014-03-10 17:42:56 -07006693 }
François Gaffiec005e562018-11-06 15:04:49 +01006694 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006695 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006696}
6697
François Gaffie11d30102018-11-02 16:09:09 +01006698sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6699 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006700{
François Gaffie11d30102018-11-02 16:09:09 +01006701 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006702
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006703 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006704 if (index >= 0) {
6705 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006706 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006707 ALOGV("getNewInputDevice() device %s forced by patch %d",
6708 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6709 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006710 }
6711 }
6712
Eric Laurent97ac8712018-07-27 18:59:02 -07006713 // Honor explicit routing requests only if no client using default routing is active on this
6714 // input: a specific app can not force routing for other apps by setting a preferred device.
6715 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006716 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6717 if (device != nullptr) {
6718 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006719 }
6720
Eric Laurentdc95a252018-04-12 12:46:56 -07006721 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006722 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006723 audio_attributes_t attributes;
6724 uid_t uid;
6725 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6726 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006727 attributes = topClient->attributes();
6728 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006729 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006730 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6731 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006732 }
6733
Francois Gaffie716e1432019-01-14 16:58:59 +01006734 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6735 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006736 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006737 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006738 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006739 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006740
Eric Laurente552edb2014-03-10 17:42:56 -07006741 return device;
6742}
6743
Eric Laurent794fde22016-03-11 09:50:45 -08006744bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6745 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006746 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006747}
6748
Dorin Drimusf2196d82022-01-03 12:11:18 +01006749// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006750status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006751 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006752 if (devices == nullptr) {
6753 return BAD_VALUE;
6754 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006755
6756 // Devices are determined in the following precedence:
6757 //
6758 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6759 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6760 //
6761 // If no such dynamic policy then
6762 // 2) Devices containing an active client using setPreferredDevice
6763 // with same strategy as the attributes.
6764 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6765 //
6766 // If no corresponding active client with setPreferredDevice then
6767 // 3) Devices associated with the strategy determined by the attributes
6768 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6769 //
6770 // See related getOutputForAttrInt().
6771
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006772 // check dynamic policies but only for primary descriptors (secondary not used for audible
6773 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006774 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006775 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6776 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006777 if (status != OK) {
6778 return status;
6779 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006780
6781 DeviceVector curDevices;
6782 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6783 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6784 // as they are unaffected by device/stream volume
6785 // (per SwAudioOutputDescriptor::isFixedVolume()).
6786 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6787 ) {
6788 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6789 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6790 curDevices.add(deviceDesc);
6791 } else {
6792 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6793 // which selects setPreferredDevice if active. This means forVolume call
6794 // will take an active setPreferredDevice, if such exists.
6795
6796 curDevices = mEngine->getOutputDevicesForAttributes(
6797 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006798 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006799
6800 if (forVolume) {
6801 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6802 // for single volume control in AudioService (such relationship should exist if
6803 // SPEAKER_SAFE is present).
6804 //
6805 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6806 DeviceVector speakerSafeDevices =
6807 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6808 if (!speakerSafeDevices.isEmpty()) {
6809 curDevices.merge(
6810 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6811 curDevices.remove(speakerSafeDevices);
6812 }
6813 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006814 for (const auto& device : curDevices) {
6815 devices->push_back(device->getDeviceTypeAddr());
6816 }
6817 return NO_ERROR;
6818}
6819
Eric Laurente0720872014-03-11 09:30:41 -07006820void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006821 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006822 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006823 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006824 updateDevicesAndOutputs();
6825 break;
6826 default:
6827 break;
6828 }
6829}
6830
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006831uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006832
6833 // skip beacon mute management if a dedicated TTS output is available
6834 if (mTtsOutputAvailable) {
6835 return 0;
6836 }
6837
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006838 switch(event) {
6839 case STARTING_OUTPUT:
6840 mBeaconMuteRefCount++;
6841 break;
6842 case STOPPING_OUTPUT:
6843 if (mBeaconMuteRefCount > 0) {
6844 mBeaconMuteRefCount--;
6845 }
6846 break;
6847 case STARTING_BEACON:
6848 mBeaconPlayingRefCount++;
6849 break;
6850 case STOPPING_BEACON:
6851 if (mBeaconPlayingRefCount > 0) {
6852 mBeaconPlayingRefCount--;
6853 }
6854 break;
6855 }
6856
6857 if (mBeaconMuteRefCount > 0) {
6858 // any playback causes beacon to be muted
6859 return setBeaconMute(true);
6860 } else {
6861 // no other playback: unmute when beacon starts playing, mute when it stops
6862 return setBeaconMute(mBeaconPlayingRefCount == 0);
6863 }
6864}
6865
6866uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6867 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6868 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6869 // keep track of muted state to avoid repeating mute/unmute operations
6870 if (mBeaconMuted != mute) {
6871 // mute/unmute AUDIO_STREAM_TTS on all outputs
6872 ALOGV("\t muting %d", mute);
6873 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006874 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6875 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6876 ALOGV("\t no tts volume source available");
6877 return 0;
6878 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006879 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006880 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006881 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006882 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006883 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006884 maxLatency = latency;
6885 }
6886 }
6887 mBeaconMuted = mute;
6888 return maxLatency;
6889 }
6890 return 0;
6891}
6892
Eric Laurente0720872014-03-11 09:30:41 -07006893void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006894{
François Gaffiec005e562018-11-06 15:04:49 +01006895 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006896 mPreviousOutputs = mOutputs;
6897}
6898
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006899uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006900 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006901 uint32_t delayMs)
6902{
6903 // mute/unmute strategies using an incompatible device combination
6904 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6905 // if unmuting, unmute only after the specified delay
6906 if (outputDesc->isDuplicated()) {
6907 return 0;
6908 }
6909
6910 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006911 DeviceVector devices = outputDesc->devices();
6912 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006913
François Gaffiec005e562018-11-06 15:04:49 +01006914 auto productStrategies = mEngine->getOrderedProductStrategies();
6915 for (const auto &productStrategy : productStrategies) {
6916 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6917 DeviceVector curDevices =
6918 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6919 curDevices = curDevices.filter(outputDesc->supportedDevices());
6920 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006921 bool doMute = false;
6922
François Gaffiec005e562018-11-06 15:04:49 +01006923 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006924 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006925 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6926 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006927 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006928 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006929 }
Eric Laurent99401132014-05-07 19:48:15 -07006930 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006931 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006932 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006933 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006934 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006935 continue;
6936 }
François Gaffiec005e562018-11-06 15:04:49 +01006937 ALOGVV("%s() %s (curDevice %s)", __func__,
6938 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6939 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6940 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006941 if (mute) {
6942 // FIXME: should not need to double latency if volume could be applied
6943 // immediately by the audioflinger mixer. We must account for the delay
6944 // between now and the next time the audioflinger thread for this output
6945 // will process a buffer (which corresponds to one buffer size,
6946 // usually 1/2 or 1/4 of the latency).
6947 if (muteWaitMs < desc->latency() * 2) {
6948 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006949 }
6950 }
6951 }
6952 }
6953 }
6954 }
6955
Eric Laurent99401132014-05-07 19:48:15 -07006956 // temporary mute output if device selection changes to avoid volume bursts due to
6957 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006958 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006959 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006960
Eric Laurentdc462862016-07-19 12:29:53 -07006961 if (muteWaitMs < tempMuteWaitMs) {
6962 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006963 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006964
6965 // If recommended duration is defined, replace temporary mute duration to avoid
6966 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6967 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6968 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6969 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6970 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6971
François Gaffieaaac0fd2018-11-22 17:56:39 +01006972 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6973 // make sure that we do not start the temporary mute period too early in case of
6974 // delayed device change
6975 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6976 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006977 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006978 }
6979 }
6980
Eric Laurente552edb2014-03-10 17:42:56 -07006981 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6982 if (muteWaitMs > delayMs) {
6983 muteWaitMs -= delayMs;
6984 usleep(muteWaitMs * 1000);
6985 return muteWaitMs;
6986 }
6987 return 0;
6988}
6989
François Gaffie11d30102018-11-02 16:09:09 +01006990uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6991 const DeviceVector &devices,
6992 bool force,
6993 int delayMs,
6994 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006995 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006996{
François Gaffie11d30102018-11-02 16:09:09 +01006997 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006998 uint32_t muteWaitMs;
6999
7000 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007001 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7002 nullptr /* patchHandle */, requiresMuteCheck);
7003 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7004 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007005 return muteWaitMs;
7006 }
Eric Laurente552edb2014-03-10 17:42:56 -07007007
7008 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007009 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007010 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007011 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007012
François Gaffie11d30102018-11-02 16:09:09 +01007013 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7014
7015 if (!filteredDevices.isEmpty()) {
7016 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007017 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007018
7019 // if the outputs are not materially active, there is no need to mute.
7020 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007021 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007022 } else {
7023 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7024 muteWaitMs = 0;
7025 }
Eric Laurente552edb2014-03-10 17:42:56 -07007026
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007027 bool outputRouted = outputDesc->isRouted();
7028
Eric Laurent79ea9582020-06-11 18:49:24 -07007029 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7030 // output profile or if new device is not supported AND previous device(s) is(are) still
7031 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007032 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007033 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7034 // restore previous device after evaluating strategy mute state
7035 outputDesc->setDevices(prevDevices);
7036 return muteWaitMs;
7037 }
7038
Eric Laurente552edb2014-03-10 17:42:56 -07007039 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007040 // the requested device is AUDIO_DEVICE_NONE
7041 // OR the requested device is the same as current device
7042 // AND force is not specified
7043 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007044 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007045 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007046 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7047 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007048 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7049 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7050 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7051 }
Eric Laurente552edb2014-03-10 17:42:56 -07007052 return muteWaitMs;
7053 }
7054
François Gaffie11d30102018-11-02 16:09:09 +01007055 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007056
Eric Laurente552edb2014-03-10 17:42:56 -07007057 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007058 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007059 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007060 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007061 PatchBuilder patchBuilder;
7062 patchBuilder.addSource(outputDesc);
7063 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7064 for (const auto &filteredDevice : filteredDevices) {
7065 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007066 }
7067
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007068 // Add half reported latency to delayMs when muteWaitMs is null in order
7069 // to avoid disordered sequence of muting volume and changing devices.
7070 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7071 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007072 }
Eric Laurente552edb2014-03-10 17:42:56 -07007073
7074 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007075 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007076
7077 return muteWaitMs;
7078}
7079
Eric Laurentc75307b2015-03-17 15:29:32 -07007080status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007081 int delayMs,
7082 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007083{
Eric Laurent6a94d692014-05-20 11:18:06 -07007084 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007085 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7086 return INVALID_OPERATION;
7087 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007088 if (patchHandle) {
7089 index = mAudioPatches.indexOfKey(*patchHandle);
7090 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007091 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007092 }
7093 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007094 return INVALID_OPERATION;
7095 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007096 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007097 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007098 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007099 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007100 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007101 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007102 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007103 return status;
7104}
7105
7106status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007107 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007108 bool force,
7109 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007110{
7111 status_t status = NO_ERROR;
7112
Eric Laurent1f2f2232014-06-02 12:01:23 -07007113 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007114 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7115 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007116
François Gaffie11d30102018-11-02 16:09:09 +01007117 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007118 PatchBuilder patchBuilder;
7119 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007120 // AUDIO_SOURCE_HOTWORD is for internal use only:
7121 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007122 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7123 auto result = usecase;
7124 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7125 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7126 }
7127 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007128 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007129 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007130 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007131 }
7132 }
7133 return status;
7134}
7135
Eric Laurent6a94d692014-05-20 11:18:06 -07007136status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7137 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007138{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007139 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007140 ssize_t index;
7141 if (patchHandle) {
7142 index = mAudioPatches.indexOfKey(*patchHandle);
7143 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007144 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007145 }
7146 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007147 return INVALID_OPERATION;
7148 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007149 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007150 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007151 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007152 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007153 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007154 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007155 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007156 return status;
7157}
7158
François Gaffie11d30102018-11-02 16:09:09 +01007159sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007160 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007161 audio_format_t& format,
7162 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007163 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007164{
7165 // Choose an input profile based on the requested capture parameters: select the first available
7166 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007167 //
7168 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7169 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007170
Glenn Kasten730b9262018-03-29 15:01:26 -07007171 sp<IOProfile> firstInexact;
7172 uint32_t updatedSamplingRate = 0;
7173 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7174 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007175 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007176 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007177 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007178 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007179 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007180 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007181 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007182 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007183 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007184 &channelMask /*updatedChannelMask*/,
7185 // FIXME ugly cast
7186 (audio_output_flags_t) flags,
7187 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007188 return profile;
7189 }
François Gaffie11d30102018-11-02 16:09:09 +01007190 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007191 samplingRate,
7192 &updatedSamplingRate,
7193 format,
7194 &updatedFormat,
7195 channelMask,
7196 &updatedChannelMask,
7197 // FIXME ugly cast
7198 (audio_output_flags_t) flags,
7199 false /*exactMatchRequiredForInputFlags*/)) {
7200 firstInexact = profile;
7201 }
7202
Eric Laurente552edb2014-03-10 17:42:56 -07007203 }
7204 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007205 if (firstInexact != nullptr) {
7206 samplingRate = updatedSamplingRate;
7207 format = updatedFormat;
7208 channelMask = updatedChannelMask;
7209 return firstInexact;
7210 }
Eric Laurente552edb2014-03-10 17:42:56 -07007211 return NULL;
7212}
7213
François Gaffieaaac0fd2018-11-22 17:56:39 +01007214float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7215 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007216 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007217 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007218{
jiabin9a3361e2019-10-01 09:38:30 -07007219 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007220
7221 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7222 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7223 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7224 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007225 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7226 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7227 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7228 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7229 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007230
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007231 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007232 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7233 mOutputs.isActive(ringVolumeSrc, 0)) {
7234 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007235 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007236 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007237 }
7238
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007239 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007240 if ((volumeSource != callVolumeSrc && (isInCall() ||
7241 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007242 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007243 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7244 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007245 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7246 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7247 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007248 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007249 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007250 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007251 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007252 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007253 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007254 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7255 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7256 // programmatically muted.
7257 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7258 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7259 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007260 bool exemptFromCapping =
7261 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7262 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007263 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7264 volumeSource, volumeDb);
7265 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007266 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7267 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7268 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007269 }
7270 }
Eric Laurente552edb2014-03-10 17:42:56 -07007271 // if a headset is connected, apply the following rules to ring tones and notifications
7272 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007273 // - always attenuate notifications volume by 6dB
7274 // - attenuate ring tones volume by 6dB unless music is not playing and
7275 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007276 // - if music is playing, always limit the volume to current music volume,
7277 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007278 if (!Intersection(deviceTypes,
7279 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7280 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007281 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7282 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007283 ((volumeSource == alarmVolumeSrc ||
7284 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007285 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7286 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7287 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007288 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7289 curves.canBeMuted()) {
7290
Eric Laurente552edb2014-03-10 17:42:56 -07007291 // when the phone is ringing we must consider that music could have been paused just before
7292 // by the music application and behave as if music was active if the last music track was
7293 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007294 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007295 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007296 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007297 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007298 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7299 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007300 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007301 float musicVolDb = computeVolume(musicCurves,
7302 musicVolumeSrc,
7303 musicCurves.getVolumeIndex(musicDevice),
7304 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007305 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7306 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7307 if (volumeDb > minVolDb) {
7308 volumeDb = minVolDb;
7309 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007310 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007311 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7312 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7313 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007314 // on A2DP, also ensure notification volume is not too low compared to media when
7315 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007316 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007317 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007318 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7319 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007320 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7321 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007322 }
7323 }
jiabin9a3361e2019-10-01 09:38:30 -07007324 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007325 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007326 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007327 }
7328 }
7329
François Gaffie43c73442018-11-08 08:21:55 +01007330 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007331}
7332
Eric Laurent3839bc02018-07-10 18:33:34 -07007333int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007334 VolumeSource fromVolumeSource,
7335 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007336{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007337 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007338 return srcIndex;
7339 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007340 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7341 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007342 float minSrc = (float)srcCurves.getVolumeIndexMin();
7343 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7344 float minDst = (float)dstCurves.getVolumeIndexMin();
7345 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007346
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007347 // preserve mute request or correct range
7348 if (srcIndex < minSrc) {
7349 if (srcIndex == 0) {
7350 return 0;
7351 }
7352 srcIndex = minSrc;
7353 } else if (srcIndex > maxSrc) {
7354 srcIndex = maxSrc;
7355 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007356 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7357}
7358
François Gaffieaaac0fd2018-11-22 17:56:39 +01007359status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7360 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007361 int index,
7362 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007363 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007364 int delayMs,
7365 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007366{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007367 // do not change actual attributes volume if the attributes is muted
7368 if (outputDesc->isMuted(volumeSource)) {
7369 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7370 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007371 return NO_ERROR;
7372 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007373 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7374 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7375 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7376 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007377
Eric Laurent2517af32020-11-25 15:31:27 +01007378 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007379 bool isHAUsed = isHearingAidUsedForComm();
7380
Eric Laurente552edb2014-03-10 17:42:56 -07007381 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007382 // if sco and call follow same curves, bypass forceUseForComm
7383 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007384 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007385 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7386 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007387 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007388 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007389 // Do not return an error here as AudioService will always set both voice call
7390 // and bluetooth SCO volumes due to stream aliasing.
7391 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007392 }
jiabin9a3361e2019-10-01 09:38:30 -07007393 if (deviceTypes.empty()) {
7394 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007395 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007396
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007397 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7398 ALOGE("invalid volume index range");
7399 return BAD_VALUE;
7400 }
7401
jiabin9a3361e2019-10-01 09:38:30 -07007402 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7403 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007404 // Force VoIP volume to max for bluetooth SCO device except if muted
7405 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007406 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007407 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007408 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007409 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007410 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007411 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007412
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007413 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007414 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007415 // 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 +01007416 if (isVoiceVolSrc) {
7417 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007418 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007419 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007420 }
Eric Laurent18fba842016-03-31 14:41:26 -07007421 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007422 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7423 mLastVoiceVolume = voiceVolume;
7424 }
7425 }
Eric Laurente552edb2014-03-10 17:42:56 -07007426 return NO_ERROR;
7427}
7428
Eric Laurentc75307b2015-03-17 15:29:32 -07007429void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007430 const DeviceTypeSet& deviceTypes,
7431 int delayMs,
7432 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007433{
jiabincd510522020-01-22 09:40:55 -08007434 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007435 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7436 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7437 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007438 curves.getVolumeIndex(deviceTypes),
7439 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007440 }
7441}
7442
François Gaffiec005e562018-11-06 15:04:49 +01007443void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7444 bool on,
7445 const sp<AudioOutputDescriptor>& outputDesc,
7446 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007447 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007448{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007449 std::vector<VolumeSource> sourcesToMute;
7450 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7451 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7452 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007453 VolumeSource source = toVolumeSource(attributes, false);
7454 if ((source != VOLUME_SOURCE_NONE) &&
7455 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7456 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007457 sourcesToMute.push_back(source);
7458 }
Eric Laurente552edb2014-03-10 17:42:56 -07007459 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007460 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007461 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007462 }
7463
Eric Laurente552edb2014-03-10 17:42:56 -07007464}
7465
François Gaffieaaac0fd2018-11-22 17:56:39 +01007466void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7467 bool on,
7468 const sp<AudioOutputDescriptor>& outputDesc,
7469 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007470 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007471{
jiabin9a3361e2019-10-01 09:38:30 -07007472 if (deviceTypes.empty()) {
7473 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007474 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007475 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007476 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007477 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007478 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007479 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007480 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7481 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007482 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007483 }
7484 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007485 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7486 // ignored
7487 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007488 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007489 if (!outputDesc->isMuted(volumeSource)) {
7490 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007491 return;
7492 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007493 if (outputDesc->decMuteCount(volumeSource) == 0) {
7494 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007495 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007496 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007497 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007498 delayMs);
7499 }
7500 }
7501}
7502
François Gaffie53615e22015-03-19 09:24:12 +01007503bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7504{
François Gaffiec005e562018-11-06 15:04:49 +01007505 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007506 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7507 return true;
7508 }
7509
7510 // has known usage?
7511 switch (paa->usage) {
7512 case AUDIO_USAGE_UNKNOWN:
7513 case AUDIO_USAGE_MEDIA:
7514 case AUDIO_USAGE_VOICE_COMMUNICATION:
7515 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7516 case AUDIO_USAGE_ALARM:
7517 case AUDIO_USAGE_NOTIFICATION:
7518 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7519 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7520 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7521 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7522 case AUDIO_USAGE_NOTIFICATION_EVENT:
7523 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7524 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7525 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7526 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007527 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007528 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007529 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007530 case AUDIO_USAGE_EMERGENCY:
7531 case AUDIO_USAGE_SAFETY:
7532 case AUDIO_USAGE_VEHICLE_STATUS:
7533 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007534 break;
7535 default:
7536 return false;
7537 }
7538 return true;
7539}
7540
François Gaffie2110e042015-03-24 08:41:51 +01007541audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7542{
7543 return mEngine->getForceUse(usage);
7544}
7545
Eric Laurent96d1dda2022-03-14 17:14:19 +01007546bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007547 return isStateInCall(mEngine->getPhoneState());
7548}
7549
Eric Laurent96d1dda2022-03-14 17:14:19 +01007550bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007551 return is_state_in_call(state);
7552}
7553
Eric Laurentf9cccec2022-11-16 19:12:00 +01007554bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007555 audio_mode_t mode = mEngine->getPhoneState();
7556 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007557 || (mode == AUDIO_MODE_CALL_SCREEN)
7558 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007559}
7560
Eric Laurentf9cccec2022-11-16 19:12:00 +01007561bool AudioPolicyManager::isInCallOrScreening() const {
7562 audio_mode_t mode = mEngine->getPhoneState();
7563 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7564}
7565
Eric Laurentd60560a2015-04-10 11:31:20 -07007566void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7567{
7568 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007569 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007570 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007571 sourceDesc->sinkDevice()->equals(deviceDesc))
7572 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007573 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007574 }
7575 }
7576
7577 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7578 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7579 bool release = false;
7580 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7581 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7582 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7583 source->ext.device.type == deviceDesc->type()) {
7584 release = true;
7585 }
7586 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007587 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007588 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7589 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7590 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007591 sink->ext.device.type == deviceDesc->type() &&
7592 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7593 || strncmp(sink->ext.device.address, address,
7594 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007595 release = true;
7596 }
7597 }
7598 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007599 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7600 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007601 }
7602 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007603
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007604 mInputs.clearSessionRoutesForDevice(deviceDesc);
7605
Francois Gaffie716e1432019-01-14 16:58:59 +01007606 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007607}
7608
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007609void AudioPolicyManager::modifySurroundFormats(
7610 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007611 std::unordered_set<audio_format_t> enforcedSurround(
7612 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007613 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7614 for (const auto& pair : mConfig.getSurroundFormats()) {
7615 allSurround.insert(pair.first);
7616 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7617 }
Phil Burk09bc4612016-02-24 15:58:15 -08007618
7619 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7620 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007621 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007622 // This is the resulting set of formats depending on the surround mode:
7623 // 'all surround' = allSurround
7624 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7625 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7626 // 'manual surround' = mManualSurroundFormats
7627 // AUTO: formats v 'enforced surround'
7628 // ALWAYS: formats v 'all surround' v 'enforced surround'
7629 // NEVER: formats ^ 'non-surround'
7630 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007631
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007632 std::unordered_set<audio_format_t> formatSet;
7633 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7634 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007635 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007636 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007637 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007638 formatSet.insert(*formatIter);
7639 }
7640 }
7641 } else {
7642 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7643 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007644 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007645
jiabin81772902018-04-02 17:52:27 -07007646 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007647 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007648 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7649 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7650 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007651 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007652 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7653 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7654 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007655 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007656 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007657 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007658 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007659 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007660 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007661}
7662
jiabin06e4bab2019-07-29 10:13:34 -07007663void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7664 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007665 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7666 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7667
7668 // If NEVER, then remove support for channelMasks > stereo.
7669 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007670 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7671 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007672 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007673 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007674 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007675 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007676 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007677 }
7678 }
jiabin81772902018-04-02 17:52:27 -07007679 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7680 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7681 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007682 bool supports5dot1 = false;
7683 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007684 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007685 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7686 supports5dot1 = true;
7687 break;
7688 }
7689 }
7690 // If not then add 5.1 support.
7691 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007692 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007693 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007694 }
Phil Burk09bc4612016-02-24 15:58:15 -08007695 }
7696}
7697
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007698void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007699 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007700 AudioProfileVector &profiles)
7701{
7702 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007703 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007704
François Gaffie112b0af2015-11-19 16:13:25 +01007705 // Format MUST be checked first to update the list of AudioProfile
7706 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007707 reply = mpClientInterface->getParameters(
7708 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007709 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007710 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00007711 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08007712 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00007713 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
7714 formats = formatsFromString(reply.string());
7715 } else if (devDesc->hasValidAudioProfile()) {
7716 ALOGD("%s: using the device profiles", __func__);
7717 formats = devDesc->getAudioProfiles().getSupportedFormats();
7718 } else {
7719 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01007720 return;
7721 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01007722 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007723 if (device == AUDIO_DEVICE_OUT_HDMI
7724 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007725 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007726 }
jiabin3e277cc2019-09-10 14:27:34 -07007727 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007728 }
François Gaffie112b0af2015-11-19 16:13:25 +01007729
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007730 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00007731 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07007732 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007733 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007734 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007735
7736 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007737 reply = mpClientInterface->getParameters(
7738 ioHandle,
7739 requestedParameters.toString() + ";" +
7740 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007741 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007742 AudioParameter repliedParameters(reply);
7743 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007744 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007745 samplingRates = samplingRatesFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007746 } else {
7747 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01007748 }
7749 }
7750 if (profiles.hasDynamicChannelsFor(format)) {
7751 reply = mpClientInterface->getParameters(ioHandle,
7752 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007753 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007754 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007755 AudioParameter repliedParameters(reply);
7756 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007757 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007758 channelMasks = channelMasksFromString(reply.string());
jiabinf26596b2023-04-12 18:56:39 +00007759 } else {
7760 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
7761 }
7762 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
7763 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
7764 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01007765 }
7766 }
jiabin3e277cc2019-09-10 14:27:34 -07007767 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00007768 profiles, new AudioProfile(
7769 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007770 }
7771}
Eric Laurentd60560a2015-04-10 11:31:20 -07007772
Mikhail Naganovdc769682018-05-04 15:34:08 -07007773status_t AudioPolicyManager::installPatch(const char *caller,
7774 audio_patch_handle_t *patchHandle,
7775 AudioIODescriptorInterface *ioDescriptor,
7776 const struct audio_patch *patch,
7777 int delayMs)
7778{
7779 ssize_t index = mAudioPatches.indexOfKey(
7780 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7781 *patchHandle : ioDescriptor->getPatchHandle());
7782 sp<AudioPatch> patchDesc;
7783 status_t status = installPatch(
7784 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7785 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007786 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007787 }
7788 return status;
7789}
7790
7791status_t AudioPolicyManager::installPatch(const char *caller,
7792 ssize_t index,
7793 audio_patch_handle_t *patchHandle,
7794 const struct audio_patch *patch,
7795 int delayMs,
7796 uid_t uid,
7797 sp<AudioPatch> *patchDescPtr)
7798{
7799 sp<AudioPatch> patchDesc;
7800 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7801 if (index >= 0) {
7802 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007803 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007804 }
7805
7806 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7807 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7808 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7809 if (status == NO_ERROR) {
7810 if (index < 0) {
7811 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007812 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007813 } else {
7814 patchDesc->mPatch = *patch;
7815 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007816 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007817 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007818 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007819 }
7820 nextAudioPortGeneration();
7821 mpClientInterface->onAudioPatchListUpdate();
7822 }
7823 if (patchDescPtr) *patchDescPtr = patchDesc;
7824 return status;
7825}
7826
jiabinbce0c1d2020-10-05 11:20:18 -07007827bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7828{
7829 const TrackClientVector activeClients = output->getActiveClients();
7830 if (activeClients.empty()) {
7831 return true;
7832 }
7833 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7834 if (index < 0) {
7835 ALOGE("%s, no audio patch found while there are active clients on output %d",
7836 __func__, output->getId());
7837 return false;
7838 }
7839 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7840 DeviceVector routedDevices;
7841 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7842 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7843 patchDesc->mPatch.sinks[i].id);
7844 if (device == nullptr) {
7845 ALOGE("%s, no audio device found with id(%d)",
7846 __func__, patchDesc->mPatch.sinks[i].id);
7847 return false;
7848 }
7849 routedDevices.add(device);
7850 }
7851 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007852 if (client->isInvalid()) {
7853 // No need to take care about invalidated clients.
7854 continue;
7855 }
jiabinbce0c1d2020-10-05 11:20:18 -07007856 sp<DeviceDescriptor> preferredDevice =
7857 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7858 if (mEngine->getOutputDevicesForAttributes(
7859 client->attributes(), preferredDevice, false) == routedDevices) {
7860 return false;
7861 }
7862 }
7863 return true;
7864}
7865
7866sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007867 const sp<IOProfile>& profile, const DeviceVector& devices,
7868 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007869{
7870 for (const auto& device : devices) {
7871 // TODO: This should be checking if the profile supports the device combo.
7872 if (!profile->supportsDevice(device)) {
7873 return nullptr;
7874 }
7875 }
7876 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7877 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007878 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007879 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7880 if (status != NO_ERROR) {
7881 return nullptr;
7882 }
7883
7884 // Here is where the out_set_parameters() for card & device gets called
7885 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7886 const audio_devices_t deviceType = device->type();
7887 const String8 &address = String8(device->address().c_str());
7888 if (!address.isEmpty()) {
7889 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7890 mpClientInterface->setParameters(output, String8(param));
7891 free(param);
7892 }
7893 updateAudioProfiles(device, output, profile->getAudioProfiles());
7894 if (!profile->hasValidAudioProfile()) {
7895 ALOGW("%s() missing param", __func__);
7896 desc->close();
7897 return nullptr;
7898 } else if (profile->hasDynamicAudioProfile()) {
7899 desc->close();
7900 output = AUDIO_IO_HANDLE_NONE;
7901 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7902 profile->pickAudioProfile(
7903 config.sample_rate, config.channel_mask, config.format);
7904 config.offload_info.sample_rate = config.sample_rate;
7905 config.offload_info.channel_mask = config.channel_mask;
7906 config.offload_info.format = config.format;
7907
Eric Laurentb4f42a92022-01-17 17:37:31 +01007908 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007909 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7910 if (status != NO_ERROR) {
7911 return nullptr;
7912 }
7913 }
7914
7915 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007916
baek.kim -61c20122022-07-27 10:05:32 +00007917 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7918 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7919
jiabinbce0c1d2020-10-05 11:20:18 -07007920 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7921 sp<AudioPolicyMix> policyMix;
7922 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7923 policyMix->setOutput(desc);
7924 desc->mPolicyMix = policyMix;
7925 } else {
7926 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7927 address.string());
7928 }
7929
baek.kim -61c20122022-07-27 10:05:32 +00007930 } else if (hasPrimaryOutput() && speaker != nullptr
7931 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007932 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7933 // no duplicated output for:
7934 // - direct outputs
7935 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007936 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007937 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7938
7939 //TODO: configure audio effect output stage here
7940
7941 // open a duplicating output thread for the new output and the primary output
7942 sp<SwAudioOutputDescriptor> dupOutputDesc =
7943 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7944 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7945 if (status == NO_ERROR) {
7946 // add duplicated output descriptor
7947 addOutput(duplicatedOutput, dupOutputDesc);
7948 } else {
7949 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7950 mPrimaryOutput->mIoHandle, output);
7951 desc->close();
7952 removeOutput(output);
7953 nextAudioPortGeneration();
7954 return nullptr;
7955 }
7956 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007957 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7958 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7959 mPrimaryOutput = desc;
7960 }
jiabinbce0c1d2020-10-05 11:20:18 -07007961 return desc;
7962}
7963
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007964} // namespace android