blob: 8c8278cbc966f9b3f0ea48a1f1713dffa1bd0659 [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:
599 audioDeviceSet = getAudioDeviceOutAllBleSet();
600 break;
601 default:
602 ALOGE("%s() device type 0x%08x not supported", __func__, device);
603 return BAD_VALUE;
604 }
605
jiabin9a3361e2019-10-01 09:38:30 -0700606 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800607 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800608 for (const auto& device : declaredDevices) {
609 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800610 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800611 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800612 return status;
613}
614
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100615DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
616{
617 DeviceVector rxSinkdevices{};
618 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
619 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
620 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
621 auto rxSinkDevice = rxSinkdevices.itemAt(0);
622 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
623 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
624 // retrieve Rx Source device descriptor
625 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
626 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
627
628 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
629 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
630 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
631 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
632 return DeviceVector(rxSinkDevice);
633 }
634 }
635 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
636 // the device returned is not necessarily reachable via this output
637 // (filter later by setOutputDevices())
638 return getNewOutputDevices(mPrimaryOutput, fromCache);
639}
640
641status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
642{
643 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
644 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
645 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
646 }
647 return INVALID_OPERATION;
648}
649
650status_t AudioPolicyManager::updateCallRoutingInternal(
651 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700652{
653 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100654 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700655 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700656 if(!hasPrimaryOutput() ||
657 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700659 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100660 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100661
Francois Gaffie716e1432019-01-14 16:58:59 +0100662 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100663 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100665
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100666 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100667 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668
Francois Gaffie601801d2021-06-22 13:27:39 +0200669 disconnectTelephonyAudioSource(mCallRxSourceClient);
670 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671
François Gaffie9eb18552018-11-05 10:33:26 +0100672 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700673 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100674 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700675 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100676 // retrieve Rx Source and Tx Sink device descriptors
677 sp<DeviceDescriptor> rxSourceDevice =
678 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
679 String8(),
680 AUDIO_FORMAT_DEFAULT);
681 sp<DeviceDescriptor> txSinkDevice =
682 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
683 String8(),
684 AUDIO_FORMAT_DEFAULT);
685
686 // RX and TX Telephony device are declared by Primary Audio HAL
687 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
688 (telephonyRxModule->getHalVersionMajor() >= 3)) {
689 if (rxSourceDevice == 0 || txSinkDevice == 0) {
690 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100691 ALOGE("%s() no telephony Tx and/or RX device", __func__);
692 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100693 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100694 // createAudioPatchInternal now supports both HW / SW bridging
695 createRxPatch = true;
696 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100697 } else {
698 // If the RX device is on the primary HW module, then use legacy routing method for
699 // voice calls via setOutputDevice() on primary output.
700 // Otherwise, create two audio patches for TX and RX path.
701 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
702 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700703 // If the TX device is also on the primary HW module, setOutputDevice() will take care
704 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100705 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
706 (txSinkDevice != 0);
707 }
708 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
709 // Otherwise, create two audio patches for TX and RX path.
710 if (!createRxPatch) {
711 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700712 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200713 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800714 // If the TX device is on the primary HW module but RX device is
715 // on other HW module, SinkMetaData of telephony input should handle it
716 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700717 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700718 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 // terminate active capture if on the same HW module as the call TX source device
720 // FIXME: would be better to refine to only inputs whose profile connects to the
721 // call TX device but this information is not in the audio patch and logic here must be
722 // symmetric to the one in startInput()
723 for (const auto& activeDesc : mInputs.getActiveInputs()) {
724 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
725 closeActiveClients(activeDesc);
726 }
727 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200728 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800729 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100730 if (waitMs != nullptr) {
731 *waitMs = muteWaitMs;
732 }
733 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800734}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700735
Mikhail Naganov100f0122018-11-29 11:22:16 -0800736bool AudioPolicyManager::isDeviceOfModule(
737 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
738 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
739 if (module != 0) {
740 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
741 .indexOf(devDesc) != NAME_NOT_FOUND
742 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
743 .indexOf(devDesc) != NAME_NOT_FOUND;
744 }
745 return false;
746}
747
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200748void AudioPolicyManager::connectTelephonyRxAudioSource()
749{
Francois Gaffie601801d2021-06-22 13:27:39 +0200750 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200751 const struct audio_port_config source = {
752 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
753 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
754 };
755 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200756 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
757 ALOGE_IF(mCallRxSourceClient == nullptr,
758 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200759}
760
Francois Gaffie601801d2021-06-22 13:27:39 +0200761void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200762{
Francois Gaffie601801d2021-06-22 13:27:39 +0200763 if (clientDesc == nullptr) {
764 return;
765 }
766 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
767 "%s error stopping audio source", __func__);
768 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200769}
770
771void AudioPolicyManager::connectTelephonyTxAudioSource(
772 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
773 uint32_t delayMs)
774{
Francois Gaffie601801d2021-06-22 13:27:39 +0200775 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200776 if (srcDevice == nullptr || sinkDevice == nullptr) {
777 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
778 return;
779 }
780 PatchBuilder patchBuilder;
781 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
782 ALOGV("%s between source %s and sink %s", __func__,
783 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200785 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
786 struct audio_port_config source = {};
787 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200788 mCallTxSourceClient = new InternalSourceClientDescriptor(
789 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200790 mCommunnicationStrategy, toVolumeSource(aa));
791 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
792 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200793 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
794 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200795 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
796 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200799}
800
Eric Laurente0720872014-03-11 09:30:41 -0700801void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700802{
803 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100804 // store previous phone state for management of sonification strategy below
805 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100806 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100807
808 if (mEngine->setPhoneState(state) != NO_ERROR) {
809 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700810 return;
811 }
François Gaffie2110e042015-03-24 08:41:51 +0100812 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700813 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700814 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700815 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800816 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 }
818
François Gaffie2110e042015-03-24 08:41:51 +0100819 /**
820 * Switching to or from incall state or switching between telephony and VoIP lead to force
821 * routing command.
822 */
Eric Laurent74b71512019-11-06 17:21:57 -0800823 bool force = ((isStateInCall(oldState) != isStateInCall(state))
824 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700825
826 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700827 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700828
Eric Laurente552edb2014-03-10 17:42:56 -0700829 int delayMs = 0;
830 if (isStateInCall(state)) {
831 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100832 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
833 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700834 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700835 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700836 // mute media and sonification strategies and delay device switch by the largest
837 // latency of any output where either strategy is active.
838 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100839 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
840 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
841 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700842 (delayMs < (int)desc->latency()*2)) {
843 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700844 }
François Gaffiec005e562018-11-06 15:04:49 +0100845 setStrategyMute(musicStrategy, true, desc);
846 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
847 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
848 nullptr, true /*fromCache*/).types());
849 setStrategyMute(sonificationStrategy, true, desc);
850 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
851 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
852 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700853 }
854 }
855
Eric Laurent87ffa392015-05-22 10:32:38 -0700856 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700857 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100858 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700859 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100860 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
861 // force routing command to audio hardware when ending call
862 // even if no device change is needed
863 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
864 rxDevices = mPrimaryOutput->devices();
865 }
866 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200867 disconnectTelephonyAudioSource(mCallRxSourceClient);
868 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100869 }
François Gaffie11d30102018-11-02 16:09:09 +0100870 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700871 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700872 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700873
874 // reevaluate routing on all outputs in case tracks have been started during the call
875 for (size_t i = 0; i < mOutputs.size(); i++) {
876 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100877 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200878 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
879 bool forceRouting = !newDevices.isEmpty();
880 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
881 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700882 }
883 }
884
Eric Laurent96d1dda2022-03-14 17:14:19 +0100885 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
886
Eric Laurente552edb2014-03-10 17:42:56 -0700887 if (isStateInCall(state)) {
888 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700889 // force reevaluating accessibility routing when call starts
890 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 }
892
893 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100894 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
895 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700896}
897
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700898audio_mode_t AudioPolicyManager::getPhoneState() {
899 return mEngine->getPhoneState();
900}
901
Eric Laurente0720872014-03-11 09:30:41 -0700902void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100903 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700904{
François Gaffie2110e042015-03-24 08:41:51 +0100905 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700906 if (config == mEngine->getForceUse(usage)) {
907 return;
908 }
Eric Laurente552edb2014-03-10 17:42:56 -0700909
François Gaffie2110e042015-03-24 08:41:51 +0100910 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
911 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
912 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700913 }
François Gaffie2110e042015-03-24 08:41:51 +0100914 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
915 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
916 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700917
918 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700919 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800920
Eric Laurent22fcda22019-05-17 16:28:47 -0700921 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
922 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
923 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
924 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
925 }
926
Eric Laurentdc462862016-07-19 12:29:53 -0700927 //FIXME: workaround for truncated touch sounds
928 // to be removed when the problem is handled by system UI
929 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700930 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
931 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
932 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700933
934 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100935 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700936}
937
Eric Laurente0720872014-03-11 09:30:41 -0700938void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700939{
940 ALOGV("setSystemProperty() property %s, value %s", property, value);
941}
942
Dorin Drimusecc9f422022-03-09 17:57:40 +0100943// Find an MSD output profile compatible with the parameters passed.
944// When "directOnly" is set, restrict search to profiles for direct outputs.
945sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
946 const DeviceVector& devices,
947 uint32_t samplingRate,
948 audio_format_t format,
949 audio_channel_mask_t channelMask,
950 audio_output_flags_t flags,
951 bool directOnly)
952{
953 flags = getRelevantFlags(flags, directOnly);
954
955 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
956 if (msdModule != nullptr) {
957 // for the msd module check if there are patches to the output devices
958 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
959 HwModuleCollection modules;
960 modules.add(msdModule);
961 return searchCompatibleProfileHwModules(
962 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
963 flags, directOnly);
964 }
965 }
966 return nullptr;
967}
968
Michael Chana94fbb22018-04-24 14:31:19 +1000969// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
970// search to profiles for direct outputs.
971sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100972 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000973 uint32_t samplingRate,
974 audio_format_t format,
975 audio_channel_mask_t channelMask,
976 audio_output_flags_t flags,
977 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700978{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100979 flags = getRelevantFlags(flags, directOnly);
980
981 return searchCompatibleProfileHwModules(
982 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
983}
984
985audio_output_flags_t AudioPolicyManager::getRelevantFlags (
986 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000987 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100988 // only retain flags that will drive the direct output profile selection
989 // if explicitly requested
990 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000991 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100992 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
993 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000994 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100995 return flags;
996}
Eric Laurent861a6282015-05-18 15:40:16 -0700997
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
999 const HwModuleCollection& hwModules,
1000 const DeviceVector& devices,
1001 uint32_t samplingRate,
1002 audio_format_t format,
1003 audio_channel_mask_t channelMask,
1004 audio_output_flags_t flags,
1005 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001006 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001007 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001008 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009 if (!curProfile->isCompatibleProfile(devices,
1010 samplingRate, NULL /*updatedSamplingRate*/,
1011 format, NULL /*updatedFormat*/,
1012 channelMask, NULL /*updatedChannelMask*/,
1013 flags)) {
1014 continue;
1015 }
1016 // reject profiles not corresponding to a device currently available
1017 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1018 continue;
1019 }
1020 // reject profiles if connected device does not support codec
1021 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1022 continue;
1023 }
1024 if (!directOnly) {
1025 return curProfile;
1026 }
1027
1028 // when searching for direct outputs, if several profiles are compatible, give priority
1029 // to one with offload capability
1030 if (profile != 0 &&
1031 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001032 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 }
1034 profile = curProfile;
1035 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1036 break;
1037 }
Eric Laurente552edb2014-03-10 17:42:56 -07001038 }
1039 }
Eric Laurent861a6282015-05-18 15:40:16 -07001040 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001041}
1042
Eric Laurentfa0f6742021-08-17 18:39:44 +02001043sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001044 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001045{
1046 for (const auto& hwModule : mHwModules) {
1047 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001048 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001049 continue;
1050 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001051 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001052 // reject profiles not corresponding to a device currently available
1053 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1054 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1055 continue;
1056 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001057 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1058 != devices.size()) {
1059 continue;
1060 }
1061 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001062 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1063 return curProfile;
1064 }
1065 }
1066 return nullptr;
1067}
1068
Eric Laurentf4e63452017-11-06 19:31:46 +00001069audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001070{
François Gaffiec005e562018-11-06 15:04:49 +01001071 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001072
1073 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1074 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1075 // format, flags, etc. This may result in some discrepancy for functions that utilize
1076 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1077 // and AudioSystem::getOutputSamplingRate().
1078
François Gaffie11d30102018-11-02 16:09:09 +01001079 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001080 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001081
François Gaffie11d30102018-11-02 16:09:09 +01001082 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1083 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001084 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001085}
1086
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001087status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1088 const audio_attributes_t *srcAttr,
1089 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001090{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001091 if (srcAttr != NULL) {
1092 if (!isValidAttributes(srcAttr)) {
1093 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1094 __func__,
1095 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1096 srcAttr->tags);
1097 return BAD_VALUE;
1098 }
1099 *dstAttr = *srcAttr;
1100 } else {
1101 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1102 ALOGE("%s: invalid stream type", __func__);
1103 return BAD_VALUE;
1104 }
François Gaffiec005e562018-11-06 15:04:49 +01001105 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001106 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001107
1108 // Only honor audibility enforced when required. The client will be
1109 // forced to reconnect if the forced usage changes.
1110 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001111 dstAttr->flags = static_cast<audio_flags_mask_t>(
1112 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001113 }
1114
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001115 return NO_ERROR;
1116}
1117
Kevin Rocard153f92d2018-12-18 18:33:28 -08001118status_t AudioPolicyManager::getOutputForAttrInt(
1119 audio_attributes_t *resultAttr,
1120 audio_io_handle_t *output,
1121 audio_session_t session,
1122 const audio_attributes_t *attr,
1123 audio_stream_type_t *stream,
1124 uid_t uid,
1125 const audio_config_t *config,
1126 audio_output_flags_t *flags,
1127 audio_port_handle_t *selectedDeviceId,
1128 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001129 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001130 output_type_t *outputType,
1131 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001132{
François Gaffiec005e562018-11-06 15:04:49 +01001133 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001134 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001135 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001136 const sp<DeviceDescriptor> requestedDevice =
1137 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1138
Eric Laurent8a1095a2019-11-08 14:44:16 -08001139 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001140 *isSpatialized = false;
1141
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001142 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1143 if (status != NO_ERROR) {
1144 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001145 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001146 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001147 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001148 }
François Gaffiec005e562018-11-06 15:04:49 +01001149 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001150
François Gaffiec005e562018-11-06 15:04:49 +01001151 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1152 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001153
Kevin Rocard153f92d2018-12-18 18:33:28 -08001154 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1155 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1156 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001157 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001158 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1159 .channel_mask = config->channel_mask,
1160 .format = config->format,
1161 };
1162 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1163 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001164 if (status != OK) {
1165 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001166 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001167
Kevin Rocard153f92d2018-12-18 18:33:28 -08001168 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001169 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001170
1171 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001172 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1173 && !audio_is_linear_pcm(config->format)) {
1174 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001175 return BAD_VALUE;
1176 }
1177 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001178 sp<DeviceDescriptor> deviceDesc =
1179 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1180 primaryMix->mDeviceAddress,
1181 AUDIO_FORMAT_DEFAULT);
1182 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001183 bool tryDirectForFlags = policyDesc == nullptr ||
1184 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1185 // if a direct output can be opened to deliver the track's multi-channel content to the
1186 // output rather than being downmixed by the primary output, then use this direct
1187 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1188 // mix.
1189 bool tryDirectForChannelMask = policyDesc != nullptr
1190 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1191 audio_channel_count_from_out_mask(config->channel_mask));
1192 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001193 audio_io_handle_t newOutput;
1194 status = openDirectOutput(
1195 *stream, session, config,
1196 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1197 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001198 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001199 policyDesc = mOutputs.valueFor(newOutput);
1200 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001201 } else if (tryDirectForFlags) {
1202 policyDesc = nullptr;
1203 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001204 }
1205 if (policyDesc != nullptr) {
1206 policyDesc->mPolicyMix = primaryMix;
1207 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001208 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001209
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001210 ALOGV("getOutputForAttr() returns output %d", *output);
1211 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1212 *outputType = API_OUT_MIX_PLAYBACK;
1213 } else {
1214 *outputType = API_OUTPUT_LEGACY;
1215 }
1216 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001217 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001218 }
François Gaffiec005e562018-11-06 15:04:49 +01001219 // Virtual sources must always be dynamicaly or explicitly routed
1220 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1221 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1222 return BAD_VALUE;
1223 }
1224 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1225 // in order to let the choice of the order to future vendor engine
1226 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001227
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001228 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001229 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001230 }
1231
Nadav Barb2f18162018-07-18 13:01:53 +03001232 // Set incall music only if device was explicitly set, and fallback to the device which is
1233 // chosen by the engine if not.
1234 // FIXME: provide a more generic approach which is not device specific and move this back
1235 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001236 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001237 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001238 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001239 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001240 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001241 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001242 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001243 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001244 }
1245 }
1246
François Gaffiec005e562018-11-06 15:04:49 +01001247 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1248 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1249 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001250
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001251 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001252 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001253 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001254 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001255 ALOGV("%s() Using MSD devices %s instead of devices %s",
1256 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001257 } else {
1258 *output = AUDIO_IO_HANDLE_NONE;
1259 }
1260 }
1261 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001262 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001263 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001264 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001265 if (*output == AUDIO_IO_HANDLE_NONE) {
1266 return INVALID_OPERATION;
1267 }
Paul McLeanaa981192015-03-21 09:55:15 -07001268
François Gaffiec005e562018-11-06 15:04:49 +01001269 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001270 for (auto &outputDevice : outputDevices) {
1271 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1272 *selectedDeviceId = outputDevice->getId();
1273 break;
1274 }
1275 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001276
Eric Laurent8a1095a2019-11-08 14:44:16 -08001277 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1278 *outputType = API_OUTPUT_TELEPHONY_TX;
1279 } else {
1280 *outputType = API_OUTPUT_LEGACY;
1281 }
1282
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001283 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1284
1285 return NO_ERROR;
1286}
1287
1288status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1289 audio_io_handle_t *output,
1290 audio_session_t session,
1291 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001292 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001293 const audio_config_t *config,
1294 audio_output_flags_t *flags,
1295 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001296 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001297 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001298 output_type_t *outputType,
1299 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001300{
1301 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1302 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1303 return INVALID_OPERATION;
1304 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001305 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001306 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001307 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001308 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001309 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001310 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001311 const sp<DeviceDescriptor> requestedDevice =
1312 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1313
1314 // Prevent from storing invalid requested device id in clients
1315 const audio_port_handle_t sanitizedRequestedPortId =
1316 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1317 *selectedDeviceId = sanitizedRequestedPortId;
1318
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001319 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001320 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001321 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001322 if (status != NO_ERROR) {
1323 return status;
1324 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001325 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001326 if (secondaryOutputs != nullptr) {
1327 for (auto &secondaryMix : secondaryMixes) {
1328 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1329 if (outputDesc != nullptr &&
1330 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1331 secondaryOutputs->push_back(outputDesc->mIoHandle);
1332 weakSecondaryOutputDescs.push_back(outputDesc);
1333 }
1334 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001335 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001336
Eric Laurent8fc147b2018-07-22 19:13:55 -07001337 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001338 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001339 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001340 };
jiabin4ef93452019-09-10 14:29:54 -07001341 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001342
Eric Laurentc209fe42020-06-05 18:11:23 -07001343 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001344 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001345 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001346 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001347 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001348 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001349 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001350 std::move(weakSecondaryOutputDescs),
1351 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001352 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001353
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001354 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1355 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001356
Eric Laurente83b55d2014-11-14 10:06:21 -08001357 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001358}
1359
Eric Laurentc529cf62020-04-17 18:19:10 -07001360status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1361 audio_session_t session,
1362 const audio_config_t *config,
1363 audio_output_flags_t flags,
1364 const DeviceVector &devices,
1365 audio_io_handle_t *output) {
1366
1367 *output = AUDIO_IO_HANDLE_NONE;
1368
1369 // skip direct output selection if the request can obviously be attached to a mixed output
1370 // and not explicitly requested
1371 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1372 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1373 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1374 return NAME_NOT_FOUND;
1375 }
1376
1377 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1378 // This prevents creating an offloaded track and tearing it down immediately after start
1379 // when audioflinger detects there is an active non offloadable effect.
1380 // FIXME: We should check the audio session here but we do not have it in this context.
1381 // This may prevent offloading in rare situations where effects are left active by apps
1382 // in the background.
1383 sp<IOProfile> profile;
1384 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1385 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1386 profile = getProfileForOutput(
1387 devices, config->sample_rate, config->format, config->channel_mask,
1388 flags, true /* directOnly */);
1389 }
1390
1391 if (profile == nullptr) {
1392 return NAME_NOT_FOUND;
1393 }
1394
1395 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1396 for (size_t i = 0; i < mOutputs.size(); i++) {
1397 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1398 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1399 // reuse direct output if currently open by the same client
1400 // and configured with same parameters
1401 if ((config->sample_rate == desc->getSamplingRate()) &&
1402 (config->format == desc->getFormat()) &&
1403 (config->channel_mask == desc->getChannelMask()) &&
1404 (session == desc->mDirectClientSession)) {
1405 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001406 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001407 mOutputs.keyAt(i), session);
1408 *output = mOutputs.keyAt(i);
1409 return NO_ERROR;
1410 }
1411 }
1412 }
1413
1414 if (!profile->canOpenNewIo()) {
1415 return NAME_NOT_FOUND;
1416 }
1417
1418 sp<SwAudioOutputDescriptor> outputDesc =
1419 new SwAudioOutputDescriptor(profile, mpClientInterface);
1420
Michael Chan6fb34492020-12-08 15:44:49 +11001421 // An MSD patch may be using the only output stream that can service this request. Release
1422 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001423 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001424
Eric Laurentf1f22e72021-07-13 14:04:14 +02001425 status_t status =
1426 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001427
1428 // only accept an output with the requested parameters
1429 if (status != NO_ERROR ||
1430 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1431 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1432 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1433 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1434 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1435 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1436 config->channel_mask, outputDesc->getChannelMask());
1437 if (*output != AUDIO_IO_HANDLE_NONE) {
1438 outputDesc->close();
1439 }
1440 // fall back to mixer output if possible when the direct output could not be open
1441 if (audio_is_linear_pcm(config->format) &&
1442 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1443 return NAME_NOT_FOUND;
1444 }
1445 *output = AUDIO_IO_HANDLE_NONE;
1446 return BAD_VALUE;
1447 }
1448 outputDesc->mDirectOpenCount = 1;
1449 outputDesc->mDirectClientSession = session;
1450
1451 addOutput(*output, outputDesc);
1452 mPreviousOutputs = mOutputs;
1453 ALOGV("%s returns new direct output %d", __func__, *output);
1454 mpClientInterface->onAudioPortListUpdate();
1455 return NO_ERROR;
1456}
1457
François Gaffie11d30102018-11-02 16:09:09 +01001458audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1459 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001460 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001461 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001462 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001463 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001464 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001465 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001466{
Andy Hungc88b0642018-04-27 15:42:35 -07001467 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001468
jiabine375d412019-02-26 12:54:53 -08001469 // Discard haptic channel mask when forcing muting haptic channels.
1470 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001471 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1472 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001473
Eric Laurente552edb2014-03-10 17:42:56 -07001474 // open a direct output if required by specified parameters
1475 //force direct flag if offload flag is set: offloading implies a direct output stream
1476 // and all common behaviors are driven by checking only the direct flag
1477 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001478 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1479 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001480 }
Nadav Bar766fb022018-01-07 12:18:03 +02001481 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1482 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001483 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001484
1485 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1486
Eric Laurente83b55d2014-11-14 10:06:21 -08001487 // only allow deep buffering for music stream type
1488 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001489 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001490 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001491 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001492 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1493 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001494 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001495 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001496 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001497 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001498 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001499 audio_is_linear_pcm(config->format) &&
1500 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001501 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001502 AUDIO_OUTPUT_FLAG_DIRECT);
1503 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001504 }
Eric Laurente552edb2014-03-10 17:42:56 -07001505
Carter Hsua3abb402021-10-26 11:11:20 +08001506 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1507 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1508 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1509 }
1510
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001511 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001512 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001513 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001514 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001515 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001516 }
1517
Eric Laurentc529cf62020-04-17 18:19:10 -07001518 audio_config_t directConfig = *config;
1519 directConfig.channel_mask = channelMask;
1520 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1521 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001522 return output;
1523 }
1524
Eric Laurent14cbfca2016-03-17 09:42:16 -07001525 // A request for HW A/V sync cannot fallback to a mixed output because time
1526 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001527 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001528 return AUDIO_IO_HANDLE_NONE;
1529 }
1530
Eric Laurente552edb2014-03-10 17:42:56 -07001531 // ignoring channel mask due to downmix capability in mixer
1532
1533 // open a non direct output
1534
1535 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001536 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001537 // get which output is suitable for the specified stream. The actual
1538 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001539 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001540
Eric Laurent8838a382014-09-08 16:44:28 -07001541 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001542 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001543 output = selectOutput(
1544 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001545 }
François Gaffie11d30102018-11-02 16:09:09 +01001546 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001547 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001548 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001549
Eric Laurente552edb2014-03-10 17:42:56 -07001550 return output;
1551}
1552
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001553sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001554 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1555 mAvailableInputDevices);
1556 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1557}
1558
1559DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1560 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1561 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001562}
1563
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001564const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001565 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001566 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1567 if (msdModule != 0) {
1568 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1569 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1570 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1571 const struct audio_port_config *source = &patch->mPatch.sources[j];
1572 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1573 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001574 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001575 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001576 }
1577 }
1578 }
1579 return msdPatches;
1580}
1581
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001582bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1583 ssize_t index = mAudioPatches.indexOfKey(handle);
1584 if (index < 0) {
1585 return false;
1586 }
1587 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1588 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1589 if (msdModule == nullptr) {
1590 return false;
1591 }
1592 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1593 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1594 return true;
1595 }
1596 index = getMsdOutputPatches().indexOfKey(handle);
1597 if (index < 0) {
1598 return false;
1599 }
1600 return true;
1601}
1602
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001603status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1604 const InputProfileCollection &inputProfiles,
1605 const OutputProfileCollection &outputProfiles,
1606 const sp<DeviceDescriptor> &sourceDevice,
1607 const sp<DeviceDescriptor> &sinkDevice,
1608 AudioProfileVector& sourceProfiles,
1609 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001610 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001611 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001612 return NO_INIT;
1613 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001614 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001615 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001616 return NO_INIT;
1617 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001618 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001619 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1620 inProfile->supportsDevice(sourceDevice)) {
1621 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 }
1623 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001625 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001626 outProfile->supportsDevice(sinkDevice)) {
1627 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628 }
1629 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630 return NO_ERROR;
1631}
1632
1633status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1634 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1635 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1636{
Dean Wheatley16809da2022-12-09 14:55:46 +11001637 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1638 static const std::vector<audio_format_t> formatsOrder = {{
1639 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1640 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1641 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1642 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1643 // preferred).
1644 std::vector<audio_channel_mask_t> masks = {{
1645 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1646 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1647 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1648 // insert index masks (higher counts most preferred) as preferred over position masks
1649 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1650 masks.insert(
1651 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1652 }
1653 return masks;
1654 }();
1655
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001656 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001657 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1658 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001659 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001660 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1661 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001662 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001663 }
1664 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1665 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1666 sinkConfig->format = bestSinkConfig.format;
1667 // For encoded streams force direct flag to prevent downstream mixing.
1668 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1669 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001670 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1671 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001672 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001673 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1674 // raw and IEC61937 framed streams.
1675 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1676 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1677 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1679 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001680 sourceConfig->channel_mask =
1681 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1682 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1683 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 sourceConfig->format = bestSinkConfig.format;
1685 // Copy input stream directly without any processing (e.g. resampling).
1686 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1687 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1688 if (hwAvSync) {
1689 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1690 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1691 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1692 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1693 }
1694 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1695 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1696 sinkConfig->config_mask |= config_mask;
1697 sourceConfig->config_mask |= config_mask;
1698 return NO_ERROR;
1699}
1700
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001701PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1702 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703{
1704 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001705 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1706 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1707 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1708 if (deviceModule == nullptr) {
1709 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1710 return patchBuilder;
1711 }
1712 const InputProfileCollection inputProfiles = msdIsSource ?
1713 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1714 const OutputProfileCollection outputProfiles = msdIsSource ?
1715 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1716
1717 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1718 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1719 device : getMsdAudioOutDevices().itemAt(0);
1720 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1721
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1723 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001724 AudioProfileVector sourceProfiles;
1725 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1727 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001728 for (auto hwAvSync : { true, false }) {
1729 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1730 sourceProfiles, sinkProfiles) != NO_ERROR) {
1731 continue;
1732 }
1733 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1734 &sinkConfig) == NO_ERROR) {
1735 // Found a matching config. Re-create PatchBuilder with this config.
1736 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1737 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001739 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 " supporting PCM format conversion.", __func__);
1741 return patchBuilder;
1742}
1743
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001745 DeviceVector devices;
1746 if (outputDevices != nullptr && outputDevices->size() > 0) {
1747 devices.add(*outputDevices);
1748 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001749 // Use media strategy for unspecified output device. This should only
1750 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1751 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001752 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001753 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001754 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 }
Michael Chan6fb34492020-12-08 15:44:49 +11001756 std::vector<PatchBuilder> patchesToCreate;
1757 for (auto i = 0u; i < devices.size(); ++i) {
1758 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001760 }
1761 // Retain only the MSD patches associated with outputDevices request.
1762 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001763 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001764 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1765 auto retainedPatch = false;
1766 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1767 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1768 patchesToRemove.removeItemsAt(i);
1769 retainedPatch = true;
1770 break;
1771 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 }
Michael Chan6fb34492020-12-08 15:44:49 +11001773 if (retainedPatch) {
1774 it = patchesToCreate.erase(it);
1775 continue;
1776 }
1777 ++it;
1778 }
1779 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1780 return NO_ERROR;
1781 }
1782 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1783 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001784 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 }
Michael Chan6fb34492020-12-08 15:44:49 +11001786 status_t status = NO_ERROR;
1787 for (const auto &p : patchesToCreate) {
1788 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1789 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1790 char message[256];
1791 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1792 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1793 currStatus == NO_ERROR ? "Success" : "Error",
1794 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1795 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1796 if (currStatus == NO_ERROR) {
1797 ALOGD("%s", message);
1798 } else {
1799 ALOGE("%s", message);
1800 if (status == NO_ERROR) {
1801 status = currStatus;
1802 }
1803 }
1804 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 return status;
1806}
1807
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1809 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001810 for (size_t i = 0; i < msdPatches.size(); i++) {
1811 const auto& patch = msdPatches[i];
1812 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1813 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1814 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1815 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1816 releaseAudioPatch(patch->getHandle(), mUidCached);
1817 break;
1818 }
1819 }
1820 }
1821}
1822
Dorin Drimus94d94412022-02-02 09:05:02 +01001823bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1824 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1825 AudioPatchCollection msdPatches = getMsdOutputPatches();
1826 for (size_t i = 0; i < msdPatches.size(); i++) {
1827 const auto& patch = msdPatches[i];
1828 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1829 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1830 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1831 const auto& foundDevice = devicesToCheck.getDevice(
1832 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1833 if (foundDevice != nullptr) {
1834 devicesToCheck.remove(foundDevice);
1835 if (devicesToCheck.isEmpty()) {
1836 return true;
1837 }
1838 }
1839 }
1840 }
1841 }
1842 return false;
1843}
1844
Eric Laurente0720872014-03-11 09:30:41 -07001845audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001846 audio_output_flags_t flags,
1847 audio_format_t format,
1848 audio_channel_mask_t channelMask,
1849 uint32_t samplingRate,
1850 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001851{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001852 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1853 "%s called with format %#x", __func__, format);
1854
jiabinebb6af42020-06-09 17:31:17 -07001855 // Return the output that haptic-generating attached to when 1) session id is specified,
1856 // 2) haptic-generating effect exists for given session id and 3) the output that
1857 // haptic-generating effect attached to is in given outputs.
1858 if (sessionId != AUDIO_SESSION_NONE) {
1859 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1860 sessionId, FX_IID_HAPTICGENERATOR);
1861 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1862 return hapticGeneratingOutput;
1863 }
1864 }
1865
Eric Laurent16c66dd2019-05-01 17:54:10 -07001866 // Flags disqualifying an output: the match must happen before calling selectOutput()
1867 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1868 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1869
1870 // Flags expressing a functional request: must be honored in priority over
1871 // other criteria
1872 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1873 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001874 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1875 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001876 // Flags expressing a performance request: have lower priority than serving
1877 // requested sampling rate or channel mask
1878 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1879 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1880 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1881
1882 const audio_output_flags_t functionalFlags =
1883 (audio_output_flags_t)(flags & kFunctionalFlags);
1884 const audio_output_flags_t performanceFlags =
1885 (audio_output_flags_t)(flags & kPerformanceFlags);
1886
1887 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1888
Eric Laurente552edb2014-03-10 17:42:56 -07001889 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001890 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001891 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001892 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001893 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001894 // with tiebreak preferring the minimum number of extra functional flags
1895 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001896 // 3: the output supporting the exact channel mask
1897 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001898 // 5: the output with the highest sampling rate if the requested sample rate is
1899 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001900 // 6: the output with the highest number of requested performance flags
1901 // 7: the output with the bit depth the closest to the requested one
1902 // 8: the primary output
1903 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001904
Eric Laurent16c66dd2019-05-01 17:54:10 -07001905 // matching criteria values in priority order for best matching output so far
1906 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001907
Eric Laurent16c66dd2019-05-01 17:54:10 -07001908 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1909 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1910 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001911
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001912 for (audio_io_handle_t output : outputs) {
1913 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001914 // matching criteria values in priority order for current output
1915 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001916
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 if (outputDesc->isDuplicated()) {
1918 continue;
1919 }
1920 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1921 continue;
1922 }
Eric Laurent8838a382014-09-08 16:44:28 -07001923
Eric Laurent16c66dd2019-05-01 17:54:10 -07001924 // If haptic channel is specified, use the haptic output if present.
1925 // When using haptic output, same audio format and sample rate are required.
1926 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001927 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001928 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1929 continue;
1930 }
1931 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001932 && format == outputDesc->getFormat()
1933 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001934 currentMatchCriteria[0] = outputHapticChannelCount;
1935 }
1936
1937 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001938 const int matchingFunctionalFlags =
1939 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1940 const int totalFunctionalFlags =
1941 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1942 // Prefer matching functional flags, but subtract unnecessary functional flags.
1943 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001944
1945 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001946 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1947 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001948 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1949 channelCount <= outputChannelCount) {
1950 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001951 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1952 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001954 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001955 currentMatchCriteria[3] = outputChannelCount;
1956 }
1957
1958 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001959 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001960 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001961 }
1962
1963 // performance flags match
1964 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1965
1966 // format match
1967 if (format != AUDIO_FORMAT_INVALID) {
1968 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001969 PolicyAudioPort::kFormatDistanceMax -
1970 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001971 }
1972
1973 // primary output match
1974 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1975
1976 // compare match criteria by priority then value
1977 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1978 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1979 bestMatchCriteria = currentMatchCriteria;
1980 bestOutput = output;
1981
1982 std::stringstream result;
1983 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1984 std::ostream_iterator<int>(result, " "));
1985 ALOGV("%s new bestOutput %d criteria %s",
1986 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001987 }
1988 }
1989
Eric Laurent16c66dd2019-05-01 17:54:10 -07001990 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001991}
1992
Eric Laurent8fc147b2018-07-22 19:13:55 -07001993status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001994{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001995 ALOGV("%s portId %d", __FUNCTION__, portId);
1996
1997 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1998 if (outputDesc == 0) {
1999 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002000 return BAD_VALUE;
2001 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002002 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002003
Eric Laurent8fc147b2018-07-22 19:13:55 -07002004 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002005 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002006
Eric Laurent733ce942017-12-07 12:18:25 -08002007 status_t status = outputDesc->start();
2008 if (status != NO_ERROR) {
2009 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002010 }
2011
Eric Laurent97ac8712018-07-27 18:59:02 -07002012 uint32_t delayMs;
2013 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002014
2015 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002016 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002017 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002018 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002019 if (delayMs != 0) {
2020 usleep(delayMs * 1000);
2021 }
2022
2023 return status;
2024}
2025
Eric Laurent96d1dda2022-03-14 17:14:19 +01002026bool AudioPolicyManager::isLeUnicastActive() const {
2027 if (isInCall()) {
2028 return true;
2029 }
2030 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2031}
2032
2033bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2034 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2035 return false;
2036 }
2037 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2038 ALOGV("%s active %d", __func__, active);
2039 return active;
2040}
2041
Eric Laurent97ac8712018-07-27 18:59:02 -07002042status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2043 const sp<TrackClientDescriptor>& client,
2044 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002045{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002046 // cannot start playback of STREAM_TTS if any other output is being used
2047 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002048
2049 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002051 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002052 auto clientStrategy = client->strategy();
2053 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002054 if (stream == AUDIO_STREAM_TTS) {
2055 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002056 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002057 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002058 return INVALID_OPERATION;
2059 } else {
2060 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2061 }
2062 } else {
2063 // some playback other than beacon starts
2064 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2065 }
2066
Eric Laurent77305a62016-07-25 16:39:22 -07002067 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002068 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002069 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002070
François Gaffie11d30102018-11-02 16:09:09 +01002071 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002072 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002073 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002074 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002075 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002076 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002077 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002078 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002079 } else {
2080 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002081 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002082 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2083 AUDIO_FORMAT_DEFAULT);
2084 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2085 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002086 }
2087
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002088 // requiresMuteCheck is false when we can bypass mute strategy.
2089 // It covers a common case when there is no materially active audio
2090 // and muting would result in unnecessary delay and dropped audio.
2091 const uint32_t outputLatencyMs = outputDesc->latency();
2092 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002093 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002094
Eric Laurente552edb2014-03-10 17:42:56 -07002095 // increment usage count for this stream on the requested output:
2096 // NOTE that the usage count is the same for duplicated output and hardware output which is
2097 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002098 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002099
2100 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002101 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2102 client->isPreferredDeviceForExclusiveUse()) {
2103 // Preferred device may be exclusive, use only if no other active clients on this output
2104 devices = DeviceVector(
2105 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2106 } else {
2107 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2108 }
François Gaffie11d30102018-11-02 16:09:09 +01002109 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002110 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002111 }
2112 }
Eric Laurente552edb2014-03-10 17:42:56 -07002113
François Gaffiec005e562018-11-06 15:04:49 +01002114 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002115 selectOutputForMusicEffects();
2116 }
2117
François Gaffie1c878552018-11-22 16:53:21 +01002118 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002119 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002120 if (devices.isEmpty()) {
2121 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002122 }
François Gaffiec005e562018-11-06 15:04:49 +01002123 bool shouldWait =
2124 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2125 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2126 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002127 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002128 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002129 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002130 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002131 // An output has a shared device if
2132 // - managed by the same hw module
2133 // - supports the currently selected device
2134 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002135 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002136
Eric Laurent77305a62016-07-25 16:39:22 -07002137 // force a device change if any other output is:
2138 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002139 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002140 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002141 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002142 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002143 // change the device currently selected by the other output.
2144 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002145 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002146 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002147 force = true;
2148 }
2149 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002150 // a notification so that audio focus effect can propagate, or that a mute/unmute
2151 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002152 const uint32_t latencyMs = desc->latency();
2153 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2154
2155 if (shouldWait && isActive && (waitMs < latencyMs)) {
2156 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002157 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002158
2159 // Require mute check if another output is on a shared device
2160 // and currently active to have proper drain and avoid pops.
2161 // Note restoring AudioTracks onto this output needs to invoke
2162 // a volume ramp if there is no mute.
2163 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002164 }
2165 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002166
2167 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002168 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002169
Eric Laurente552edb2014-03-10 17:42:56 -07002170 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002171 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002172 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002173 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002174 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002175 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002176 outputDesc->useHwGain() /*force*/)) {
2177 // request AudioService to reinitialize the volume curves asynchronously
2178 ALOGE("checkAndSetVolume failed, requesting volume range init");
2179 mpClientInterface->onVolumeRangeInitRequest();
2180 };
Eric Laurente552edb2014-03-10 17:42:56 -07002181
2182 // update the outputs if starting an output with a stream that can affect notification
2183 // routing
2184 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002185
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002186 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002187 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002188 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2189 }
Eric Laurentdc462862016-07-19 12:29:53 -07002190
2191 if (waitMs > muteWaitMs) {
2192 *delayMs = waitMs - muteWaitMs;
2193 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002194
2195 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2196 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2197 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2198 // change occurs after the MixerThread starts and causes a stream volume
2199 // glitch.
2200 //
2201 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002202 }
Eric Laurentdc462862016-07-19 12:29:53 -07002203
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002204 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002205 mEngine->getForceUse(
2206 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002207 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002208 }
2209
Eric Laurent97ac8712018-07-27 18:59:02 -07002210 // Automatically enable the remote submix input when output is started on a re routing mix
2211 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002212 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2213 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002214 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2215 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2216 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002217 "remote-submix",
2218 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002219 }
2220
Eric Laurent96d1dda2022-03-14 17:14:19 +01002221 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2222
Eric Laurente552edb2014-03-10 17:42:56 -07002223 return NO_ERROR;
2224}
2225
Eric Laurent96d1dda2022-03-14 17:14:19 +01002226void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2227 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2228 bool isUnicastActive = isLeUnicastActive();
2229
2230 if (wasUnicastActive != isUnicastActive) {
2231 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2232 for (size_t i = 0; i < mOutputs.size(); i++) {
2233 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2234 if (desc != ignoredOutput && desc->isActive()
2235 && ((isUnicastActive &&
2236 !desc->devices().
2237 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2238 || (wasUnicastActive &&
2239 !desc->devices().getDevicesFromTypes(
2240 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2241 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2242 bool force = desc->devices() != newDevices;
2243 setOutputDevices(desc, newDevices, force, delayMs);
2244 // re-apply device specific volume if not done by setOutputDevice()
2245 if (!force) {
2246 applyStreamVolumes(desc, newDevices.types(), delayMs);
2247 }
2248 }
2249 }
2250 }
2251}
2252
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002254{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002255 ALOGV("%s portId %d", __FUNCTION__, portId);
2256
2257 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2258 if (outputDesc == 0) {
2259 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002260 return BAD_VALUE;
2261 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002262 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002263
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 ALOGV("stopOutput() output %d, stream %d, session %d",
2265 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002266
Eric Laurent97ac8712018-07-27 18:59:02 -07002267 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002268
Eric Laurent733ce942017-12-07 12:18:25 -08002269 if (status == NO_ERROR ) {
2270 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002271 }
2272 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002273}
2274
Eric Laurent97ac8712018-07-27 18:59:02 -07002275status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2276 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002277{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002278 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002279 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002280 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002281 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002282
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002283 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2284
François Gaffie1c878552018-11-22 16:53:21 +01002285 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2286 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002287 // Automatically disable the remote submix input when output is stopped on a
2288 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002289 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002290 if (isSingleDeviceType(
2291 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002292 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002293 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002294 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2295 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002296 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002297 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002298 }
2299 }
2300 bool forceDeviceUpdate = false;
2301 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002302 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 forceDeviceUpdate = true;
2304 }
2305
Eric Laurente552edb2014-03-10 17:42:56 -07002306 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002307 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002308
Eric Laurente552edb2014-03-10 17:42:56 -07002309 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002310 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002311 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002312 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002313
2314 // If the routing does not change, if an output is routed on a device using HwGain
2315 // (aka setAudioPortConfig) and there are still active clients following different
2316 // volume group(s), force reapply volume
2317 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2318 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2319
Eric Laurente552edb2014-03-10 17:42:56 -07002320 // delay the device switch by twice the latency because stopOutput() is executed when
2321 // the track stop() command is received and at that time the audio track buffer can
2322 // still contain data that needs to be drained. The latency only covers the audio HAL
2323 // and kernel buffers. Also the latency does not always include additional delay in the
2324 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002325 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2326 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002327
2328 // force restoring the device selection on other active outputs if it differs from the
2329 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002330 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002331 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002332 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002333 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002334 desc->isActive() &&
2335 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002336 (newDevices != desc->devices())) {
2337 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2338 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002339
François Gaffie11d30102018-11-02 16:09:09 +01002340 setOutputDevices(desc, newDevices2, force, delayMs);
2341
Eric Laurent57de36c2016-09-28 16:59:11 -07002342 // re-apply device specific volume if not done by setOutputDevice()
2343 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002344 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002345 }
Eric Laurente552edb2014-03-10 17:42:56 -07002346 }
2347 }
2348 // update the outputs if stopping one with a stream that can affect notification routing
2349 handleNotificationRoutingForStream(stream);
2350 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002351
2352 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2353 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002354 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002355 }
2356
François Gaffiec005e562018-11-06 15:04:49 +01002357 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002358 selectOutputForMusicEffects();
2359 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002360
2361 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2362
Eric Laurente552edb2014-03-10 17:42:56 -07002363 return NO_ERROR;
2364 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002365 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002366 return INVALID_OPERATION;
2367 }
2368}
2369
jiabinbce0c1d2020-10-05 11:20:18 -07002370bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002371{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002372 ALOGV("%s portId %d", __FUNCTION__, portId);
2373
2374 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2375 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002376 // If an output descriptor is closed due to a device routing change,
2377 // then there are race conditions with releaseOutput from tracks
2378 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2379 // destroyed shortly thereafter.
2380 //
2381 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002382 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002383 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002384 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002385
2386 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002387
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302388 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2389 if (outputDesc->isClientActive(client)) {
2390 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2391 stopOutput(portId);
2392 }
2393
Eric Laurent8fc147b2018-07-22 19:13:55 -07002394 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2395 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002396 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002397 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002398 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002399 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002400 if (--outputDesc->mDirectOpenCount == 0) {
2401 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002402 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002403 }
2404 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302405
Andy Hung39efb7a2018-09-26 15:39:28 -07002406 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002407 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2408 // The output is pending reopened to query dynamic profiles and
2409 // there is no active clients
2410 closeOutput(outputDesc->mIoHandle);
2411 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2412 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2413 if (newOutputDesc == nullptr) {
2414 ALOGE("%s failed to open output", __func__);
2415 }
2416 return true;
2417 }
2418 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002419}
2420
Eric Laurentcaf7f482014-11-25 17:50:47 -08002421status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2422 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002423 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002424 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002425 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002426 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002427 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002428 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002429 input_type_t *inputType,
2430 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002431{
François Gaffiec005e562018-11-06 15:04:49 +01002432 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002433 "flags %#x attributes=%s requested device ID %d",
2434 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2435 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002436
Eric Laurentad2e7b92017-09-14 20:06:42 -07002437 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002438 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002439 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002440 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002441 sp<AudioInputDescriptor> inputDesc;
2442 sp<RecordClientDescriptor> clientDesc;
2443 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002444 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002445 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002446
2447 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2448 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2449 return INVALID_OPERATION;
2450 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002451
Francois Gaffie716e1432019-01-14 16:58:59 +01002452 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2453 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002454 }
2455
Paul McLean466dc8e2015-04-17 13:15:36 -06002456 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002457 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002458 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002459
Eric Laurentad2e7b92017-09-14 20:06:42 -07002460 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2461 // possible
2462 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2463 *input != AUDIO_IO_HANDLE_NONE) {
2464 ssize_t index = mInputs.indexOfKey(*input);
2465 if (index < 0) {
2466 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2467 status = BAD_VALUE;
2468 goto error;
2469 }
2470 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002471 RecordClientVector clients = inputDesc->getClientsForSession(session);
2472 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002473 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2474 status = BAD_VALUE;
2475 goto error;
2476 }
2477 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2478 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002479 // corresponds to a new client and is only permitted from the same UID.
2480 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002481 if (clients.size() > 1) {
2482 for (const auto& client : clients) {
2483 // The client map is ordered by key values (portId) and portIds are allocated
2484 // incrementaly. So the first client in this list is the one opened by audio flinger
2485 // when the mmap stream is created and should be ignored as it does not correspond
2486 // to an actual client
2487 if (client == *clients.cbegin()) {
2488 continue;
2489 }
2490 if (uid != client->uid() && !client->isSilenced()) {
2491 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2492 uid, client->portId(), client->uid());
2493 status = INVALID_OPERATION;
2494 goto error;
2495 }
Eric Laurent331679c2018-04-16 17:03:16 -07002496 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002497 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002498 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002499 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002500
Eric Laurentfecbceb2021-02-09 14:46:43 +01002501 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002502 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002503 }
2504
2505 *input = AUDIO_IO_HANDLE_NONE;
2506 *inputType = API_INPUT_INVALID;
2507
Francois Gaffie716e1432019-01-14 16:58:59 +01002508 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2509 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2510 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002511 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002512 ALOGW("%s could not find input mix for attr %s",
2513 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002514 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002515 }
jiabinc1de2df2019-05-07 14:26:40 -07002516 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2517 String8(attr->tags + strlen("addr=")),
2518 AUDIO_FORMAT_DEFAULT);
2519 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002520 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002521 __func__, attributes.source, attributes.tags);
2522 status = BAD_VALUE;
2523 goto error;
2524 }
2525
Kevin Rocard25f9b052019-02-27 15:08:54 -08002526 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2527 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2528 } else {
2529 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2530 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002532 if (explicitRoutingDevice != nullptr) {
2533 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002535 // Prevent from storing invalid requested device id in clients
2536 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002537 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002538 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2539 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 }
François Gaffie11d30102018-11-02 16:09:09 +01002541 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002542 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002543 status = BAD_VALUE;
2544 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002545 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002546 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2547 *inputType = API_INPUT_MIX_CAPTURE;
2548 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002549 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2550 // there is an external policy, but this input is attached to a mix of recorders,
2551 // meaning it receives audio injected into the framework, so the recorder doesn't
2552 // know about it and is therefore considered "legacy"
2553 *inputType = API_INPUT_LEGACY;
2554 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002555 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002556 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002557 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002558 } else {
2559 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002560 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002561
Eric Laurent599c7582015-12-07 18:05:55 -08002562 }
2563
François Gaffiec005e562018-11-06 15:04:49 +01002564 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002565 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002566 status = INVALID_OPERATION;
2567 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002568 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002569
Eric Laurent8f42ea12018-08-08 09:08:25 -07002570exit:
2571
François Gaffiec005e562018-11-06 15:04:49 +01002572 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2573 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002574
Francois Gaffie716e1432019-01-14 16:58:59 +01002575 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002576 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002577 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578
Mikhail Naganov2996f672019-04-18 12:29:59 -07002579 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002580 requestedDeviceId, attributes.source, flags,
2581 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002582 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002583 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002584
2585 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2586 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002587
Eric Laurent599c7582015-12-07 18:05:55 -08002588 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002589
2590error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002591 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002592}
2593
2594
François Gaffie11d30102018-11-02 16:09:09 +01002595audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002596 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002597 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002598 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002599 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002600 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002601{
2602 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002603 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002604 bool isSoundTrigger = false;
2605
François Gaffiec005e562018-11-06 15:04:49 +01002606 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002607 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2608 if (index >= 0) {
2609 input = mSoundTriggerSessions.valueFor(session);
2610 isSoundTrigger = true;
2611 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2612 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2613 } else {
2614 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002615 }
François Gaffiec005e562018-11-06 15:04:49 +01002616 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002617 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002618 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002619 }
2620
Carter Hsua3abb402021-10-26 11:11:20 +08002621 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2622 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2623 }
2624
Andy Hungf129b032015-04-07 13:45:50 -07002625 // find a compatible input profile (not necessarily identical in parameters)
2626 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002627 // sampling rate and flags may be updated by getInputProfile
2628 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2629 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002630 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002631 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002632 audio_input_flags_t profileFlags = flags;
2633 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002634 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002635 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002636 profileFlags);
2637 if (profile != 0) {
2638 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002639 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2640 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002641 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002642 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2643 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002644 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002645 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002646 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002647 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002648 }
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002650 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002651 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002652 if (samplingRate == 0) {
2653 samplingRate = profileSamplingRate;
2654 }
Eric Laurente552edb2014-03-10 17:42:56 -07002655
Eric Laurent322b4d22015-04-03 15:57:54 -07002656 if (profile->getModuleHandle() == 0) {
2657 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002658 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002659 }
2660
Eric Laurentec376dc2021-04-08 20:41:22 +02002661 // Reuse an already opened input if a client with the same session ID already exists
2662 // on that input
2663 for (size_t i = 0; i < mInputs.size(); i++) {
2664 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2665 if (desc->mProfile != profile) {
2666 continue;
2667 }
2668 RecordClientVector clients = desc->clientsList();
2669 for (const auto &client : clients) {
2670 if (session == client->session()) {
2671 return desc->mIoHandle;
2672 }
2673 }
2674 }
2675
Eric Laurent3974e3b2017-12-07 17:58:43 -08002676 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002677 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002678 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002679 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002680 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002681 continue;
2682 }
2683 // if sound trigger, reuse input if used by other sound trigger on same session
2684 // else
2685 // reuse input if active client app is not in IDLE state
2686 //
2687 RecordClientVector clients = desc->clientsList();
2688 bool doClose = false;
2689 for (const auto& client : clients) {
2690 if (isSoundTrigger != client->isSoundTrigger()) {
2691 continue;
2692 }
2693 if (client->isSoundTrigger()) {
2694 if (session == client->session()) {
2695 return desc->mIoHandle;
2696 }
2697 continue;
2698 }
2699 if (client->active() && client->appState() != APP_STATE_IDLE) {
2700 return desc->mIoHandle;
2701 }
2702 doClose = true;
2703 }
2704 if (doClose) {
2705 closeInput(desc->mIoHandle);
2706 } else {
2707 i++;
2708 }
2709 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002710 }
2711
Eric Laurentfe231122017-11-17 17:48:06 -08002712 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002713
Eric Laurentfe231122017-11-17 17:48:06 -08002714 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2715 lConfig.sample_rate = profileSamplingRate;
2716 lConfig.channel_mask = profileChannelMask;
2717 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002718
François Gaffie11d30102018-11-02 16:09:09 +01002719 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002720
2721 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002722 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002723 (profileSamplingRate != lConfig.sample_rate) ||
2724 !audio_formats_match(profileFormat, lConfig.format) ||
2725 (profileChannelMask != lConfig.channel_mask)) {
2726 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002727 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002728 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002729 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002730 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002731 }
Eric Laurent599c7582015-12-07 18:05:55 -08002732 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002733 }
2734
Eric Laurentc722f302014-12-10 11:21:49 -08002735 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002736
Eric Laurent599c7582015-12-07 18:05:55 -08002737 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002738 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002739
Eric Laurent599c7582015-12-07 18:05:55 -08002740 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002741}
2742
Eric Laurent4eb58f12018-12-07 16:41:02 -08002743status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002744{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002745 ALOGV("%s portId %d", __FUNCTION__, portId);
2746
2747 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2748 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002750 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002751 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002752 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002753 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002754 if (client->active()) {
2755 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2756 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002757 }
2758
Eric Laurent8f42ea12018-08-08 09:08:25 -07002759 audio_session_t session = client->session();
2760
Eric Laurent4eb58f12018-12-07 16:41:02 -08002761 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002762
Eric Laurent4eb58f12018-12-07 16:41:02 -08002763 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002764
Eric Laurent4eb58f12018-12-07 16:41:02 -08002765 status_t status = inputDesc->start();
2766 if (status != NO_ERROR) {
2767 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002768 }
Eric Laurente552edb2014-03-10 17:42:56 -07002769
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002770 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002771 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002772 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002773
Eric Laurent8f42ea12018-08-08 09:08:25 -07002774 // indicate active capture to sound trigger service if starting capture from a mic on
2775 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002776 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002777 if (device != nullptr) {
2778 status = setInputDevice(input, device, true /* force */);
2779 } else {
2780 ALOGW("%s no new input device can be found for descriptor %d",
2781 __FUNCTION__, inputDesc->getId());
2782 status = BAD_VALUE;
2783 }
Eric Laurente552edb2014-03-10 17:42:56 -07002784
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002785 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002786 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002787 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002788 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002789 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2790 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002791 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002792 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002793
François Gaffie11d30102018-11-02 16:09:09 +01002794 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2795 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002796 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002797 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002798 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002799
Eric Laurent8f42ea12018-08-08 09:08:25 -07002800 // automatically enable the remote submix output when input is started if not
2801 // used by a policy mix of type MIX_TYPE_RECORDERS
2802 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002803 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002804 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002805 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002806 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002807 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2808 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002809 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002810 if (address != "") {
2811 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2812 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002813 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002814 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002815 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002816 } else if (status != NO_ERROR) {
2817 // Restore client activity state.
2818 inputDesc->setClientActive(client, false);
2819 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002820 }
2821
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002822 ALOGV("%s input %d source = %d status = %d exit",
2823 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002824
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002825 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002826}
2827
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002829{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830 ALOGV("%s portId %d", __FUNCTION__, portId);
2831
2832 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2833 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002834 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002835 return BAD_VALUE;
2836 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002837 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002838 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002839 if (!client->active()) {
2840 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002841 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002842 }
Carter Hsue6139d52021-07-08 10:30:20 +08002843 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002844 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002845
Eric Laurent8f42ea12018-08-08 09:08:25 -07002846 inputDesc->stop();
2847 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002848 auto current_source = inputDesc->source();
2849 setInputDevice(input, getNewInputDevice(inputDesc),
2850 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002851 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002852 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002853 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002854 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002855 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2856 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002857 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002858 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859
2860 // automatically disable the remote submix output when input is stopped if not
2861 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002862 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002863 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002864 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002866 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2867 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002868 }
2869 if (address != "") {
2870 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2871 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002872 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 }
2874 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875 resetInputDevice(input);
2876
2877 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2878 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002879 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2880 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002882 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883 }
2884 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002885 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002886 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002887}
2888
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002890{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002891 ALOGV("%s portId %d", __FUNCTION__, portId);
2892
2893 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2894 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002895 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002896 return;
2897 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002898 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002899 audio_io_handle_t input = inputDesc->mIoHandle;
2900
Eric Laurent8f42ea12018-08-08 09:08:25 -07002901 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002902
Andy Hung39efb7a2018-09-26 15:39:28 -07002903 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002904
Andy Hung39efb7a2018-09-26 15:39:28 -07002905 if (inputDesc->getClientCount() > 0) {
2906 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002907 return;
2908 }
2909
Eric Laurent05b90f82014-08-27 15:32:29 -07002910 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002911 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002912 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002913}
2914
Eric Laurent8f42ea12018-08-08 09:08:25 -07002915void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002916{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002917 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002918
2919 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002920 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002921 }
2922}
2923
Eric Laurent8f42ea12018-08-08 09:08:25 -07002924void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2925{
2926 stopInput(portId);
2927 releaseInput(portId);
2928}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002929
Eric Laurent0dd51852019-04-19 18:18:58 -07002930void AudioPolicyManager::checkCloseInputs() {
2931 // After connecting or disconnecting an input device, close input if:
2932 // - it has no client (was just opened to check profile) OR
2933 // - none of its supported devices are connected anymore OR
2934 // - one of its clients cannot be routed to one of its supported
2935 // devices anymore. Otherwise update device selection
2936 std::vector<audio_io_handle_t> inputsToClose;
2937 for (size_t i = 0; i < mInputs.size(); i++) {
2938 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2939 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002940 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002941 inputsToClose.push_back(mInputs.keyAt(i));
2942 } else {
2943 bool close = false;
2944 for (const auto& client : input->clientsList()) {
2945 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002946 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002947 if (!input->supportedDevices().contains(device)) {
2948 close = true;
2949 break;
2950 }
2951 }
2952 if (close) {
2953 inputsToClose.push_back(mInputs.keyAt(i));
2954 } else {
2955 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2956 }
2957 }
2958 }
2959
2960 for (const audio_io_handle_t handle : inputsToClose) {
2961 ALOGV("%s closing input %d", __func__, handle);
2962 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002963 }
Eric Laurentd4692962014-05-05 18:13:44 -07002964}
2965
François Gaffie251c7f02018-11-07 10:41:08 +01002966void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002967{
2968 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002969 if (indexMin < 0 || indexMax < 0) {
2970 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2971 return;
2972 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002973 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002974
2975 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002976 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2977 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002978 continue;
2979 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002980 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002981 }
Eric Laurente552edb2014-03-10 17:42:56 -07002982}
2983
Eric Laurente0720872014-03-11 09:30:41 -07002984status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002985 int index,
2986 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002987{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002988 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002989 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2990 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2991 return NO_ERROR;
2992 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002993 ALOGV("%s: stream %s attributes=%s", __func__,
2994 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002995 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002996}
2997
Eric Laurente0720872014-03-11 09:30:41 -07002998status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002999 int *index,
3000 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003001{
François Gaffiec005e562018-11-06 15:04:49 +01003002 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3003 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003004 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003005 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003006 deviceTypes = mEngine->getOutputDevicesForStream(
3007 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003008 }
jiabin9a3361e2019-10-01 09:38:30 -07003009 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003010}
3011
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003012status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003013 int index,
3014 audio_devices_t device)
3015{
3016 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003017 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3018 if (group == VOLUME_GROUP_NONE) {
3019 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003020 return BAD_VALUE;
3021 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003022 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003023 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003024 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003025 VolumeSource vs = toVolumeSource(group);
3026 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3027
3028 status = setVolumeCurveIndex(index, device, curves);
3029 if (status != NO_ERROR) {
3030 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3031 return status;
3032 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003033
jiabin9a3361e2019-10-01 09:38:30 -07003034 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003035 auto curCurvAttrs = curves.getAttributes();
3036 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3037 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003038 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003039 } else if (!curves.getStreamTypes().empty()) {
3040 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003041 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003042 } else {
3043 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3044 return BAD_VALUE;
3045 }
jiabin9a3361e2019-10-01 09:38:30 -07003046 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3047 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003048
François Gaffiecfe17322018-11-07 13:41:29 +01003049 // update volume on all outputs and streams matching the following:
3050 // - The requested stream (or a stream matching for volume control) is active on the output
3051 // - The device (or devices) selected by the engine for this stream includes
3052 // the requested device
3053 // - For non default requested device, currently selected device on the output is either the
3054 // requested device or one of the devices selected by the engine for this stream
3055 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3056 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003057 for (size_t i = 0; i < mOutputs.size(); i++) {
3058 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003059 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003060
jiabin9a3361e2019-10-01 09:38:30 -07003061 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3062 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003063 }
François Gaffieed91f582020-01-31 10:35:37 +01003064 if (!(desc->isActive(vs) || isInCall())) {
3065 continue;
3066 }
3067 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3068 curDevices.find(device) == curDevices.end()) {
3069 continue;
3070 }
3071 bool applyVolume = false;
3072 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3073 curSrcDevices.insert(device);
3074 applyVolume = (curSrcDevices.find(
3075 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3076 } else {
3077 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3078 }
3079 if (!applyVolume) {
3080 continue; // next output
3081 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003082 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3083 // If a higher priority strategy is active, and the output is routed to a device with a
3084 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003085 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003086 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003087 // If the volume source is active with higher priority source, ensure at least Sw Muted
3088 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003089 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3090 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3091 false /*preferredDevice*/);
3092 if (activeClients.empty()) {
3093 continue;
3094 }
3095 bool isPreempted = false;
3096 bool isHigherPriority = productStrategy < strategy;
3097 for (const auto &client : activeClients) {
3098 if (isHigherPriority && (client->volumeSource() != vs)) {
3099 ALOGV("%s: Strategy=%d (\nrequester:\n"
3100 " group %d, volumeGroup=%d attributes=%s)\n"
3101 " higher priority source active:\n"
3102 " volumeGroup=%d attributes=%s) \n"
3103 " on output %zu, bailing out", __func__, productStrategy,
3104 group, group, toString(attributes).c_str(),
3105 client->volumeSource(), toString(client->attributes()).c_str(), i);
3106 applyVolume = false;
3107 isPreempted = true;
3108 break;
3109 }
3110 // However, continue for loop to ensure no higher prio clients running on output
3111 if (client->volumeSource() == vs) {
3112 applyVolume = true;
3113 }
3114 }
3115 if (isPreempted || applyVolume) {
3116 break;
3117 }
3118 }
3119 if (!applyVolume) {
3120 continue; // next output
3121 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003122 }
François Gaffieed91f582020-01-31 10:35:37 +01003123 //FIXME: workaround for truncated touch sounds
3124 // delayed volume change for system stream to be removed when the problem is
3125 // handled by system UI
3126 status_t volStatus = checkAndSetVolume(
3127 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003128 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003129 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3130 if (volStatus != NO_ERROR) {
3131 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003132 }
3133 }
François Gaffiecfe17322018-11-07 13:41:29 +01003134 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3135 return status;
3136}
3137
François Gaffieaaac0fd2018-11-22 17:56:39 +01003138status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003139 audio_devices_t device,
3140 IVolumeCurves &volumeCurves)
3141{
3142 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3143 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003144 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3145 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003146 (index > volumeCurves.getVolumeIndexMax())) {
3147 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3148 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3149 return BAD_VALUE;
3150 }
3151 if (!audio_is_output_device(device)) {
3152 return BAD_VALUE;
3153 }
3154
3155 // Force max volume if stream cannot be muted
3156 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3157
François Gaffieaaac0fd2018-11-22 17:56:39 +01003158 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003159 volumeCurves.addCurrentVolumeIndex(device, index);
3160 return NO_ERROR;
3161}
3162
3163status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3164 int &index,
3165 audio_devices_t device)
3166{
3167 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3168 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003169 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003170 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003171 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003172 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003173 }
jiabin9a3361e2019-10-01 09:38:30 -07003174 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003175}
3176
3177status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3178 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003179 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003180{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003181 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003182 return BAD_VALUE;
3183 }
jiabin9a3361e2019-10-01 09:38:30 -07003184 index = curves.getVolumeIndex(deviceTypes);
3185 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003186 return NO_ERROR;
3187}
3188
3189status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3190 int &index)
3191{
3192 index = getVolumeCurves(attr).getVolumeIndexMin();
3193 return NO_ERROR;
3194}
3195
3196status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3197 int &index)
3198{
3199 index = getVolumeCurves(attr).getVolumeIndexMax();
3200 return NO_ERROR;
3201}
3202
Eric Laurent36829f92017-04-07 19:04:42 -07003203audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003204{
3205 // select one output among several suitable for global effects.
3206 // The priority is as follows:
3207 // 1: An offloaded output. If the effect ends up not being offloadable,
3208 // AudioFlinger will invalidate the track and the offloaded output
3209 // will be closed causing the effect to be moved to a PCM output.
3210 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003211 // 3: The primary output
3212 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003213
François Gaffiec005e562018-11-06 15:04:49 +01003214 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3215 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003216 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003217
Eric Laurent36829f92017-04-07 19:04:42 -07003218 if (outputs.size() == 0) {
3219 return AUDIO_IO_HANDLE_NONE;
3220 }
Eric Laurente552edb2014-03-10 17:42:56 -07003221
Eric Laurent36829f92017-04-07 19:04:42 -07003222 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3223 bool activeOnly = true;
3224
3225 while (output == AUDIO_IO_HANDLE_NONE) {
3226 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3227 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3228 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3229
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003230 for (audio_io_handle_t output : outputs) {
3231 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003232 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003233 continue;
3234 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003235 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3236 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003237 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003238 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003239 }
3240 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003241 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003242 }
3243 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003244 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003245 }
3246 }
3247 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3248 output = outputOffloaded;
3249 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3250 output = outputDeepBuffer;
3251 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3252 output = outputPrimary;
3253 } else {
3254 output = outputs[0];
3255 }
3256 activeOnly = false;
3257 }
3258
3259 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003260 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003261 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3262 mMusicEffectOutput = output;
3263 }
3264
3265 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003266 return output;
3267}
3268
Eric Laurent36829f92017-04-07 19:04:42 -07003269audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3270{
3271 return selectOutputForMusicEffects();
3272}
3273
Eric Laurente0720872014-03-11 09:30:41 -07003274status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003275 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003276 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003277 int session,
3278 int id)
3279{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003280 if (session != AUDIO_SESSION_DEVICE) {
3281 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003282 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003283 index = mInputs.indexOfKey(io);
3284 if (index < 0) {
3285 ALOGW("registerEffect() unknown io %d", io);
3286 return INVALID_OPERATION;
3287 }
Eric Laurente552edb2014-03-10 17:42:56 -07003288 }
3289 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003290 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3291 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3292 || strategy == PRODUCT_STRATEGY_NONE));
3293 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003294}
3295
Eric Laurentc241b0d2018-11-28 09:08:49 -08003296status_t AudioPolicyManager::unregisterEffect(int id)
3297{
3298 if (mEffects.getEffect(id) == nullptr) {
3299 return INVALID_OPERATION;
3300 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003301 if (mEffects.isEffectEnabled(id)) {
3302 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3303 setEffectEnabled(id, false);
3304 }
3305 return mEffects.unregisterEffect(id);
3306}
3307
3308status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3309{
3310 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3311 if (effect == nullptr) {
3312 return INVALID_OPERATION;
3313 }
3314
3315 status_t status = mEffects.setEffectEnabled(id, enabled);
3316 if (status == NO_ERROR) {
3317 mInputs.trackEffectEnabled(effect, enabled);
3318 }
3319 return status;
3320}
3321
Eric Laurent6c796322019-04-09 14:13:17 -07003322
3323status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3324{
3325 mEffects.moveEffects(ids, io);
3326 return NO_ERROR;
3327}
3328
Eric Laurentc75307b2015-03-17 15:29:32 -07003329bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3330{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003331 auto vs = toVolumeSource(stream, false);
3332 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003333}
3334
3335bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3336{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003337 auto vs = toVolumeSource(stream, false);
3338 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003339}
3340
Eric Laurente0720872014-03-11 09:30:41 -07003341bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003342{
3343 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003344 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003345 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003346 return true;
3347 }
3348 }
3349 return false;
3350}
3351
Eric Laurent275e8e92014-11-30 15:14:47 -08003352// Register a list of custom mixes with their attributes and format.
3353// When a mix is registered, corresponding input and output profiles are
3354// added to the remote submix hw module. The profile contains only the
3355// parameters (sampling rate, format...) specified by the mix.
3356// The corresponding input remote submix device is also connected.
3357//
3358// When a remote submix device is connected, the address is checked to select the
3359// appropriate profile and the corresponding input or output stream is opened.
3360//
3361// When capture starts, getInputForAttr() will:
3362// - 1 look for a mix matching the address passed in attribtutes tags if any
3363// - 2 if none found, getDeviceForInputSource() will:
3364// - 2.1 look for a mix matching the attributes source
3365// - 2.2 if none found, default to device selection by policy rules
3366// At this time, the corresponding output remote submix device is also connected
3367// and active playback use cases can be transferred to this mix if needed when reconnecting
3368// after AudioTracks are invalidated
3369//
3370// When playback starts, getOutputForAttr() will:
3371// - 1 look for a mix matching the address passed in attribtutes tags if any
3372// - 2 if none found, look for a mix matching the attributes usage
3373// - 3 if none found, default to device and output selection by policy rules.
3374
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003375status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003376{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003377 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3378 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003379 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 sp<HwModule> rSubmixModule;
3381 // examine each mix's route type
3382 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003383 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003384 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3385 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3386 ALOGE("Unsupported Policy Mix %zu of %zu: "
3387 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3388 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003389 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003390 break;
3391 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003392 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3393 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003394 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003395 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3396 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003397 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003398 rSubmixModule = mHwModules.getModuleFromName(
3399 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3400 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003401 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003402 i);
3403 res = INVALID_OPERATION;
3404 break;
3405 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003406 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003407
Eric Laurent97ac8712018-07-27 18:59:02 -07003408 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003409 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003410 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003411 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003412 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3413 } else {
3414 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3415 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003416 }
François Gaffie036e1e92015-03-19 10:16:24 +01003417
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003418 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003419 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003420 res = INVALID_OPERATION;
3421 break;
3422 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003423 audio_config_t outputConfig = mix.mFormat;
3424 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003425 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3426 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003427 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3428 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003429 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003430 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003431 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003432 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003433
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003434 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003435 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3436 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3437 ALOGE("Failed to set remote submix device available, type %u, address %s",
3438 mix.mDeviceType, address.string());
3439 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003440 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003441 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3442 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003443 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003444 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003445 i, mixes.size(), type, address.string());
3446
3447 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3448 mix.mDeviceType, mix.mDeviceAddress,
3449 String8(), AUDIO_FORMAT_DEFAULT);
3450 if (device == nullptr) {
3451 res = INVALID_OPERATION;
3452 break;
3453 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003454
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003455 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003456 // First try to find an already opened output supporting the device
3457 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003458 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003459
Eric Laurentc529cf62020-04-17 18:19:10 -07003460 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003461 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003462 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3463 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003464 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003465 } else {
3466 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003468 }
3469 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003470 // If no output found, try to find a direct output profile supporting the device
3471 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3472 sp<HwModule> module = mHwModules[i];
3473 for (size_t j = 0;
3474 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3475 j++) {
3476 sp<IOProfile> profile = module->getOutputProfiles()[j];
3477 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3478 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3479 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3480 address.string());
3481 res = INVALID_OPERATION;
3482 } else {
3483 foundOutput = true;
3484 }
3485 }
3486 }
3487 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003488 if (res != NO_ERROR) {
3489 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003490 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003491 res = INVALID_OPERATION;
3492 break;
3493 } else if (!foundOutput) {
3494 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003495 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003496 res = INVALID_OPERATION;
3497 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003498 } else {
3499 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003500 }
Eric Laurentc722f302014-12-10 11:21:49 -08003501 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003502 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003503 if (res != NO_ERROR) {
3504 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003505 } else if (checkOutputs) {
3506 checkForDeviceAndOutputChanges();
3507 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003508 }
3509 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003510}
3511
3512status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3513{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003514 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003515 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003516 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003517 sp<HwModule> rSubmixModule;
3518 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003519 for (const auto& mix : mixes) {
3520 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003521
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003522 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003523 rSubmixModule = mHwModules.getModuleFromName(
3524 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3525 if (rSubmixModule == 0) {
3526 res = INVALID_OPERATION;
3527 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003528 }
3529 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003530
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003531 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003532
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003533 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003534 res = INVALID_OPERATION;
3535 continue;
3536 }
3537
Kevin Rocard04ed0462019-05-02 17:53:24 -07003538 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3539 if (getDeviceConnectionState(device, address.string()) ==
3540 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3541 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3542 address.string(), "remote-submix",
3543 AUDIO_FORMAT_DEFAULT);
3544 if (res != OK) {
3545 ALOGE("Error making RemoteSubmix device unavailable for mix "
3546 "with type %d, address %s", device, address.string());
3547 }
3548 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003549 }
jiabin5740f082019-08-19 15:08:30 -07003550 rSubmixModule->removeOutputProfile(address.c_str());
3551 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003552
Kevin Rocard153f92d2018-12-18 18:33:28 -08003553 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003554 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003555 res = INVALID_OPERATION;
3556 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003557 } else {
3558 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003559 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003561 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003562 if (res == NO_ERROR && checkOutputs) {
3563 checkForDeviceAndOutputChanges();
3564 updateCallAndOutputRouting();
3565 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003566 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003567}
3568
Mikhail Naganov100f0122018-11-29 11:22:16 -08003569void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3570{
3571 size_t i = 0;
3572 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3573 for (const auto& fmt : mManualSurroundFormats) {
3574 if (i++ != 0) dst->append(", ");
3575 std::string sfmt;
3576 FormatConverter::toString(fmt, sfmt);
3577 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3578 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3579 }
3580}
3581
Eric Laurentc529cf62020-04-17 18:19:10 -07003582// Returns true if all devices types match the predicate and are supported by one HW module
3583bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003584 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003585 std::function<bool(audio_devices_t)> predicate,
3586 const char *context) {
3587 for (size_t i = 0; i < devices.size(); i++) {
3588 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003589 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003590 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003591 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003592 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003593 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003594 return false;
3595 }
3596 }
3597 return true;
3598}
3599
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003600status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003601 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003602 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003603 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3604 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003605 }
3606 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003607 if (res != NO_ERROR) {
3608 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3609 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003610 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003611
3612 checkForDeviceAndOutputChanges();
3613 updateCallAndOutputRouting();
3614
3615 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003616}
3617
3618status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3619 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003620 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3621 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003622 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003623 __FUNCTION__, uid);
3624 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003625 }
3626
Eric Laurentc529cf62020-04-17 18:19:10 -07003627 checkForDeviceAndOutputChanges();
3628 updateCallAndOutputRouting();
3629
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003630 return res;
3631}
3632
Eric Laurent2517af32020-11-25 15:31:27 +01003633
jiabin0a488932020-08-07 17:32:40 -07003634status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3635 device_role_t role,
3636 const AudioDeviceTypeAddrVector &devices) {
3637 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3638 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003639
Eric Laurentc529cf62020-04-17 18:19:10 -07003640 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003641 return BAD_VALUE;
3642 }
jiabin0a488932020-08-07 17:32:40 -07003643 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003644 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003645 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3646 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003647 return status;
3648 }
3649
3650 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003651
3652 bool forceVolumeReeval = false;
3653 // FIXME: workaround for truncated touch sounds
3654 // to be removed when the problem is handled by system UI
3655 uint32_t delayMs = 0;
3656 if (strategy == mCommunnicationStrategy) {
3657 forceVolumeReeval = true;
3658 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3659 updateInputRouting();
3660 }
3661 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003662
3663 return NO_ERROR;
3664}
3665
3666void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3667{
3668 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003669 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003670 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003671 // Only apply special touch sound delay once
3672 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003673 }
3674 for (size_t i = 0; i < mOutputs.size(); i++) {
3675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3676 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003677 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3678 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003679 // As done in setDeviceConnectionState, we could also fix default device issue by
3680 // preventing the force re-routing in case of default dev that distinguishes on address.
3681 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003682 bool forceRouting = !newDevices.isEmpty();
3683 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3684 true /*requiresMuteCheck*/,
3685 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003686 // Only apply special touch sound delay once
3687 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003688 }
3689 if (forceVolumeReeval && !newDevices.isEmpty()) {
3690 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3691 }
3692 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003693 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003694}
3695
Eric Laurent2517af32020-11-25 15:31:27 +01003696void AudioPolicyManager::updateInputRouting() {
3697 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303698 // Skip for hotword recording as the input device switch
3699 // is handled within sound trigger HAL
3700 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3701 continue;
3702 }
Eric Laurent2517af32020-11-25 15:31:27 +01003703 auto newDevice = getNewInputDevice(activeDesc);
3704 // Force new input selection if the new device can not be reached via current input
3705 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3706 setInputDevice(activeDesc->mIoHandle, newDevice);
3707 } else {
3708 closeInput(activeDesc->mIoHandle);
3709 }
3710 }
3711}
3712
jiabin0a488932020-08-07 17:32:40 -07003713status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3714 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003715{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003716 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003717
jiabin0a488932020-08-07 17:32:40 -07003718 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003719 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003720 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3721 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003722 return status;
3723 }
3724
3725 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003726
3727 bool forceVolumeReeval = false;
3728 // FIXME: workaround for truncated touch sounds
3729 // to be removed when the problem is handled by system UI
3730 uint32_t delayMs = 0;
3731 if (strategy == mCommunnicationStrategy) {
3732 forceVolumeReeval = true;
3733 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3734 updateInputRouting();
3735 }
3736 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003737
3738 return NO_ERROR;
3739}
3740
jiabin0a488932020-08-07 17:32:40 -07003741status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3742 device_role_t role,
3743 AudioDeviceTypeAddrVector &devices) {
3744 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003745}
3746
Jiabin Huang3b98d322020-09-03 17:54:16 +00003747status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3748 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3749 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3750 dumpAudioDeviceTypeAddrVector(devices).c_str());
3751
Mikhail Naganov55773032020-10-01 15:08:13 -07003752 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003753 return BAD_VALUE;
3754 }
3755 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3756 ALOGW_IF(status != NO_ERROR,
3757 "Engine could not set preferred devices %s for audio source %d role %d",
3758 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3759
3760 return status;
3761}
3762
3763status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3764 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3765 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3766 dumpAudioDeviceTypeAddrVector(devices).c_str());
3767
Mikhail Naganov55773032020-10-01 15:08:13 -07003768 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003769 return BAD_VALUE;
3770 }
3771 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3772 ALOGW_IF(status != NO_ERROR,
3773 "Engine could not add preferred devices %s for audio source %d role %d",
3774 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3775
Eric Laurent2517af32020-11-25 15:31:27 +01003776 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003777 return status;
3778}
3779
3780status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3781 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3782{
3783 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3784 dumpAudioDeviceTypeAddrVector(devices).c_str());
3785
Mikhail Naganov55773032020-10-01 15:08:13 -07003786 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003787 return BAD_VALUE;
3788 }
3789
3790 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3791 audioSource, role, devices);
3792 ALOGW_IF(status != NO_ERROR,
3793 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3794
Eric Laurent2517af32020-11-25 15:31:27 +01003795 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003796 return status;
3797}
3798
3799status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3800 device_role_t role) {
3801 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3802
3803 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3804 ALOGW_IF(status != NO_ERROR,
3805 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3806
Eric Laurent2517af32020-11-25 15:31:27 +01003807 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003808 return status;
3809}
3810
3811status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3812 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3813 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3814}
3815
Oscar Azucena90e77632019-11-27 17:12:28 -08003816status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003817 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003818 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003819 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3820 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003821 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003822 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3823 if (status != NO_ERROR) {
3824 ALOGE("%s() could not set device affinity for userId %d",
3825 __FUNCTION__, userId);
3826 return status;
3827 }
3828
3829 // reevaluate outputs for all devices
3830 checkForDeviceAndOutputChanges();
3831 updateCallAndOutputRouting();
3832
3833 return NO_ERROR;
3834}
3835
3836status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003837 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003838 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3839 if (status != NO_ERROR) {
3840 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3841 __FUNCTION__, userId);
3842 return status;
3843 }
3844
3845 // reevaluate outputs for all devices
3846 checkForDeviceAndOutputChanges();
3847 updateCallAndOutputRouting();
3848
3849 return NO_ERROR;
3850}
3851
Andy Hungc29d82b2018-10-05 12:23:17 -07003852void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003853{
Andy Hungc29d82b2018-10-05 12:23:17 -07003854 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003855 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003856 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003857 std::string stateLiteral;
3858 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003859 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003860 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3861 "communications", "media", "record", "dock", "system",
3862 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3863 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3864 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003865 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3866 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3867 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3868 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3869 dst->append(" (MANUAL: ");
3870 dumpManualSurroundFormats(dst);
3871 dst->append(")");
3872 }
3873 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003874 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003875 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3876 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003877 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003878 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003879
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003880 dst->append("\n");
3881 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3882 dst->append("\n");
3883 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003884 mHwModulesAll.dump(dst);
3885 mOutputs.dump(dst);
3886 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003887 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003888 mAudioPatches.dump(dst);
3889 mPolicyMixes.dump(dst);
3890 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003891
Kevin Rocardb99cc752019-03-21 20:52:24 -07003892 dst->appendFormat(" AllowedCapturePolicies:\n");
3893 for (auto& policy : mAllowedCapturePolicies) {
3894 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3895 }
3896
François Gaffiec005e562018-11-06 15:04:49 +01003897 dst->appendFormat("\nPolicy Engine dump:\n");
3898 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003899}
3900
3901status_t AudioPolicyManager::dump(int fd)
3902{
3903 String8 result;
3904 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003905 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003906 return NO_ERROR;
3907}
3908
Kevin Rocardb99cc752019-03-21 20:52:24 -07003909status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3910{
3911 mAllowedCapturePolicies[uid] = capturePolicy;
3912 return NO_ERROR;
3913}
3914
Eric Laurente552edb2014-03-10 17:42:56 -07003915// This function checks for the parameters which can be offloaded.
3916// This can be enhanced depending on the capability of the DSP and policy
3917// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003918audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003919{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003920 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003921 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003922 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003923 offloadInfo.format,
3924 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3925 offloadInfo.has_video);
3926
jiabin2b9d5a12021-12-10 01:06:29 +00003927 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003928 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003929 }
3930
3931 // See if there is a profile to support this.
3932 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003933 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003934 offloadInfo.sample_rate,
3935 offloadInfo.format,
3936 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003937 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3938 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003939 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3940 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3941 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003942 if (profile == nullptr) {
3943 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3944 }
3945 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3946 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3947 }
3948 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003949}
3950
Michael Chana94fbb22018-04-24 14:31:19 +10003951bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3952 const audio_attributes_t& attributes) {
3953 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003954 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003955 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3956 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003957 config.sample_rate,
3958 config.format,
3959 config.channel_mask,
3960 output_flags,
3961 true /* directOnly */);
3962 ALOGV("%s() profile %sfound with name: %s, "
3963 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3964 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003965 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003966 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003967
3968 // also try the MSD module if compatible profile not found
3969 if (profile == nullptr) {
3970 profile = getMsdProfileForOutput(outputDevices,
3971 config.sample_rate,
3972 config.format,
3973 config.channel_mask,
3974 output_flags,
3975 true /* directOnly */);
3976 ALOGV("%s() MSD profile %sfound with name: %s, "
3977 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3978 __FUNCTION__, profile != 0 ? "" : "NOT ",
3979 (profile != 0 ? profile->getTagName().c_str() : "null"),
3980 config.sample_rate, config.format, config.channel_mask, output_flags);
3981 }
3982 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003983}
3984
jiabin2b9d5a12021-12-10 01:06:29 +00003985bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3986 bool durationIgnored) {
3987 if (mMasterMono) {
3988 return false; // no offloading if mono is set.
3989 }
3990
3991 // Check if offload has been disabled
3992 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3993 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3994 return false;
3995 }
3996
3997 // Check if stream type is music, then only allow offload as of now.
3998 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3999 {
4000 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4001 return false;
4002 }
4003
4004 //TODO: enable audio offloading with video when ready
4005 const bool allowOffloadWithVideo =
4006 property_get_bool("audio.offload.video", false /* default_value */);
4007 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4008 ALOGV("%s: has_video == true, returning false", __func__);
4009 return false;
4010 }
4011
4012 //If duration is less than minimum value defined in property, return false
4013 const int min_duration_secs = property_get_int32(
4014 "audio.offload.min.duration.secs", -1 /* default_value */);
4015 if (!durationIgnored) {
4016 if (min_duration_secs >= 0) {
4017 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4018 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4019 __func__, min_duration_secs);
4020 return false;
4021 }
4022 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4023 ALOGV("%s: Offload denied by duration < default min(=%u)",
4024 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4025 return false;
4026 }
4027 }
4028
4029 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4030 // creating an offloaded track and tearing it down immediately after start when audioflinger
4031 // detects there is an active non offloadable effect.
4032 // FIXME: We should check the audio session here but we do not have it in this context.
4033 // This may prevent offloading in rare situations where effects are left active by apps
4034 // in the background.
4035 if (mEffects.isNonOffloadableEffectEnabled()) {
4036 return false;
4037 }
4038
4039 return true;
4040}
4041
4042audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4043 const audio_config_t *config) {
4044 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4045 offloadInfo.format = config->format;
4046 offloadInfo.sample_rate = config->sample_rate;
4047 offloadInfo.channel_mask = config->channel_mask;
4048 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4049 offloadInfo.has_video = false;
4050 offloadInfo.is_streaming = false;
4051 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4052
4053 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4054 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4055 audio_flags_to_audio_output_flags(attr->flags, &flags);
4056 // only retain flags that will drive compressed offload or passthrough
4057 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4058 if (offloadPossible) {
4059 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4060 }
4061 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4062
Dorin Drimusfae3c642022-03-17 18:36:30 +01004063 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004064 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004065 DeviceVector outputDevices = engineOutputDevices;
4066 // the MSD module checks for different conditions and output devices
4067 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4068 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4069 continue;
4070 }
4071 outputDevices = getMsdAudioOutDevices();
4072 }
jiabin2b9d5a12021-12-10 01:06:29 +00004073 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004074 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004075 config->sample_rate, nullptr /*updatedSamplingRate*/,
4076 config->format, nullptr /*updatedFormat*/,
4077 config->channel_mask, nullptr /*updatedChannelMask*/,
4078 flags)) {
4079 continue;
4080 }
4081 // reject profiles not corresponding to a device currently available
4082 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4083 continue;
4084 }
4085 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4086 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004087 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004088 != AUDIO_DIRECT_NOT_SUPPORTED) {
4089 // Already reports offload gapless supported. No need to report offload support.
4090 continue;
4091 }
4092 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4093 != AUDIO_OUTPUT_FLAG_NONE) {
4094 // If offload gapless is reported, no need to report offload support.
4095 directMode = (audio_direct_mode_t) ((directMode &
4096 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4097 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4098 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004099 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004100 }
4101 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004102 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004103 }
4104 }
4105 }
4106 return directMode;
4107}
4108
Dorin Drimusf2196d82022-01-03 12:11:18 +01004109status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4110 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004111 if (mEffects.isNonOffloadableEffectEnabled()) {
4112 return OK;
4113 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004114 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004115 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004116 if (status != OK) {
4117 return status;
4118 }
4119 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4120 if (devices.empty()) {
4121 return OK; // no output devices for the attributes
4122 }
4123
4124 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004125 // the MSD module checks for different conditions
4126 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4127 continue;
4128 }
4129 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4130 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004131 continue;
4132 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004133 // allow only profiles that support all the available and routed devices
4134 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004135 != devices.size()) {
4136 continue;
4137 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004138 audioProfilesVector.addAllValidProfiles(
4139 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004140 }
4141 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004142
4143 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4144 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4145 if (msdModule != nullptr) {
4146 if (msdHasPatchesToAllDevices(devices)) {
4147 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4148 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4149 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4150 continue;
4151 }
4152 audioProfilesVector.addAllValidProfiles(
4153 outputProfile->asAudioPort()->getAudioProfiles());
4154 }
4155 } else {
4156 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4157 }
4158 }
4159
Dorin Drimusf2196d82022-01-03 12:11:18 +01004160 return NO_ERROR;
4161}
4162
Eric Laurent6a94d692014-05-20 11:18:06 -07004163status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4164 audio_port_type_t type,
4165 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004166 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 unsigned int *generation)
4168{
jiabin19cdba52020-11-24 11:28:58 -08004169 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4170 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004171 return BAD_VALUE;
4172 }
4173 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004174 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 *num_ports = 0;
4176 }
4177
4178 size_t portsWritten = 0;
4179 size_t portsMax = *num_ports;
4180 *num_ports = 0;
4181 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004182 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4183 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004185 for (const auto& dev : mAvailableOutputDevices) {
4186 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004187 continue;
4188 }
4189 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004190 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004191 }
4192 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004194 }
4195 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004196 for (const auto& dev : mAvailableInputDevices) {
4197 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004198 continue;
4199 }
4200 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004201 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004202 }
4203 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004204 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004205 }
4206 }
4207 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4208 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4209 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4210 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4211 }
4212 *num_ports += mInputs.size();
4213 }
4214 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004215 size_t numOutputs = 0;
4216 for (size_t i = 0; i < mOutputs.size(); i++) {
4217 if (!mOutputs[i]->isDuplicated()) {
4218 numOutputs++;
4219 if (portsWritten < portsMax) {
4220 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4221 }
4222 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004223 }
Eric Laurent84c70242014-06-23 08:46:27 -07004224 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004225 }
4226 }
4227 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004228 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004229 return NO_ERROR;
4230}
4231
jiabin19cdba52020-11-24 11:28:58 -08004232status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004233{
Eric Laurent99fcae42018-05-17 16:59:18 -07004234 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4235 return BAD_VALUE;
4236 }
4237 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4238 if (dev != 0) {
4239 dev->toAudioPort(port);
4240 return NO_ERROR;
4241 }
4242 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4243 if (dev != 0) {
4244 dev->toAudioPort(port);
4245 return NO_ERROR;
4246 }
4247 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4248 if (out != 0) {
4249 out->toAudioPort(port);
4250 return NO_ERROR;
4251 }
4252 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4253 if (in != 0) {
4254 in->toAudioPort(port);
4255 return NO_ERROR;
4256 }
4257 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004258}
4259
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004260status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4261 audio_patch_handle_t *handle,
4262 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004263{
François Gaffieafd4cea2019-11-18 15:50:22 +01004264 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 if (handle == NULL || patch == NULL) {
4266 return BAD_VALUE;
4267 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004268 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004269 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004270 return BAD_VALUE;
4271 }
4272 // only one source per audio patch supported for now
4273 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004274 return INVALID_OPERATION;
4275 }
Eric Laurent874c42872014-08-08 15:13:39 -07004276 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004277 return INVALID_OPERATION;
4278 }
Eric Laurent874c42872014-08-08 15:13:39 -07004279 for (size_t i = 0; i < patch->num_sinks; i++) {
4280 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4281 return INVALID_OPERATION;
4282 }
4283 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004284
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004285 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4286 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4287 if (srcDevice == nullptr || sinkDevice == nullptr) {
4288 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4289 return BAD_VALUE;
4290 }
4291 ALOGV("%s between source %s and sink %s", __func__,
4292 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4293 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4294 // Default attributes, default volume priority, not to infer with non raw audio patches.
4295 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4296 const struct audio_port_config *source = &patch->sources[0];
4297 sp<SourceClientDescriptor> sourceDesc =
4298 new InternalSourceClientDescriptor(
4299 portId, uid, attributes, *source, srcDevice, sinkDevice,
4300 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4301
4302 status_t status =
4303 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4304
4305 if (status != NO_ERROR) {
4306 return INVALID_OPERATION;
4307 }
4308 mAudioSources.add(portId, sourceDesc);
4309 return NO_ERROR;
4310}
4311
4312status_t AudioPolicyManager::connectAudioSourceToSink(
4313 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4314 const struct audio_patch *patch,
4315 audio_patch_handle_t &handle,
4316 uid_t uid, uint32_t delayMs)
4317{
4318 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4319 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4320 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4321 return INVALID_OPERATION;
4322 }
4323 sourceDesc->connect(handle, sinkDevice);
4324 if (isMsdPatch(handle)) {
4325 return NO_ERROR;
4326 }
4327 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4328 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4329 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4330 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4331 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4332 goto FailurePatchAdded;
4333 }
4334 status = swOutput->start();
4335 if (status != NO_ERROR) {
4336 goto FailureSourceAdded;
4337 }
4338 swOutput->addClient(sourceDesc);
4339 status = startSource(swOutput, sourceDesc, &delayMs);
4340 if (status != NO_ERROR) {
4341 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4342 goto FailureSourceActive;
4343 }
4344 if (delayMs != 0) {
4345 usleep(delayMs * 1000);
4346 }
4347 return NO_ERROR;
4348
4349FailureSourceActive:
4350 swOutput->stop();
4351 releaseOutput(sourceDesc->portId());
4352FailureSourceAdded:
4353 sourceDesc->setSwOutput(nullptr);
4354FailurePatchAdded:
4355 releaseAudioPatchInternal(handle);
4356 return INVALID_OPERATION;
4357}
4358
4359status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4360 audio_patch_handle_t *handle,
4361 uid_t uid, uint32_t delayMs,
4362 const sp<SourceClientDescriptor>& sourceDesc)
4363{
4364 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004365 sp<AudioPatch> patchDesc;
4366 ssize_t index = mAudioPatches.indexOfKey(*handle);
4367
François Gaffieafd4cea2019-11-18 15:50:22 +01004368 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4369 patch->sources[0].role,
4370 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004371#if LOG_NDEBUG == 0
4372 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004373 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4374 patch->sinks[i].role,
4375 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004376 }
4377#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004378
4379 if (index >= 0) {
4380 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004381 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4382 __func__, mUidCached, patchDesc->getUid(), uid);
4383 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004384 return INVALID_OPERATION;
4385 }
4386 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004387 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004388 }
4389
4390 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004391 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004392 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004393 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004394 return BAD_VALUE;
4395 }
Eric Laurent84c70242014-06-23 08:46:27 -07004396 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4397 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004398 if (patchDesc != 0) {
4399 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004400 ALOGV("%s source id differs for patch current id %d new id %d",
4401 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004402 return BAD_VALUE;
4403 }
4404 }
Eric Laurent874c42872014-08-08 15:13:39 -07004405 DeviceVector devices;
4406 for (size_t i = 0; i < patch->num_sinks; i++) {
4407 // Only support mix to devices connection
4408 // TODO add support for mix to mix connection
4409 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004410 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004411 return INVALID_OPERATION;
4412 }
4413 sp<DeviceDescriptor> devDesc =
4414 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4415 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004416 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004417 return BAD_VALUE;
4418 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004419
François Gaffie11d30102018-11-02 16:09:09 +01004420 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004421 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004422 NULL, // updatedSamplingRate
4423 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004424 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004425 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004426 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004427 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004428 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004429 return INVALID_OPERATION;
4430 }
4431 devices.add(devDesc);
4432 }
4433 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 return INVALID_OPERATION;
4435 }
Eric Laurent874c42872014-08-08 15:13:39 -07004436
Eric Laurent6a94d692014-05-20 11:18:06 -07004437 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004438 ALOGV("%s setting device %s on output %d",
4439 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004440 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 index = mAudioPatches.indexOfKey(*handle);
4442 if (index >= 0) {
4443 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004444 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 }
4446 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004447 patchDesc->setUid(uid);
4448 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004449 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 return INVALID_OPERATION;
4452 }
4453 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4454 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4455 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004456 // only one sink supported when connecting an input device to a mix
4457 if (patch->num_sinks > 1) {
4458 return INVALID_OPERATION;
4459 }
François Gaffie53615e22015-03-19 09:24:12 +01004460 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004461 if (inputDesc == NULL) {
4462 return BAD_VALUE;
4463 }
4464 if (patchDesc != 0) {
4465 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4466 return BAD_VALUE;
4467 }
4468 }
François Gaffie11d30102018-11-02 16:09:09 +01004469 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004471 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004472 return BAD_VALUE;
4473 }
4474
François Gaffie11d30102018-11-02 16:09:09 +01004475 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004476 patch->sinks[0].sample_rate,
4477 NULL, /*updatedSampleRate*/
4478 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004479 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004480 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004481 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004482 // FIXME for the parameter type,
4483 // and the NONE
4484 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004485 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004486 return INVALID_OPERATION;
4487 }
4488 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004489 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004490 device->toString().c_str(), inputDesc->mIoHandle);
4491 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 index = mAudioPatches.indexOfKey(*handle);
4493 if (index >= 0) {
4494 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004495 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004496 }
4497 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004498 patchDesc->setUid(uid);
4499 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004500 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004501 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004502 return INVALID_OPERATION;
4503 }
4504 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4505 // device to device connection
4506 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004507 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004508 return BAD_VALUE;
4509 }
4510 }
François Gaffie11d30102018-11-02 16:09:09 +01004511 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004512 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004513 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004514 return BAD_VALUE;
4515 }
Eric Laurent874c42872014-08-08 15:13:39 -07004516
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 //update source and sink with our own data as the data passed in the patch may
4518 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004519 PatchBuilder patchBuilder;
4520 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004521
4522 // if first sink is to MSD, establish single MSD patch
4523 if (getMsdAudioOutDevices().contains(
4524 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4525 ALOGV("%s patching to MSD", __FUNCTION__);
4526 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4527 goto installPatch;
4528 }
4529
François Gaffieafd4cea2019-11-18 15:50:22 +01004530 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4531 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004532
Eric Laurent874c42872014-08-08 15:13:39 -07004533 for (size_t i = 0; i < patch->num_sinks; i++) {
4534 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004535 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004536 return INVALID_OPERATION;
4537 }
François Gaffie11d30102018-11-02 16:09:09 +01004538 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004539 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004540 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004541 return BAD_VALUE;
4542 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004543 audio_port_config sinkPortConfig = {};
4544 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4545 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004546
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004547 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4548 // volume management purpose (tracking activity)
4549 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4550 // in config XML to reach the sink so that is can be declared as available.
4551 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4552 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004553 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004554 // take care of dynamic routing for SwOutput selection,
4555 audio_attributes_t attributes = sourceDesc->attributes();
4556 audio_stream_type_t stream = sourceDesc->stream();
4557 audio_attributes_t resultAttr;
4558 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4559 config.sample_rate = sourceDesc->config().sample_rate;
4560 config.channel_mask = sourceDesc->config().channel_mask;
4561 config.format = sourceDesc->config().format;
4562 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4563 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4564 bool isRequestedDeviceForExclusiveUse = false;
4565 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004566 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004567 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4568 &stream, sourceDesc->uid(), &config, &flags,
4569 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004570 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004571 if (output == AUDIO_IO_HANDLE_NONE) {
4572 ALOGV("%s no output for device %s",
4573 __FUNCTION__, sinkDevice->toString().c_str());
4574 return INVALID_OPERATION;
4575 }
4576 outputDesc = mOutputs.valueFor(output);
4577 if (outputDesc->isDuplicated()) {
4578 ALOGE("%s output is duplicated", __func__);
4579 return INVALID_OPERATION;
4580 }
4581 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004582 } else {
4583 // Same for "raw patches" aka created from createAudioPatch API
4584 SortedVector<audio_io_handle_t> outputs =
4585 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4586 // if the sink device is reachable via an opened output stream, request to
4587 // go via this output stream by adding a second source to the patch
4588 // description
4589 output = selectOutput(outputs);
4590 if (output == AUDIO_IO_HANDLE_NONE) {
4591 ALOGE("%s no output available for internal patch sink", __func__);
4592 return INVALID_OPERATION;
4593 }
4594 outputDesc = mOutputs.valueFor(output);
4595 if (outputDesc->isDuplicated()) {
4596 ALOGV("%s output for device %s is duplicated",
4597 __func__, sinkDevice->toString().c_str());
4598 return INVALID_OPERATION;
4599 }
4600 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004601 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004602 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004603 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004604 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004605 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004606 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4607 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004608 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4609 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004610 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004611 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004612 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004613 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004614 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004615 return INVALID_OPERATION;
4616 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004617 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004618 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004619 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004620 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004621 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004622 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4623 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4624 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004625 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004626 }
Eric Laurent83b88082014-06-20 18:31:16 -07004627 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004628 }
4629 // TODO: check from routing capabilities in config file and other conflicting patches
4630
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004631installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004632 status_t status = installPatch(
4633 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004634 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004635 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004636 return INVALID_OPERATION;
4637 }
4638 } else {
4639 return BAD_VALUE;
4640 }
4641 } else {
4642 return BAD_VALUE;
4643 }
4644 return NO_ERROR;
4645}
4646
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004647status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004648{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004649 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 ssize_t index = mAudioPatches.indexOfKey(handle);
4651
4652 if (index < 0) {
4653 return BAD_VALUE;
4654 }
4655 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004656 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4657 __func__, mUidCached, patchDesc->getUid(), uid);
4658 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004659 return INVALID_OPERATION;
4660 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004661 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4662 for (size_t i = 0; i < mAudioSources.size(); i++) {
4663 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4664 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4665 portId = sourceDesc->portId();
4666 break;
4667 }
4668 }
4669 return portId != AUDIO_PORT_HANDLE_NONE ?
4670 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004671}
Eric Laurent6a94d692014-05-20 11:18:06 -07004672
François Gaffieafd4cea2019-11-18 15:50:22 +01004673status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004674 uint32_t delayMs,
4675 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004676{
4677 ALOGV("%s patch %d", __func__, handle);
4678 if (mAudioPatches.indexOfKey(handle) < 0) {
4679 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4680 return BAD_VALUE;
4681 }
4682 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004684 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004688 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 return BAD_VALUE;
4690 }
4691
François Gaffie11d30102018-11-02 16:09:09 +01004692 setOutputDevices(outputDesc,
4693 getNewOutputDevices(outputDesc, true /*fromCache*/),
4694 true,
4695 0,
4696 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004697 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4698 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004699 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004701 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004702 return BAD_VALUE;
4703 }
4704 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004705 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 true,
4707 NULL);
4708 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004709 status_t status =
4710 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4711 ALOGV("%s patch panel returned %d patchHandle %d",
4712 __func__, status, patchDesc->getAfHandle());
4713 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004714 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004715 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004716 // SW or HW Bridge
4717 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4718 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004719 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004720 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4721 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4722 outputDesc = sourceDesc->swOutput().promote();
4723 }
4724 if (outputDesc == nullptr) {
4725 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4726 // releaseOutput has already called closeOutput in case of direct output
4727 return NO_ERROR;
4728 }
4729 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4730 resetOutputDevice(outputDesc);
4731 } else {
4732 // Reuse patch handle if still valid / do not force rerouting if still routed
4733 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004734 setOutputDevices(outputDesc,
4735 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004736 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004737 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004738 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004739 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 } else {
4741 return BAD_VALUE;
4742 }
4743 } else {
4744 return BAD_VALUE;
4745 }
4746 return NO_ERROR;
4747}
4748
4749status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4750 struct audio_patch *patches,
4751 unsigned int *generation)
4752{
François Gaffie53615e22015-03-19 09:24:12 +01004753 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 return BAD_VALUE;
4755 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004757 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004758}
4759
Eric Laurente1715a42014-05-20 11:30:42 -07004760status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004761{
Eric Laurente1715a42014-05-20 11:30:42 -07004762 ALOGV("setAudioPortConfig()");
4763
4764 if (config == NULL) {
4765 return BAD_VALUE;
4766 }
4767 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4768 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004769 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4770 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004771 }
4772
Eric Laurenta121f902014-06-03 13:32:54 -07004773 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004774 if (config->type == AUDIO_PORT_TYPE_MIX) {
4775 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004776 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004777 if (outputDesc == NULL) {
4778 return BAD_VALUE;
4779 }
Eric Laurent84c70242014-06-23 08:46:27 -07004780 ALOG_ASSERT(!outputDesc->isDuplicated(),
4781 "setAudioPortConfig() called on duplicated output %d",
4782 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004783 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004784 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004785 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004786 if (inputDesc == NULL) {
4787 return BAD_VALUE;
4788 }
Eric Laurenta121f902014-06-03 13:32:54 -07004789 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004790 } else {
4791 return BAD_VALUE;
4792 }
4793 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4794 sp<DeviceDescriptor> deviceDesc;
4795 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4796 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4797 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4798 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4799 } else {
4800 return BAD_VALUE;
4801 }
4802 if (deviceDesc == NULL) {
4803 return BAD_VALUE;
4804 }
Eric Laurenta121f902014-06-03 13:32:54 -07004805 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004806 } else {
4807 return BAD_VALUE;
4808 }
4809
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004810 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004811 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4812 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004813 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004814 audioPortConfig->toAudioPortConfig(&newConfig, config);
4815 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004816 }
Eric Laurenta121f902014-06-03 13:32:54 -07004817 if (status != NO_ERROR) {
4818 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004819 }
Eric Laurente1715a42014-05-20 11:30:42 -07004820
4821 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004822}
4823
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004824void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4825{
Eric Laurentd60560a2015-04-10 11:31:20 -07004826 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004827 clearAudioPatches(uid);
4828 clearSessionRoutes(uid);
4829}
4830
Eric Laurent6a94d692014-05-20 11:18:06 -07004831void AudioPolicyManager::clearAudioPatches(uid_t uid)
4832{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004833 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004834 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004835 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004836 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004837 }
4838 }
4839}
4840
François Gaffiec005e562018-11-06 15:04:49 +01004841void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004842{
François Gaffiec005e562018-11-06 15:04:49 +01004843 // Take the first attributes following the product strategy as it is used to retrieve the routed
4844 // device. All attributes wihin a strategy follows the same "routing strategy"
4845 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4846 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004847 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004848 for (size_t j = 0; j < mOutputs.size(); j++) {
4849 if (mOutputs.keyAt(j) == ouptutToSkip) {
4850 continue;
4851 }
4852 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004853 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004854 continue;
4855 }
4856 // If the default device for this strategy is on another output mix,
4857 // invalidate all tracks in this strategy to force re connection.
4858 // Otherwise select new device on the output mix.
4859 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004860 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4861 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004862 }
4863 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004864 setOutputDevices(
4865 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004866 }
4867 }
4868}
4869
4870void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4871{
4872 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004873 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004874 for (size_t i = 0; i < mOutputs.size(); i++) {
4875 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004876 for (const auto& client : outputDesc->getClientIterable()) {
4877 if (client->hasPreferredDevice() && client->uid() == uid) {
4878 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004879 auto clientStrategy = client->strategy();
4880 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4881 end(affectedStrategies)) {
4882 continue;
4883 }
4884 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004885 }
4886 }
4887 }
4888 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004889 for (const auto& strategy : affectedStrategies) {
4890 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004891 }
4892
4893 // remove input routes associated with this uid
4894 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004895 for (size_t i = 0; i < mInputs.size(); i++) {
4896 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004897 for (const auto& client : inputDesc->getClientIterable()) {
4898 if (client->hasPreferredDevice() && client->uid() == uid) {
4899 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4900 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004901 }
4902 }
4903 }
4904 // reroute inputs if necessary
4905 SortedVector<audio_io_handle_t> inputsToClose;
4906 for (size_t i = 0; i < mInputs.size(); i++) {
4907 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004908 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004909 inputsToClose.add(inputDesc->mIoHandle);
4910 }
4911 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004912 for (const auto& input : inputsToClose) {
4913 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004914 }
4915}
4916
Eric Laurentd60560a2015-04-10 11:31:20 -07004917void AudioPolicyManager::clearAudioSources(uid_t uid)
4918{
4919 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004920 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4921 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004922 stopAudioSource(mAudioSources.keyAt(i));
4923 }
4924 }
4925}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004926
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004927status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4928 audio_io_handle_t *ioHandle,
4929 audio_devices_t *device)
4930{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004931 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4932 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004933 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004934 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004935
François Gaffiedf372692015-03-19 10:43:27 +01004936 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004937}
4938
Eric Laurentd60560a2015-04-10 11:31:20 -07004939status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004940 const audio_attributes_t *attributes,
4941 audio_port_handle_t *portId,
4942 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004943{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004944 ALOGV("%s", __FUNCTION__);
4945 *portId = AUDIO_PORT_HANDLE_NONE;
4946
4947 if (source == NULL || attributes == NULL || portId == NULL) {
4948 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4949 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004950 return BAD_VALUE;
4951 }
4952
Eric Laurentd60560a2015-04-10 11:31:20 -07004953 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4954 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004955 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4956 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004957 return INVALID_OPERATION;
4958 }
4959
François Gaffie11d30102018-11-02 16:09:09 +01004960 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004961 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004962 String8(source->ext.device.address),
4963 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004964 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004965 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004966 return BAD_VALUE;
4967 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004968
jiabin4ef93452019-09-10 14:29:54 -07004969 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004970
François Gaffieaaac0fd2018-11-22 17:56:39 +01004971 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004972 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004973 mEngine->getStreamTypeForAttributes(*attributes),
4974 mEngine->getProductStrategyForAttributes(*attributes),
4975 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004976
4977 status_t status = connectAudioSource(sourceDesc);
4978 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004979 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004980 }
4981 return status;
4982}
4983
Francois Gaffie601801d2021-06-22 13:27:39 +02004984sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4985 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4986{
4987 ALOGV("%s", __FUNCTION__);
4988 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4989
4990 status_t status = startAudioSource(source, attributes, &portId, uid);
4991 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4992 return mAudioSources.valueFor(portId);
4993}
4994
4995
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004996status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004997{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004998 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004999
5000 // make sure we only have one patch per source.
5001 disconnectAudioSource(sourceDesc);
5002
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005003 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005004 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5005 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5006 sourceDesc->srcDevice()->type(),
5007 String8(sourceDesc->srcDevice()->address().c_str()),
5008 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005009 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005010 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005011 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005012 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005013 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5014 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5015 return INVALID_OPERATION;
5016 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005017 PatchBuilder patchBuilder;
5018 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5019 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005020
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005021 return connectAudioSourceToSink(
5022 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005023}
5024
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005025status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005026{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005027 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5028 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005029 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005030 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005031 return BAD_VALUE;
5032 }
5033 status_t status = disconnectAudioSource(sourceDesc);
5034
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005035 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005036 return status;
5037}
5038
Andy Hung2ddee192015-12-18 17:34:44 -08005039status_t AudioPolicyManager::setMasterMono(bool mono)
5040{
5041 if (mMasterMono == mono) {
5042 return NO_ERROR;
5043 }
5044 mMasterMono = mono;
5045 // if enabling mono we close all offloaded devices, which will invalidate the
5046 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5047 // for recreating the new AudioTrack as non-offloaded PCM.
5048 //
5049 // If disabling mono, we leave all tracks as is: we don't know which clients
5050 // and tracks are able to be recreated as offloaded. The next "song" should
5051 // play back offloaded.
5052 if (mMasterMono) {
5053 Vector<audio_io_handle_t> offloaded;
5054 for (size_t i = 0; i < mOutputs.size(); ++i) {
5055 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5056 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5057 offloaded.push(desc->mIoHandle);
5058 }
5059 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005060 for (const auto& handle : offloaded) {
5061 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005062 }
5063 }
5064 // update master mono for all remaining outputs
5065 for (size_t i = 0; i < mOutputs.size(); ++i) {
5066 updateMono(mOutputs.keyAt(i));
5067 }
5068 return NO_ERROR;
5069}
5070
5071status_t AudioPolicyManager::getMasterMono(bool *mono)
5072{
5073 *mono = mMasterMono;
5074 return NO_ERROR;
5075}
5076
Eric Laurentac9cef52017-06-09 15:46:26 -07005077float AudioPolicyManager::getStreamVolumeDB(
5078 audio_stream_type_t stream, int index, audio_devices_t device)
5079{
jiabin9a3361e2019-10-01 09:38:30 -07005080 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005081}
5082
jiabin81772902018-04-02 17:52:27 -07005083status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5084 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005085 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005086{
Kriti Dang6537def2021-03-02 13:46:59 +01005087 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5088 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005089 return BAD_VALUE;
5090 }
Kriti Dang6537def2021-03-02 13:46:59 +01005091 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5092 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005093
5094 size_t formatsWritten = 0;
5095 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005096
Kriti Dang6537def2021-03-02 13:46:59 +01005097 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005098 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5099 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005100 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005101 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005102 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005103 bool formatEnabled = true;
5104 switch (forceUse) {
5105 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005106 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005107 break;
5108 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5109 formatEnabled = false;
5110 break;
5111 default: // AUTO or ALWAYS => true
5112 break;
jiabin81772902018-04-02 17:52:27 -07005113 }
5114 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5115 }
jiabin81772902018-04-02 17:52:27 -07005116 }
5117 return NO_ERROR;
5118}
5119
Kriti Dang6537def2021-03-02 13:46:59 +01005120status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5121 audio_format_t *surroundFormats) {
5122 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5123 return BAD_VALUE;
5124 }
5125 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5126 __func__, *numSurroundFormats, surroundFormats);
5127
5128 size_t formatsWritten = 0;
5129 size_t formatsMax = *numSurroundFormats;
5130 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5131
5132 // Return formats from all device profiles that have already been resolved by
5133 // checkOutputsForDevice().
5134 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5135 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5136 audio_devices_t deviceType = device->type();
5137 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5138 // returns formats reported by HDMI devices.
5139 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5140 continue;
5141 }
5142 // Formats reported by sink devices
5143 std::unordered_set<audio_format_t> formatset;
5144 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5145 formatset.insert(it->second.begin(), it->second.end());
5146 }
5147
5148 // Formats hard-coded in the in policy configuration file (if any).
5149 FormatVector encodedFormats = device->encodedFormats();
5150 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5151 // Filter the formats which are supported by the vendor hardware.
5152 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5153 if (mConfig.getSurroundFormats().count(*it) != 0) {
5154 formats.insert(*it);
5155 } else {
5156 for (const auto& pair : mConfig.getSurroundFormats()) {
5157 if (pair.second.count(*it) != 0) {
5158 formats.insert(pair.first);
5159 break;
5160 }
5161 }
5162 }
5163 }
5164 }
5165 *numSurroundFormats = formats.size();
5166 for (const auto& format: formats) {
5167 if (formatsWritten < formatsMax) {
5168 surroundFormats[formatsWritten++] = format;
5169 }
5170 }
5171 return NO_ERROR;
5172}
5173
jiabin81772902018-04-02 17:52:27 -07005174status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5175{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005176 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005177 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5178 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005179 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005180 return BAD_VALUE;
5181 }
5182
Mikhail Naganov100f0122018-11-29 11:22:16 -08005183 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5184 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005185 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005186 return INVALID_OPERATION;
5187 }
5188
Mikhail Naganov100f0122018-11-29 11:22:16 -08005189 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005190 return NO_ERROR;
5191 }
5192
Mikhail Naganov100f0122018-11-29 11:22:16 -08005193 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005194 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005195 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005196 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005197 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005198 }
5199 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005200 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005201 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005202 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005203 }
5204 }
5205
5206 sp<SwAudioOutputDescriptor> outputDesc;
5207 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005208 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5209 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005210 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5211 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005212 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005213 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005214 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5215 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5216 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005217 name.c_str(),
5218 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005219 if (status != NO_ERROR) {
5220 continue;
5221 }
5222 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5224 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005225 name.c_str(),
5226 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005227 profileUpdated |= (status == NO_ERROR);
5228 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005229 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005230 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005231 AUDIO_DEVICE_IN_HDMI);
5232 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5233 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005234 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005235 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005236 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5237 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5238 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005239 name.c_str(),
5240 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005241 if (status != NO_ERROR) {
5242 continue;
5243 }
5244 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5245 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5246 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005247 name.c_str(),
5248 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005249 profileUpdated |= (status == NO_ERROR);
5250 }
5251
jiabin81772902018-04-02 17:52:27 -07005252 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005253 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005254 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005255 }
5256
5257 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5258}
5259
Eric Laurent5ada82e2019-08-29 17:53:54 -07005260void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005261{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005262 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005263 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005264 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005265 }
5266}
5267
jiabin6012f912018-11-02 17:06:30 -07005268bool AudioPolicyManager::isHapticPlaybackSupported()
5269{
5270 for (const auto& hwModule : mHwModules) {
5271 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5272 for (const auto &outProfile : outputProfiles) {
5273 struct audio_port audioPort;
5274 outProfile->toAudioPort(&audioPort);
5275 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5276 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5277 return true;
5278 }
5279 }
5280 }
5281 }
5282 return false;
5283}
5284
Carter Hsu325a8eb2022-01-19 19:56:51 +08005285bool AudioPolicyManager::isUltrasoundSupported()
5286{
5287 bool hasUltrasoundOutput = false;
5288 bool hasUltrasoundInput = false;
5289 for (const auto& hwModule : mHwModules) {
5290 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5291 if (!hasUltrasoundOutput) {
5292 for (const auto &outProfile : outputProfiles) {
5293 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5294 hasUltrasoundOutput = true;
5295 break;
5296 }
5297 }
5298 }
5299
5300 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5301 if (!hasUltrasoundInput) {
5302 for (const auto &inputProfile : inputProfiles) {
5303 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5304 hasUltrasoundInput = true;
5305 break;
5306 }
5307 }
5308 }
5309
5310 if (hasUltrasoundOutput && hasUltrasoundInput)
5311 return true;
5312 }
5313 return false;
5314}
5315
Eric Laurent8340e672019-11-06 11:01:08 -08005316bool AudioPolicyManager::isCallScreenModeSupported()
5317{
5318 return getConfig().isCallScreenModeSupported();
5319}
5320
5321
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005322status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005323{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005324 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005325 if (!sourceDesc->isConnected()) {
5326 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5327 return NO_ERROR;
5328 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005329 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5330 if (swOutput != 0) {
5331 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005332 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005333 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005334 }
jiabinbce0c1d2020-10-05 11:20:18 -07005335 if (releaseOutput(sourceDesc->portId())) {
5336 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5337 // no need to release audio patch here but just return NO_ERROR.
5338 return NO_ERROR;
5339 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005340 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005341 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005342 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005343 // close Hwoutput and remove from mHwOutputs
5344 } else {
5345 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5346 }
5347 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005348 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005349 sourceDesc->disconnect();
5350 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005351}
5352
François Gaffiec005e562018-11-06 15:04:49 +01005353sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5354 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005355{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005356 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005357 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005358 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005359 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005360 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5361 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005362 source = sourceDesc;
5363 break;
5364 }
5365 }
5366 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005367}
5368
Eric Laurentb4f42a92022-01-17 17:37:31 +01005369bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005370 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005371 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005372{
5373 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5374 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005375 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005376 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005377 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5378 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5379 return false;
5380 }
5381 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5382 return false;
5383 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005384 }
5385
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005386 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005387 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005388 if (profile == nullptr) {
5389 return false;
5390 }
5391
5392 // The caller can have the audio config criteria ignored by either passing a null ptr or
5393 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005394 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005395 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005396
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005397 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005398 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005399 return false;
5400 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005401 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005402 return true;
5403}
5404
5405void AudioPolicyManager::checkVirtualizerClientRoutes() {
5406 std::set<audio_stream_type_t> streamsToInvalidate;
5407 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005408 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5409 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005410 audio_attributes_t attr = client->attributes();
5411 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5412 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5413 audio_config_base_t clientConfig = client->config();
5414 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005415 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005416 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005417 streamsToInvalidate.insert(client->stream());
5418 }
5419 }
5420 }
5421
5422 for (audio_stream_type_t stream : streamsToInvalidate) {
5423 mpClientInterface->invalidateStream(stream);
5424 }
5425}
5426
Eric Laurente191d1b2022-04-15 11:59:25 +02005427
5428bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5429 const sp<SwAudioOutputDescriptor>& outputDesc) {
5430 if (outputDesc->isDuplicated()) {
5431 return false;
5432 }
5433 DeviceVector devices = outputDesc->supportedDevices();
5434 for (size_t i = 0; i < mOutputs.size(); i++) {
5435 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5436 if (desc == outputDesc || desc->isDuplicated()) {
5437 continue;
5438 }
5439 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5440 if (!sharedDevices.isEmpty()
5441 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5442 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5443 return false;
5444 }
5445 }
5446 return true;
5447}
5448
5449
Eric Laurentfa0f6742021-08-17 18:39:44 +02005450status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005451 const audio_attributes_t *attr,
5452 audio_io_handle_t *output) {
5453 *output = AUDIO_IO_HANDLE_NONE;
5454
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005455 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5456 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5457 audio_config_t *configPtr = nullptr;
5458 audio_config_t config;
5459 if (mixerConfig != nullptr) {
5460 config = audio_config_initializer(mixerConfig);
5461 configPtr = &config;
5462 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005463 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005464 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005465 return BAD_VALUE;
5466 }
5467
5468 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005469 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005470 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005471 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005472 return BAD_VALUE;
5473 }
5474
Eric Laurente191d1b2022-04-15 11:59:25 +02005475 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005476 for (size_t i = 0; i < mOutputs.size(); i++) {
5477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005478 if (!desc->isDuplicated()
5479 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5480 spatializerOutputs.push_back(desc);
5481 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005482 }
5483 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005484 mSpatializerOutput.clear();
5485 bool outputsChanged = false;
5486 for (const auto& desc : spatializerOutputs) {
5487 if (desc->mProfile == profile
5488 && (configPtr == nullptr
5489 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5490 mSpatializerOutput = desc;
5491 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5492 } else {
5493 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5494 " and devices %s", __func__, desc->mIoHandle,
5495 configPtr != nullptr ? configPtr->channel_mask : 0,
5496 devices.toString().c_str());
5497 closeOutput(desc->mIoHandle);
5498 outputsChanged = true;
5499 }
Eric Laurent39095982021-08-24 18:29:27 +02005500 }
5501
Eric Laurente191d1b2022-04-15 11:59:25 +02005502 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005503 sp<SwAudioOutputDescriptor> desc =
5504 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005505 if (desc != nullptr) {
5506 mSpatializerOutput = desc;
5507 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005508 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005509 }
5510
5511 checkVirtualizerClientRoutes();
5512
Eric Laurente191d1b2022-04-15 11:59:25 +02005513 if (outputsChanged) {
5514 mPreviousOutputs = mOutputs;
5515 mpClientInterface->onAudioPortListUpdate();
5516 }
5517
5518 if (mSpatializerOutput == nullptr) {
5519 ALOGV("%s could not open spatializer output with requested config", __func__);
5520 return BAD_VALUE;
5521 }
Eric Laurent39095982021-08-24 18:29:27 +02005522 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005523 ALOGV("%s returning new spatializer output %d", __func__, *output);
5524 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005525}
5526
Eric Laurentfa0f6742021-08-17 18:39:44 +02005527status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5528 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005529 return INVALID_OPERATION;
5530 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005531 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005532 return BAD_VALUE;
5533 }
Eric Laurent39095982021-08-24 18:29:27 +02005534
Eric Laurente191d1b2022-04-15 11:59:25 +02005535 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5536 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5537 closeOutput(mSpatializerOutput->mIoHandle);
5538 //from now on mSpatializerOutput is null
5539 checkVirtualizerClientRoutes();
5540 }
Eric Laurent39095982021-08-24 18:29:27 +02005541
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005542 return NO_ERROR;
5543}
5544
Eric Laurente552edb2014-03-10 17:42:56 -07005545// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005546// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005547// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005548uint32_t AudioPolicyManager::nextAudioPortGeneration()
5549{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005550 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005551}
5552
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005553static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005554 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5555 !audioPolicyXmlConfigFile.empty()) {
5556 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5557 if (ret == NO_ERROR) {
5558 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005559 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005560 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005561 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005562 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005563}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005564
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005565AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5566 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005567 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005568 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005569 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005570 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005571 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005572 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005573 mAudioPortGeneration(1),
5574 mBeaconMuteRefCount(0),
5575 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005576 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005577 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005578 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005579 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005580{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005581}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005582
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005583AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5584 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5585{
5586 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005587}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005588
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005589void AudioPolicyManager::loadConfig() {
5590 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005591 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005592 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005593 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005594}
5595
5596status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005597 {
5598 auto engLib = EngineLibrary::load(
5599 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5600 if (!engLib) {
5601 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5602 return NO_INIT;
5603 }
5604 mEngine = engLib->createEngine();
5605 if (mEngine == nullptr) {
5606 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5607 return NO_INIT;
5608 }
François Gaffie2110e042015-03-24 08:41:51 +01005609 }
5610 mEngine->setObserver(this);
5611 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005612 if (status != NO_ERROR) {
5613 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5614 return status;
5615 }
François Gaffie2110e042015-03-24 08:41:51 +01005616
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005617 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005618 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5619 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5620
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005621 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005622 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005623 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005624
Eric Laurent3a4311c2014-03-17 12:00:47 -07005625 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005626 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5627 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5628 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005629 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005630 }
jiabin9ff780e2018-03-19 18:19:52 -07005631 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005632 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005633 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005634 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005635 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005636 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005637 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005638 }
5639 }
5640 }
Eric Laurente552edb2014-03-10 17:42:56 -07005641
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005642 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005643
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005644 // Silence ALOGV statements
5645 property_set("log.tag." LOG_TAG, "D");
5646
Eric Laurente552edb2014-03-10 17:42:56 -07005647 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005648 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005649}
5650
Eric Laurente0720872014-03-11 09:30:41 -07005651AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005652{
Eric Laurente552edb2014-03-10 17:42:56 -07005653 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005654 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005655 }
5656 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005657 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005658 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005659 mAvailableOutputDevices.clear();
5660 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005661 mOutputs.clear();
5662 mInputs.clear();
5663 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005664 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005665 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005666}
5667
Eric Laurente0720872014-03-11 09:30:41 -07005668status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005669{
Eric Laurent87ffa392015-05-22 10:32:38 -07005670 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005671}
5672
Eric Laurente552edb2014-03-10 17:42:56 -07005673// ---
5674
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005675void AudioPolicyManager::onNewAudioModulesAvailable()
5676{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005677 DeviceVector newDevices;
5678 onNewAudioModulesAvailableInt(&newDevices);
5679 if (!newDevices.empty()) {
5680 nextAudioPortGeneration();
5681 mpClientInterface->onAudioPortListUpdate();
5682 }
5683}
5684
5685void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5686{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005687 for (const auto& hwModule : mHwModulesAll) {
5688 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5689 continue;
5690 }
5691 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5692 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5693 ALOGW("could not open HW module %s", hwModule->getName());
5694 continue;
5695 }
5696 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005697 // open all output streams needed to access attached devices.
5698 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005699 // This also validates mAvailableOutputDevices list
5700 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5701 if (!outProfile->canOpenNewIo()) {
5702 ALOGE("Invalid Output profile max open count %u for profile %s",
5703 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5704 continue;
5705 }
5706 if (!outProfile->hasSupportedDevices()) {
5707 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5708 continue;
5709 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005710 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5711 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005712 mTtsOutputAvailable = true;
5713 }
5714
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005715 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5716 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5717 sp<DeviceDescriptor> supportedDevice = 0;
5718 if (supportedDevices.contains(mDefaultOutputDevice)) {
5719 supportedDevice = mDefaultOutputDevice;
5720 } else {
5721 // choose first device present in profile's SupportedDevices also part of
5722 // mAvailableOutputDevices.
5723 if (availProfileDevices.isEmpty()) {
5724 continue;
5725 }
5726 supportedDevice = availProfileDevices.itemAt(0);
5727 }
5728 if (!mOutputDevicesAll.contains(supportedDevice)) {
5729 continue;
5730 }
5731 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5732 mpClientInterface);
5733 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005734 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5735 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005736 AUDIO_STREAM_DEFAULT,
5737 AUDIO_OUTPUT_FLAG_NONE, &output);
5738 if (status != NO_ERROR) {
5739 ALOGW("Cannot open output stream for devices %s on hw module %s",
5740 supportedDevice->toString().c_str(), hwModule->getName());
5741 continue;
5742 }
5743 for (const auto &device : availProfileDevices) {
5744 // give a valid ID to an attached device once confirmed it is reachable
5745 if (!device->isAttached()) {
5746 device->attach(hwModule);
5747 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005748 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005749 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005750 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5751 }
5752 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005753 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005754 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5755 mPrimaryOutput = outputDesc;
5756 }
Eric Laurent39095982021-08-24 18:29:27 +02005757 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005758 outputDesc->close();
5759 } else {
5760 addOutput(output, outputDesc);
5761 setOutputDevices(outputDesc,
5762 DeviceVector(supportedDevice),
5763 true,
5764 0,
5765 NULL);
5766 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005767 }
5768 // open input streams needed to access attached devices to validate
5769 // mAvailableInputDevices list
5770 for (const auto& inProfile : hwModule->getInputProfiles()) {
5771 if (!inProfile->canOpenNewIo()) {
5772 ALOGE("Invalid Input profile max open count %u for profile %s",
5773 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5774 continue;
5775 }
5776 if (!inProfile->hasSupportedDevices()) {
5777 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5778 continue;
5779 }
5780 // chose first device present in profile's SupportedDevices also part of
5781 // available input devices
5782 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5783 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5784 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005785 ALOGV("%s: Input device list is empty! for profile %s",
5786 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005787 continue;
5788 }
5789 sp<AudioInputDescriptor> inputDesc =
5790 new AudioInputDescriptor(inProfile, mpClientInterface);
5791
5792 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5793 status_t status = inputDesc->open(nullptr,
5794 availProfileDevices.itemAt(0),
5795 AUDIO_SOURCE_MIC,
5796 AUDIO_INPUT_FLAG_NONE,
5797 &input);
5798 if (status != NO_ERROR) {
5799 ALOGW("Cannot open input stream for device %s on hw module %s",
5800 availProfileDevices.toString().c_str(),
5801 hwModule->getName());
5802 continue;
5803 }
5804 for (const auto &device : availProfileDevices) {
5805 // give a valid ID to an attached device once confirmed it is reachable
5806 if (!device->isAttached()) {
5807 device->attach(hwModule);
5808 device->importAudioPortAndPickAudioProfile(inProfile, true);
5809 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005810 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005811 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5812 }
5813 }
5814 inputDesc->close();
5815 }
5816 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005817
5818 // Check if spatializer outputs can be closed until used.
5819 // mOutputs vector never contains duplicated outputs at this point.
5820 std::vector<audio_io_handle_t> outputsClosed;
5821 for (size_t i = 0; i < mOutputs.size(); i++) {
5822 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5823 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5824 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5825 outputsClosed.push_back(desc->mIoHandle);
5826 desc->close();
5827 }
5828 }
5829 for (auto output : outputsClosed) {
5830 removeOutput(output);
5831 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005832}
5833
Eric Laurent98e38192018-02-15 18:31:53 -08005834void AudioPolicyManager::addOutput(audio_io_handle_t output,
5835 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005836{
Eric Laurent1c333e22014-05-20 10:48:17 -07005837 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005838 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005839 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005840 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005841 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005842}
5843
François Gaffie53615e22015-03-19 09:24:12 +01005844void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5845{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005846 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5847 ALOGV("%s: removing primary output", __func__);
5848 mPrimaryOutput = nullptr;
5849 }
François Gaffie53615e22015-03-19 09:24:12 +01005850 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005851 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005852}
5853
Eric Laurent98e38192018-02-15 18:31:53 -08005854void AudioPolicyManager::addInput(audio_io_handle_t input,
5855 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005856{
Eric Laurent1c333e22014-05-20 10:48:17 -07005857 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005858 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005859}
Eric Laurente552edb2014-03-10 17:42:56 -07005860
François Gaffie11d30102018-11-02 16:09:09 +01005861status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005862 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005863 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005864{
François Gaffie11d30102018-11-02 16:09:09 +01005865 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005866 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005867 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005868
François Gaffie11d30102018-11-02 16:09:09 +01005869 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005870 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005871 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005872 }
Eric Laurente552edb2014-03-10 17:42:56 -07005873
Eric Laurent3b73df72014-03-11 09:06:29 -07005874 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005875 // first call getAudioPort to get the supported attributes from the HAL
5876 struct audio_port_v7 port = {};
5877 device->toAudioPort(&port);
5878 status_t status = mpClientInterface->getAudioPort(&port);
5879 if (status == NO_ERROR) {
5880 device->importAudioPort(port);
5881 }
5882
5883 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005884 for (size_t i = 0; i < mOutputs.size(); i++) {
5885 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005886 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005887 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005888 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5889 mOutputs.keyAt(i), device->toString().c_str());
5890 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005891 }
5892 }
5893 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005894 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005895 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005896 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5897 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005898 if (profile->supportsDevice(device)) {
5899 profiles.add(profile);
5900 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5901 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005902 }
5903 }
5904 }
5905
Eric Laurent7b279bb2015-12-14 10:18:23 -08005906 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005907
Eric Laurente552edb2014-03-10 17:42:56 -07005908 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005909 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005910 return BAD_VALUE;
5911 }
5912
5913 // open outputs for matching profiles if needed. Direct outputs are also opened to
5914 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5915 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005916 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005917
5918 // nothing to do if one output is already opened for this profile
5919 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005920 for (j = 0; j < outputs.size(); j++) {
5921 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005922 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005923 // matching profile: save the sample rates, format and channel masks supported
5924 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005925 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005926 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005927 }
Eric Laurente552edb2014-03-10 17:42:56 -07005928 break;
5929 }
5930 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005931 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005932 continue;
5933 }
5934
Eric Laurent3974e3b2017-12-07 17:58:43 -08005935 if (!profile->canOpenNewIo()) {
5936 ALOGW("Max Output number %u already opened for this profile %s",
5937 profile->maxOpenCount, profile->getTagName().c_str());
5938 continue;
5939 }
5940
Eric Laurent83efe1c2017-07-09 16:51:08 -07005941 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005942 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005943 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5944 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005945 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005946 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005947 profiles.removeAt(profile_index);
5948 profile_index--;
5949 } else {
5950 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005951 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005952 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005953 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5954 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005955 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005956 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005957
François Gaffie11d30102018-11-02 16:09:09 +01005958 if (device_distinguishes_on_address(deviceType)) {
5959 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5960 device->toString().c_str());
5961 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5962 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005963 }
Eric Laurente552edb2014-03-10 17:42:56 -07005964 ALOGV("checkOutputsForDevice(): adding output %d", output);
5965 }
5966 }
5967
5968 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005969 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005970 return BAD_VALUE;
5971 }
Eric Laurentd4692962014-05-05 18:13:44 -07005972 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005973 // check if one opened output is not needed any more after disconnecting one device
5974 for (size_t i = 0; i < mOutputs.size(); i++) {
5975 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005976 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005977 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005978 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005979 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005980 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005981 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005982 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5983 mOutputs.keyAt(i));
5984 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005985 }
Eric Laurente552edb2014-03-10 17:42:56 -07005986 }
5987 }
Eric Laurentd4692962014-05-05 18:13:44 -07005988 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005989 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005990 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5991 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005992 if (!profile->supportsDevice(device)) {
5993 continue;
5994 }
5995 ALOGV("checkOutputsForDevice(): "
5996 "clearing direct output profile %zu on module %s",
5997 j, hwModule->getName());
5998 profile->clearAudioProfiles();
5999 if (!profile->hasDynamicAudioProfile()) {
6000 continue;
6001 }
6002 // When a device is disconnected, if there is an IOProfile that contains dynamic
6003 // profiles and supports the disconnected device, call getAudioPort to repopulate
6004 // the capabilities of the devices that is supported by the IOProfile.
6005 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6006 if (supportedDevice == device ||
6007 !mAvailableOutputDevices.contains(supportedDevice)) {
6008 continue;
6009 }
6010 struct audio_port_v7 port;
6011 supportedDevice->toAudioPort(&port);
6012 status_t status = mpClientInterface->getAudioPort(&port);
6013 if (status == NO_ERROR) {
6014 supportedDevice->importAudioPort(port);
6015 }
Eric Laurente552edb2014-03-10 17:42:56 -07006016 }
6017 }
6018 }
6019 }
6020 return NO_ERROR;
6021}
6022
François Gaffie11d30102018-11-02 16:09:09 +01006023status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006024 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006025{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006026 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006027
François Gaffie11d30102018-11-02 16:09:09 +01006028 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006029 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006030 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006031 }
6032
Eric Laurentd4692962014-05-05 18:13:44 -07006033 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006034 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006035 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006036 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006037 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006038 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006039 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006040 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006041
François Gaffie11d30102018-11-02 16:09:09 +01006042 if (profile->supportsDevice(device)) {
6043 profiles.add(profile);
6044 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6045 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006046 }
6047 }
6048 }
6049
Eric Laurent0dd51852019-04-19 18:18:58 -07006050 if (profiles.isEmpty()) {
6051 ALOGW("%s: No input profile available for device %s",
6052 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006053 return BAD_VALUE;
6054 }
6055
6056 // open inputs for matching profiles if needed. Direct inputs are also opened to
6057 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6058 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6059
Eric Laurent1c333e22014-05-20 10:48:17 -07006060 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006061
Eric Laurentd4692962014-05-05 18:13:44 -07006062 // nothing to do if one input is already opened for this profile
6063 size_t input_index;
6064 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6065 desc = mInputs.valueAt(input_index);
6066 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006067 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006068 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006069 }
Eric Laurentd4692962014-05-05 18:13:44 -07006070 break;
6071 }
6072 }
6073 if (input_index != mInputs.size()) {
6074 continue;
6075 }
6076
Eric Laurent3974e3b2017-12-07 17:58:43 -08006077 if (!profile->canOpenNewIo()) {
6078 ALOGW("Max Input number %u already opened for this profile %s",
6079 profile->maxOpenCount, profile->getTagName().c_str());
6080 continue;
6081 }
6082
Eric Laurentfe231122017-11-17 17:48:06 -08006083 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006084 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006085 status_t status = desc->open(nullptr,
6086 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006087 AUDIO_SOURCE_MIC,
6088 AUDIO_INPUT_FLAG_NONE,
6089 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006090
Eric Laurentcf2c0212014-07-25 16:20:43 -07006091 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006092 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006093 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006094 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006095 mpClientInterface->setParameters(input, String8(param));
6096 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006097 }
François Gaffie11d30102018-11-02 16:09:09 +01006098 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006099 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006100 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006101 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006102 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006103 }
6104
Eric Laurent0dd51852019-04-19 18:18:58 -07006105 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006106 addInput(input, desc);
6107 }
6108 } // endif input != 0
6109
Eric Laurentcf2c0212014-07-25 16:20:43 -07006110 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006111 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006112 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006113 profiles.removeAt(profile_index);
6114 profile_index--;
6115 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006116 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006117 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006118 }
Eric Laurentd4692962014-05-05 18:13:44 -07006119 ALOGV("checkInputsForDevice(): adding input %d", input);
6120 }
6121 } // end scan profiles
6122
6123 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006124 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006125 return BAD_VALUE;
6126 }
6127 } else {
6128 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006129 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006130 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006131 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006132 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006133 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006134 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006135 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006136 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6137 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006138 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006139 }
6140 }
6141 }
6142 } // end disconnect
6143
6144 return NO_ERROR;
6145}
6146
6147
Eric Laurente0720872014-03-11 09:30:41 -07006148void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006149{
6150 ALOGV("closeOutput(%d)", output);
6151
François Gaffie1c878552018-11-22 16:53:21 +01006152 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6153 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006154 ALOGW("closeOutput() unknown output %d", output);
6155 return;
6156 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006157 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006158 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006159
Eric Laurente552edb2014-03-10 17:42:56 -07006160 // look for duplicated outputs connected to the output being removed.
6161 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006162 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6163 if (dupOutput->isDuplicated() &&
6164 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6165 sp<SwAudioOutputDescriptor> remainingOutput =
6166 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006167 // As all active tracks on duplicated output will be deleted,
6168 // and as they were also referenced on the other output, the reference
6169 // count for their stream type must be adjusted accordingly on
6170 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006171 const bool wasActive = remainingOutput->isActive();
6172 // Note: no-op on the closing output where all clients has already been set inactive
6173 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006174 // stop() will be a no op if the output is still active but is needed in case all
6175 // active streams refcounts where cleared above
6176 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006177 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006178 }
Eric Laurente552edb2014-03-10 17:42:56 -07006179 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6180 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6181
6182 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006183 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006184 }
6185 }
6186
Eric Laurent05b90f82014-08-27 15:32:29 -07006187 nextAudioPortGeneration();
6188
François Gaffie1c878552018-11-22 16:53:21 +01006189 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006190 if (index >= 0) {
6191 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006192 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6193 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006194 mAudioPatches.removeItemsAt(index);
6195 mpClientInterface->onAudioPatchListUpdate();
6196 }
6197
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006198 if (closingOutputWasActive) {
6199 closingOutput->stop();
6200 }
François Gaffie1c878552018-11-22 16:53:21 +01006201 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006202
François Gaffie53615e22015-03-19 09:24:12 +01006203 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006204 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006205 if (closingOutput == mSpatializerOutput) {
6206 mSpatializerOutput.clear();
6207 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006208
6209 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6210 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006211 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006212 bool directOutputOpen = false;
6213 for (size_t i = 0; i < mOutputs.size(); i++) {
6214 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6215 directOutputOpen = true;
6216 break;
6217 }
6218 }
6219 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006220 ALOGV("no direct outputs open, reset MSD patches");
6221 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6222 // how output devices for patching are resolved. Avoid by caching and reusing the
6223 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6224 // devices to patch to. This may be complicated by the fact that devices may become
6225 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006226 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006227 }
6228 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006229}
6230
6231void AudioPolicyManager::closeInput(audio_io_handle_t input)
6232{
6233 ALOGV("closeInput(%d)", input);
6234
6235 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6236 if (inputDesc == NULL) {
6237 ALOGW("closeInput() unknown input %d", input);
6238 return;
6239 }
6240
Eric Laurent6a94d692014-05-20 11:18:06 -07006241 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006242
François Gaffie11d30102018-11-02 16:09:09 +01006243 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006244 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006245 if (index >= 0) {
6246 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006247 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6248 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006249 mAudioPatches.removeItemsAt(index);
6250 mpClientInterface->onAudioPatchListUpdate();
6251 }
6252
Eric Laurentfe231122017-11-17 17:48:06 -08006253 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006254 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006255
François Gaffie11d30102018-11-02 16:09:09 +01006256 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6257 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006258 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006259 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006260 }
Eric Laurente552edb2014-03-10 17:42:56 -07006261}
6262
François Gaffie11d30102018-11-02 16:09:09 +01006263SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6264 const DeviceVector &devices,
6265 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006266{
6267 SortedVector<audio_io_handle_t> outputs;
6268
François Gaffie11d30102018-11-02 16:09:09 +01006269 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006270 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006271 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006272 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006273 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006274 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006275 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006276 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006277 outputs.add(openOutputs.keyAt(i));
6278 }
6279 }
6280 return outputs;
6281}
6282
Mikhail Naganov37977152018-07-11 15:54:44 -07006283void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6284{
6285 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6286 // output is suspended before any tracks are moved to it
6287 checkA2dpSuspend();
6288 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006289 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006290 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006291 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006292 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006293 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6294 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6295 // configuration changes will ultimately be rerouted correctly. We can still avoid
6296 // unnecessary rerouting by caching and reusing the arguments to
6297 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6298 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006299 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006300 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006301 // an event that changed routing likely occurred, inform upper layers
6302 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006303}
6304
François Gaffiec005e562018-11-06 15:04:49 +01006305bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6306 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006307{
François Gaffiec005e562018-11-06 15:04:49 +01006308 return mEngine->getProductStrategyForAttributes(lAttr) ==
6309 mEngine->getProductStrategyForAttributes(rAttr);
6310}
6311
Francois Gaffieff1eb522020-05-06 18:37:04 +02006312void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6313{
6314 for (size_t i = 0; i < mAudioSources.size(); i++) {
6315 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6316 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006317 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006318 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006319 connectAudioSource(sourceDesc);
6320 }
6321 }
6322}
6323
6324void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6325{
6326 for (size_t i = 0; i < mAudioSources.size(); i++) {
6327 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6328 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6329 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6330 disconnectAudioSource(sourceDesc);
6331 }
6332 }
6333}
6334
François Gaffiec005e562018-11-06 15:04:49 +01006335void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6336{
6337 auto psId = mEngine->getProductStrategyForAttributes(attr);
6338
6339 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6340 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006341
François Gaffie11d30102018-11-02 16:09:09 +01006342 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6343 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006344
Eric Laurentc209fe42020-06-05 18:11:23 -07006345 uint32_t maxLatency = 0;
6346 bool invalidate = false;
6347 // take into account dynamic audio policies related changes: if a client is now associated
6348 // to a different policy mix than at creation time, invalidate corresponding stream
6349 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6350 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6351 if (desc->isDuplicated()) {
6352 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006353 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006354 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6355 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6356 continue;
6357 }
6358 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006359 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6360 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006361 if (status != OK) {
6362 continue;
6363 }
yucliuf4de36d2020-09-14 14:57:56 -07006364 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006365 invalidate = true;
6366 if (desc->isStrategyActive(psId)) {
6367 maxLatency = desc->latency();
6368 }
6369 break;
6370 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006371 }
6372 }
6373
Eric Laurentc209fe42020-06-05 18:11:23 -07006374 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006375 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6376 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006377 for (audio_io_handle_t srcOut : srcOutputs) {
6378 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006379 if (desc == nullptr) continue;
6380
6381 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006382 maxLatency = desc->latency();
6383 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006384
6385 if (invalidate) continue;
6386
6387 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006388 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006389 // a client on a non direct outputs has necessarily a linear PCM format
6390 // so we can call selectOutput() safely
6391 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6392 client->flags(),
6393 client->config().format,
6394 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006395 client->config().sample_rate,
6396 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006397 if (newOutput != srcOut) {
6398 invalidate = true;
6399 break;
6400 }
6401 } else {
6402 sp<IOProfile> profile = getProfileForOutput(newDevices,
6403 client->config().sample_rate,
6404 client->config().format,
6405 client->config().channel_mask,
6406 client->flags(),
6407 true /* directOnly */);
6408 if (profile != desc->mProfile) {
6409 invalidate = true;
6410 break;
6411 }
6412 }
6413 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006414 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006415
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006416 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006417 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006418 std::to_string(srcOutputs[0]).c_str(),
6419 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006420 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006421 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006422 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006423 if (desc == nullptr) continue;
6424
6425 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006426 setStrategyMute(psId, true, desc);
6427 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006428 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006429 }
François Gaffiec005e562018-11-06 15:04:49 +01006430 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006431 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006432 connectAudioSource(source);
6433 }
Eric Laurente552edb2014-03-10 17:42:56 -07006434 }
6435
François Gaffiec005e562018-11-06 15:04:49 +01006436 // Move effects associated to this stream from previous output to new output
6437 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006438 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006439 }
François Gaffiec005e562018-11-06 15:04:49 +01006440 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006441 if (invalidate) {
6442 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6443 mpClientInterface->invalidateStream(stream);
6444 }
jiabin49256852022-03-09 11:21:35 -08006445 for (audio_io_handle_t srcOut : srcOutputs) {
6446 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6447 if (desc == nullptr) continue;
6448
6449 desc->setTracksInvalidatedStatusByStrategy(psId);
6450 }
Eric Laurente552edb2014-03-10 17:42:56 -07006451 }
6452 }
6453}
6454
Eric Laurente0720872014-03-11 09:30:41 -07006455void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006456{
François Gaffiec005e562018-11-06 15:04:49 +01006457 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6458 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6459 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006460 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006461 }
Eric Laurente552edb2014-03-10 17:42:56 -07006462}
6463
Kevin Rocard153f92d2018-12-18 18:33:28 -08006464void AudioPolicyManager::checkSecondaryOutputs() {
6465 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006466 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006467 for (size_t i = 0; i < mOutputs.size(); i++) {
6468 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6469 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006470 sp<AudioPolicyMix> primaryMix;
6471 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006472 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6473 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006474 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6475 for (auto &secondaryMix : secondaryMixes) {
6476 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6477 if (outputDesc != nullptr &&
6478 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6479 secondaryDescs.push_back(outputDesc);
6480 }
6481 }
6482
jiabin10a03f12021-05-07 23:46:28 +00006483 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006484 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006485 } else if (!std::equal(
6486 client->getSecondaryOutputs().begin(),
6487 client->getSecondaryOutputs().end(),
6488 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006489 if (!audio_is_linear_pcm(client->config().format)) {
6490 // If the format is not PCM, the tracks should be invalidated to get correct
6491 // behavior when the secondary output is changed.
6492 streamsToInvalidate.insert(client->stream());
6493 } else {
6494 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6495 std::vector<audio_io_handle_t> secondaryOutputIds;
6496 for (const auto &secondaryDesc: secondaryDescs) {
6497 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6498 weakSecondaryDescs.push_back(secondaryDesc);
6499 }
6500 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6501 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006502 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006503 }
6504 }
6505 }
jiabin10a03f12021-05-07 23:46:28 +00006506 if (!trackSecondaryOutputs.empty()) {
6507 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6508 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006509 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006510 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006511 mpClientInterface->invalidateStream(stream);
6512 }
6513}
6514
Eric Laurent2517af32020-11-25 15:31:27 +01006515bool AudioPolicyManager::isScoRequestedForComm() const {
6516 AudioDeviceTypeAddrVector devices;
6517 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6518 for (const auto &device : devices) {
6519 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6520 return true;
6521 }
6522 }
6523 return false;
6524}
6525
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006526bool AudioPolicyManager::isHearingAidUsedForComm() const {
6527 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6528 true /*fromCache*/);
6529 for (const auto &device : devices) {
6530 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6531 return true;
6532 }
6533 }
6534 return false;
6535}
6536
6537
Eric Laurente0720872014-03-11 09:30:41 -07006538void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006539{
François Gaffie53615e22015-03-19 09:24:12 +01006540 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006541 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006542 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006543 return;
6544 }
6545
Eric Laurent3a4311c2014-03-17 12:00:47 -07006546 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006547 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6548 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006549 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006550
6551 // if suspended, restore A2DP output if:
6552 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006553 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006554 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006555 //
Eric Laurentf732e072016-08-03 19:30:28 -07006556 // if not suspended, suspend A2DP output if:
6557 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006558 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006559 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006560 //
6561 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006562 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006563 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006564 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006565 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006566
6567 mpClientInterface->restoreOutput(a2dpOutput);
6568 mA2dpSuspended = false;
6569 }
6570 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006571 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006572 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006573 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006574 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006575
6576 mpClientInterface->suspendOutput(a2dpOutput);
6577 mA2dpSuspended = true;
6578 }
6579 }
6580}
6581
François Gaffie11d30102018-11-02 16:09:09 +01006582DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6583 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006584{
François Gaffie11d30102018-11-02 16:09:09 +01006585 DeviceVector devices;
6586
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006587 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006588 if (index >= 0) {
6589 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006590 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006591 ALOGV("%s device %s forced by patch %d", __func__,
6592 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6593 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006594 }
6595 }
6596
Dean Wheatley514b4312020-06-17 21:45:00 +10006597 // Do not retrieve engine device for outputs through MSD
6598 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6599 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6600 return outputDesc->devices();
6601 }
6602
Eric Laurent97ac8712018-07-27 18:59:02 -07006603 // Honor explicit routing requests only if no client using default routing is active on this
6604 // input: a specific app can not force routing for other apps by setting a preferred device.
6605 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006606 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006607 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006608 if (device != nullptr) {
6609 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006610 }
6611
François Gaffiea807ef92018-11-05 10:44:33 +01006612 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6613 // of setForceUse / Default Bus device here
6614 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6615 if (device != nullptr) {
6616 return DeviceVector(device);
6617 }
6618
François Gaffiec005e562018-11-06 15:04:49 +01006619 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6620 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6621 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306622 auto hasStreamActive = [&](auto stream) {
6623 return hasStream(streams, stream) && isStreamActive(stream, 0);
6624 };
Eric Laurent484e9272018-06-07 17:29:23 -07006625
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306626 auto doGetOutputDevicesForVoice = [&]() {
6627 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006628 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306629 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006630 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6631 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306632 };
6633
6634 // With low-latency playing on speaker, music on WFD, when the first low-latency
6635 // output is stopped, getNewOutputDevices checks for a product strategy
6636 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006637 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306638 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6639 // stream is associated to the output descriptor.
6640 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6641 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6642 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6643 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006644 // Retrieval of devices for voice DL is done on primary output profile, cannot
6645 // check the route (would force modifying configuration file for this profile)
6646 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6647 break;
6648 }
Eric Laurente552edb2014-03-10 17:42:56 -07006649 }
François Gaffiec005e562018-11-06 15:04:49 +01006650 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006651 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006652}
6653
François Gaffie11d30102018-11-02 16:09:09 +01006654sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6655 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006656{
François Gaffie11d30102018-11-02 16:09:09 +01006657 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006658
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006659 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006660 if (index >= 0) {
6661 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006662 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006663 ALOGV("getNewInputDevice() device %s forced by patch %d",
6664 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6665 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006666 }
6667 }
6668
Eric Laurent97ac8712018-07-27 18:59:02 -07006669 // Honor explicit routing requests only if no client using default routing is active on this
6670 // input: a specific app can not force routing for other apps by setting a preferred device.
6671 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006672 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6673 if (device != nullptr) {
6674 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006675 }
6676
Eric Laurentdc95a252018-04-12 12:46:56 -07006677 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006678 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006679 audio_attributes_t attributes;
6680 uid_t uid;
6681 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6682 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006683 attributes = topClient->attributes();
6684 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006685 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006686 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6687 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006688 }
6689
Francois Gaffie716e1432019-01-14 16:58:59 +01006690 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6691 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006692 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006693 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006694 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006695 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006696
Eric Laurente552edb2014-03-10 17:42:56 -07006697 return device;
6698}
6699
Eric Laurent794fde22016-03-11 09:50:45 -08006700bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6701 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006702 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006703}
6704
Dorin Drimusf2196d82022-01-03 12:11:18 +01006705// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006706status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006707 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006708 if (devices == nullptr) {
6709 return BAD_VALUE;
6710 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006711
6712 // Devices are determined in the following precedence:
6713 //
6714 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6715 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6716 //
6717 // If no such dynamic policy then
6718 // 2) Devices containing an active client using setPreferredDevice
6719 // with same strategy as the attributes.
6720 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6721 //
6722 // If no corresponding active client with setPreferredDevice then
6723 // 3) Devices associated with the strategy determined by the attributes
6724 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6725 //
6726 // See related getOutputForAttrInt().
6727
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006728 // check dynamic policies but only for primary descriptors (secondary not used for audible
6729 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006730 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006731 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6732 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006733 if (status != OK) {
6734 return status;
6735 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006736
6737 DeviceVector curDevices;
6738 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6739 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6740 // as they are unaffected by device/stream volume
6741 // (per SwAudioOutputDescriptor::isFixedVolume()).
6742 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6743 ) {
6744 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6745 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6746 curDevices.add(deviceDesc);
6747 } else {
6748 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6749 // which selects setPreferredDevice if active. This means forVolume call
6750 // will take an active setPreferredDevice, if such exists.
6751
6752 curDevices = mEngine->getOutputDevicesForAttributes(
6753 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006754 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006755
6756 if (forVolume) {
6757 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6758 // for single volume control in AudioService (such relationship should exist if
6759 // SPEAKER_SAFE is present).
6760 //
6761 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6762 DeviceVector speakerSafeDevices =
6763 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6764 if (!speakerSafeDevices.isEmpty()) {
6765 curDevices.merge(
6766 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6767 curDevices.remove(speakerSafeDevices);
6768 }
6769 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006770 for (const auto& device : curDevices) {
6771 devices->push_back(device->getDeviceTypeAddr());
6772 }
6773 return NO_ERROR;
6774}
6775
Eric Laurente0720872014-03-11 09:30:41 -07006776void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006777 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006778 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006779 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006780 updateDevicesAndOutputs();
6781 break;
6782 default:
6783 break;
6784 }
6785}
6786
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006787uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006788
6789 // skip beacon mute management if a dedicated TTS output is available
6790 if (mTtsOutputAvailable) {
6791 return 0;
6792 }
6793
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006794 switch(event) {
6795 case STARTING_OUTPUT:
6796 mBeaconMuteRefCount++;
6797 break;
6798 case STOPPING_OUTPUT:
6799 if (mBeaconMuteRefCount > 0) {
6800 mBeaconMuteRefCount--;
6801 }
6802 break;
6803 case STARTING_BEACON:
6804 mBeaconPlayingRefCount++;
6805 break;
6806 case STOPPING_BEACON:
6807 if (mBeaconPlayingRefCount > 0) {
6808 mBeaconPlayingRefCount--;
6809 }
6810 break;
6811 }
6812
6813 if (mBeaconMuteRefCount > 0) {
6814 // any playback causes beacon to be muted
6815 return setBeaconMute(true);
6816 } else {
6817 // no other playback: unmute when beacon starts playing, mute when it stops
6818 return setBeaconMute(mBeaconPlayingRefCount == 0);
6819 }
6820}
6821
6822uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6823 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6824 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6825 // keep track of muted state to avoid repeating mute/unmute operations
6826 if (mBeaconMuted != mute) {
6827 // mute/unmute AUDIO_STREAM_TTS on all outputs
6828 ALOGV("\t muting %d", mute);
6829 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006830 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6831 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6832 ALOGV("\t no tts volume source available");
6833 return 0;
6834 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006835 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006836 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006837 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006838 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006839 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006840 maxLatency = latency;
6841 }
6842 }
6843 mBeaconMuted = mute;
6844 return maxLatency;
6845 }
6846 return 0;
6847}
6848
Eric Laurente0720872014-03-11 09:30:41 -07006849void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006850{
François Gaffiec005e562018-11-06 15:04:49 +01006851 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006852 mPreviousOutputs = mOutputs;
6853}
6854
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006855uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006856 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006857 uint32_t delayMs)
6858{
6859 // mute/unmute strategies using an incompatible device combination
6860 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6861 // if unmuting, unmute only after the specified delay
6862 if (outputDesc->isDuplicated()) {
6863 return 0;
6864 }
6865
6866 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006867 DeviceVector devices = outputDesc->devices();
6868 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006869
François Gaffiec005e562018-11-06 15:04:49 +01006870 auto productStrategies = mEngine->getOrderedProductStrategies();
6871 for (const auto &productStrategy : productStrategies) {
6872 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6873 DeviceVector curDevices =
6874 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6875 curDevices = curDevices.filter(outputDesc->supportedDevices());
6876 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006877 bool doMute = false;
6878
François Gaffiec005e562018-11-06 15:04:49 +01006879 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006880 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006881 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6882 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006883 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006884 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006885 }
Eric Laurent99401132014-05-07 19:48:15 -07006886 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006887 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006888 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006889 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006890 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006891 continue;
6892 }
François Gaffiec005e562018-11-06 15:04:49 +01006893 ALOGVV("%s() %s (curDevice %s)", __func__,
6894 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6895 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6896 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006897 if (mute) {
6898 // FIXME: should not need to double latency if volume could be applied
6899 // immediately by the audioflinger mixer. We must account for the delay
6900 // between now and the next time the audioflinger thread for this output
6901 // will process a buffer (which corresponds to one buffer size,
6902 // usually 1/2 or 1/4 of the latency).
6903 if (muteWaitMs < desc->latency() * 2) {
6904 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006905 }
6906 }
6907 }
6908 }
6909 }
6910 }
6911
Eric Laurent99401132014-05-07 19:48:15 -07006912 // temporary mute output if device selection changes to avoid volume bursts due to
6913 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006914 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006915 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006916
Eric Laurentdc462862016-07-19 12:29:53 -07006917 if (muteWaitMs < tempMuteWaitMs) {
6918 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006919 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006920
6921 // If recommended duration is defined, replace temporary mute duration to avoid
6922 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6923 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6924 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6925 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6926 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6927
François Gaffieaaac0fd2018-11-22 17:56:39 +01006928 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6929 // make sure that we do not start the temporary mute period too early in case of
6930 // delayed device change
6931 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6932 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006933 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006934 }
6935 }
6936
Eric Laurente552edb2014-03-10 17:42:56 -07006937 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6938 if (muteWaitMs > delayMs) {
6939 muteWaitMs -= delayMs;
6940 usleep(muteWaitMs * 1000);
6941 return muteWaitMs;
6942 }
6943 return 0;
6944}
6945
François Gaffie11d30102018-11-02 16:09:09 +01006946uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6947 const DeviceVector &devices,
6948 bool force,
6949 int delayMs,
6950 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006951 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006952{
François Gaffie11d30102018-11-02 16:09:09 +01006953 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006954 uint32_t muteWaitMs;
6955
6956 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006957 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6958 nullptr /* patchHandle */, requiresMuteCheck);
6959 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6960 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006961 return muteWaitMs;
6962 }
Eric Laurente552edb2014-03-10 17:42:56 -07006963
6964 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006965 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006966 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006967 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006968
François Gaffie11d30102018-11-02 16:09:09 +01006969 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6970
6971 if (!filteredDevices.isEmpty()) {
6972 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006973 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006974
6975 // if the outputs are not materially active, there is no need to mute.
6976 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006977 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006978 } else {
6979 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6980 muteWaitMs = 0;
6981 }
Eric Laurente552edb2014-03-10 17:42:56 -07006982
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006983 bool outputRouted = outputDesc->isRouted();
6984
Eric Laurent79ea9582020-06-11 18:49:24 -07006985 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6986 // output profile or if new device is not supported AND previous device(s) is(are) still
6987 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006988 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006989 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6990 // restore previous device after evaluating strategy mute state
6991 outputDesc->setDevices(prevDevices);
6992 return muteWaitMs;
6993 }
6994
Eric Laurente552edb2014-03-10 17:42:56 -07006995 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006996 // the requested device is AUDIO_DEVICE_NONE
6997 // OR the requested device is the same as current device
6998 // AND force is not specified
6999 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007000 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007001 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007002 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7003 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007004 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7005 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7006 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7007 }
Eric Laurente552edb2014-03-10 17:42:56 -07007008 return muteWaitMs;
7009 }
7010
François Gaffie11d30102018-11-02 16:09:09 +01007011 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007012
Eric Laurente552edb2014-03-10 17:42:56 -07007013 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007014 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007015 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007016 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007017 PatchBuilder patchBuilder;
7018 patchBuilder.addSource(outputDesc);
7019 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7020 for (const auto &filteredDevice : filteredDevices) {
7021 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007022 }
7023
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007024 // Add half reported latency to delayMs when muteWaitMs is null in order
7025 // to avoid disordered sequence of muting volume and changing devices.
7026 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7027 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 }
Eric Laurente552edb2014-03-10 17:42:56 -07007029
7030 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007031 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007032
7033 return muteWaitMs;
7034}
7035
Eric Laurentc75307b2015-03-17 15:29:32 -07007036status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007037 int delayMs,
7038 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007039{
Eric Laurent6a94d692014-05-20 11:18:06 -07007040 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007041 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7042 return INVALID_OPERATION;
7043 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007044 if (patchHandle) {
7045 index = mAudioPatches.indexOfKey(*patchHandle);
7046 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007047 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007048 }
7049 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007050 return INVALID_OPERATION;
7051 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007052 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007053 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007054 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007055 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007056 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007057 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007058 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007059 return status;
7060}
7061
7062status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007063 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007064 bool force,
7065 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007066{
7067 status_t status = NO_ERROR;
7068
Eric Laurent1f2f2232014-06-02 12:01:23 -07007069 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007070 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7071 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007072
François Gaffie11d30102018-11-02 16:09:09 +01007073 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007074 PatchBuilder patchBuilder;
7075 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007076 // AUDIO_SOURCE_HOTWORD is for internal use only:
7077 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007078 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7079 auto result = usecase;
7080 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7081 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7082 }
7083 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007084 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007085 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007086 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007087 }
7088 }
7089 return status;
7090}
7091
Eric Laurent6a94d692014-05-20 11:18:06 -07007092status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7093 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007094{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007095 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007096 ssize_t index;
7097 if (patchHandle) {
7098 index = mAudioPatches.indexOfKey(*patchHandle);
7099 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007100 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007101 }
7102 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007103 return INVALID_OPERATION;
7104 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007105 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007106 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007107 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007108 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007109 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007110 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007111 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007112 return status;
7113}
7114
François Gaffie11d30102018-11-02 16:09:09 +01007115sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007116 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007117 audio_format_t& format,
7118 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007119 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007120{
7121 // Choose an input profile based on the requested capture parameters: select the first available
7122 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007123 //
7124 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7125 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007126
Glenn Kasten730b9262018-03-29 15:01:26 -07007127 sp<IOProfile> firstInexact;
7128 uint32_t updatedSamplingRate = 0;
7129 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7130 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007131 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007132 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007133 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007134 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007135 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007136 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007137 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007138 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007139 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007140 &channelMask /*updatedChannelMask*/,
7141 // FIXME ugly cast
7142 (audio_output_flags_t) flags,
7143 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007144 return profile;
7145 }
François Gaffie11d30102018-11-02 16:09:09 +01007146 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007147 samplingRate,
7148 &updatedSamplingRate,
7149 format,
7150 &updatedFormat,
7151 channelMask,
7152 &updatedChannelMask,
7153 // FIXME ugly cast
7154 (audio_output_flags_t) flags,
7155 false /*exactMatchRequiredForInputFlags*/)) {
7156 firstInexact = profile;
7157 }
7158
Eric Laurente552edb2014-03-10 17:42:56 -07007159 }
7160 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007161 if (firstInexact != nullptr) {
7162 samplingRate = updatedSamplingRate;
7163 format = updatedFormat;
7164 channelMask = updatedChannelMask;
7165 return firstInexact;
7166 }
Eric Laurente552edb2014-03-10 17:42:56 -07007167 return NULL;
7168}
7169
François Gaffieaaac0fd2018-11-22 17:56:39 +01007170float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7171 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007172 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007173 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007174{
jiabin9a3361e2019-10-01 09:38:30 -07007175 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007176
7177 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7178 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7179 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7180 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007181 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7182 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7183 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7184 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7185 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007186
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007187 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007188 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7189 mOutputs.isActive(ringVolumeSrc, 0)) {
7190 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007191 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007192 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007193 }
7194
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007195 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007196 if ((volumeSource != callVolumeSrc && (isInCall() ||
7197 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007198 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007199 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7200 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007201 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7202 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7203 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007204 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007205 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007206 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007207 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007208 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007209 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007210 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7211 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7212 // programmatically muted.
7213 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7214 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7215 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007216 bool exemptFromCapping =
7217 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7218 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007219 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7220 volumeSource, volumeDb);
7221 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007222 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7223 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7224 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007225 }
7226 }
Eric Laurente552edb2014-03-10 17:42:56 -07007227 // if a headset is connected, apply the following rules to ring tones and notifications
7228 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007229 // - always attenuate notifications volume by 6dB
7230 // - attenuate ring tones volume by 6dB unless music is not playing and
7231 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007232 // - if music is playing, always limit the volume to current music volume,
7233 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007234 if (!Intersection(deviceTypes,
7235 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7236 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007237 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7238 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007239 ((volumeSource == alarmVolumeSrc ||
7240 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007241 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7242 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7243 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007244 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7245 curves.canBeMuted()) {
7246
Eric Laurente552edb2014-03-10 17:42:56 -07007247 // when the phone is ringing we must consider that music could have been paused just before
7248 // by the music application and behave as if music was active if the last music track was
7249 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007250 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007251 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007252 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007253 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007254 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7255 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007256 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007257 float musicVolDb = computeVolume(musicCurves,
7258 musicVolumeSrc,
7259 musicCurves.getVolumeIndex(musicDevice),
7260 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007261 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7262 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7263 if (volumeDb > minVolDb) {
7264 volumeDb = minVolDb;
7265 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007266 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007267 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7268 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7269 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007270 // on A2DP, also ensure notification volume is not too low compared to media when
7271 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007272 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007273 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007274 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7275 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007276 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7277 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007278 }
7279 }
jiabin9a3361e2019-10-01 09:38:30 -07007280 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007281 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007282 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007283 }
7284 }
7285
François Gaffie43c73442018-11-08 08:21:55 +01007286 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007287}
7288
Eric Laurent3839bc02018-07-10 18:33:34 -07007289int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007290 VolumeSource fromVolumeSource,
7291 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007292{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007293 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007294 return srcIndex;
7295 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007296 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7297 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007298 float minSrc = (float)srcCurves.getVolumeIndexMin();
7299 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7300 float minDst = (float)dstCurves.getVolumeIndexMin();
7301 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007302
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007303 // preserve mute request or correct range
7304 if (srcIndex < minSrc) {
7305 if (srcIndex == 0) {
7306 return 0;
7307 }
7308 srcIndex = minSrc;
7309 } else if (srcIndex > maxSrc) {
7310 srcIndex = maxSrc;
7311 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007312 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7313}
7314
François Gaffieaaac0fd2018-11-22 17:56:39 +01007315status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7316 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007317 int index,
7318 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007319 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007320 int delayMs,
7321 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007322{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007323 // do not change actual attributes volume if the attributes is muted
7324 if (outputDesc->isMuted(volumeSource)) {
7325 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7326 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007327 return NO_ERROR;
7328 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007329 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7330 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7331 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7332 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007333
Eric Laurent2517af32020-11-25 15:31:27 +01007334 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007335 bool isHAUsed = isHearingAidUsedForComm();
7336
Eric Laurente552edb2014-03-10 17:42:56 -07007337 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007338 // if sco and call follow same curves, bypass forceUseForComm
7339 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007340 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007341 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007342 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007343 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007344 // Do not return an error here as AudioService will always set both voice call
7345 // and bluetooth SCO volumes due to stream aliasing.
7346 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007347 }
jiabin9a3361e2019-10-01 09:38:30 -07007348 if (deviceTypes.empty()) {
7349 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007350 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007351
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007352 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7353 ALOGE("invalid volume index range");
7354 return BAD_VALUE;
7355 }
7356
jiabin9a3361e2019-10-01 09:38:30 -07007357 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7358 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007359 // Force VoIP volume to max for bluetooth SCO device except if muted
7360 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007361 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007362 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007363 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007364 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007365 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007366 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007367
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007368 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007369 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007370 // 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 +01007371 if (isVoiceVolSrc) {
7372 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007373 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007374 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007375 }
Eric Laurent18fba842016-03-31 14:41:26 -07007376 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007377 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7378 mLastVoiceVolume = voiceVolume;
7379 }
7380 }
Eric Laurente552edb2014-03-10 17:42:56 -07007381 return NO_ERROR;
7382}
7383
Eric Laurentc75307b2015-03-17 15:29:32 -07007384void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007385 const DeviceTypeSet& deviceTypes,
7386 int delayMs,
7387 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007388{
jiabincd510522020-01-22 09:40:55 -08007389 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007390 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7391 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7392 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007393 curves.getVolumeIndex(deviceTypes),
7394 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007395 }
7396}
7397
François Gaffiec005e562018-11-06 15:04:49 +01007398void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7399 bool on,
7400 const sp<AudioOutputDescriptor>& outputDesc,
7401 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007402 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007403{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007404 std::vector<VolumeSource> sourcesToMute;
7405 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7406 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7407 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007408 VolumeSource source = toVolumeSource(attributes, false);
7409 if ((source != VOLUME_SOURCE_NONE) &&
7410 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7411 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007412 sourcesToMute.push_back(source);
7413 }
Eric Laurente552edb2014-03-10 17:42:56 -07007414 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007415 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007416 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007417 }
7418
Eric Laurente552edb2014-03-10 17:42:56 -07007419}
7420
François Gaffieaaac0fd2018-11-22 17:56:39 +01007421void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7422 bool on,
7423 const sp<AudioOutputDescriptor>& outputDesc,
7424 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007425 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007426{
jiabin9a3361e2019-10-01 09:38:30 -07007427 if (deviceTypes.empty()) {
7428 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007429 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007430 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007431 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007432 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007433 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007434 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007435 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7436 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007437 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007438 }
7439 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007440 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7441 // ignored
7442 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007443 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007444 if (!outputDesc->isMuted(volumeSource)) {
7445 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007446 return;
7447 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007448 if (outputDesc->decMuteCount(volumeSource) == 0) {
7449 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007450 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007451 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007452 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007453 delayMs);
7454 }
7455 }
7456}
7457
François Gaffie53615e22015-03-19 09:24:12 +01007458bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7459{
François Gaffiec005e562018-11-06 15:04:49 +01007460 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007461 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7462 return true;
7463 }
7464
7465 // has known usage?
7466 switch (paa->usage) {
7467 case AUDIO_USAGE_UNKNOWN:
7468 case AUDIO_USAGE_MEDIA:
7469 case AUDIO_USAGE_VOICE_COMMUNICATION:
7470 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7471 case AUDIO_USAGE_ALARM:
7472 case AUDIO_USAGE_NOTIFICATION:
7473 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7474 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7475 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7476 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7477 case AUDIO_USAGE_NOTIFICATION_EVENT:
7478 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7479 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7480 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7481 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007482 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007483 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007484 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007485 case AUDIO_USAGE_EMERGENCY:
7486 case AUDIO_USAGE_SAFETY:
7487 case AUDIO_USAGE_VEHICLE_STATUS:
7488 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007489 break;
7490 default:
7491 return false;
7492 }
7493 return true;
7494}
7495
François Gaffie2110e042015-03-24 08:41:51 +01007496audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7497{
7498 return mEngine->getForceUse(usage);
7499}
7500
Eric Laurent96d1dda2022-03-14 17:14:19 +01007501bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007502 return isStateInCall(mEngine->getPhoneState());
7503}
7504
Eric Laurent96d1dda2022-03-14 17:14:19 +01007505bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007506 return is_state_in_call(state);
7507}
7508
Eric Laurent74b71512019-11-06 17:21:57 -08007509bool AudioPolicyManager::isCallAudioAccessible()
7510{
7511 audio_mode_t mode = mEngine->getPhoneState();
7512 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007513 || (mode == AUDIO_MODE_CALL_SCREEN)
7514 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007515}
7516
Eric Laurentd60560a2015-04-10 11:31:20 -07007517void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7518{
7519 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007520 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007521 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007522 sourceDesc->sinkDevice()->equals(deviceDesc))
7523 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007524 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007525 }
7526 }
7527
7528 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7529 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7530 bool release = false;
7531 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7532 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7533 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7534 source->ext.device.type == deviceDesc->type()) {
7535 release = true;
7536 }
7537 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007538 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007539 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7540 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7541 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007542 sink->ext.device.type == deviceDesc->type() &&
7543 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7544 || strncmp(sink->ext.device.address, address,
7545 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007546 release = true;
7547 }
7548 }
7549 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007550 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7551 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007552 }
7553 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007554
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007555 mInputs.clearSessionRoutesForDevice(deviceDesc);
7556
Francois Gaffie716e1432019-01-14 16:58:59 +01007557 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007558}
7559
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007560void AudioPolicyManager::modifySurroundFormats(
7561 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007562 std::unordered_set<audio_format_t> enforcedSurround(
7563 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007564 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7565 for (const auto& pair : mConfig.getSurroundFormats()) {
7566 allSurround.insert(pair.first);
7567 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7568 }
Phil Burk09bc4612016-02-24 15:58:15 -08007569
7570 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7571 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007572 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007573 // This is the resulting set of formats depending on the surround mode:
7574 // 'all surround' = allSurround
7575 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7576 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7577 // 'manual surround' = mManualSurroundFormats
7578 // AUTO: formats v 'enforced surround'
7579 // ALWAYS: formats v 'all surround' v 'enforced surround'
7580 // NEVER: formats ^ 'non-surround'
7581 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007582
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007583 std::unordered_set<audio_format_t> formatSet;
7584 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7585 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007586 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007587 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007588 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007589 formatSet.insert(*formatIter);
7590 }
7591 }
7592 } else {
7593 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7594 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007595 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007596
jiabin81772902018-04-02 17:52:27 -07007597 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007598 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007599 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7600 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7601 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007602 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007603 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7604 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7605 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007606 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007608 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007609 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007610 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007611 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007612}
7613
jiabin06e4bab2019-07-29 10:13:34 -07007614void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7615 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007616 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7617 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7618
7619 // If NEVER, then remove support for channelMasks > stereo.
7620 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007621 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7622 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007623 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007624 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007625 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007626 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007627 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007628 }
7629 }
jiabin81772902018-04-02 17:52:27 -07007630 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7631 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7632 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007633 bool supports5dot1 = false;
7634 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007635 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007636 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7637 supports5dot1 = true;
7638 break;
7639 }
7640 }
7641 // If not then add 5.1 support.
7642 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007643 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007644 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007645 }
Phil Burk09bc4612016-02-24 15:58:15 -08007646 }
7647}
7648
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007649void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007650 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007651 AudioProfileVector &profiles)
7652{
7653 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007654 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007655
François Gaffie112b0af2015-11-19 16:13:25 +01007656 // Format MUST be checked first to update the list of AudioProfile
7657 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007658 reply = mpClientInterface->getParameters(
7659 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007660 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007661 AudioParameter repliedParameters(reply);
7662 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007663 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007664 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7665 return;
7666 }
Phil Burk09bc4612016-02-24 15:58:15 -08007667 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007668 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007669 if (device == AUDIO_DEVICE_OUT_HDMI
7670 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007671 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007672 }
jiabin3e277cc2019-09-10 14:27:34 -07007673 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007674 }
François Gaffie112b0af2015-11-19 16:13:25 +01007675
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007676 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007677 ChannelMaskSet channelMasks;
7678 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007679 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007680 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007681
7682 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007683 reply = mpClientInterface->getParameters(
7684 ioHandle,
7685 requestedParameters.toString() + ";" +
7686 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007687 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007688 AudioParameter repliedParameters(reply);
7689 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007690 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007691 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007692 }
7693 }
7694 if (profiles.hasDynamicChannelsFor(format)) {
7695 reply = mpClientInterface->getParameters(ioHandle,
7696 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007697 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007698 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007699 AudioParameter repliedParameters(reply);
7700 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007701 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007702 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007703 if (device == AUDIO_DEVICE_OUT_HDMI
7704 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007705 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007706 }
François Gaffie112b0af2015-11-19 16:13:25 +01007707 }
7708 }
jiabin3e277cc2019-09-10 14:27:34 -07007709 addDynamicAudioProfileAndSort(
7710 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007711 }
7712}
Eric Laurentd60560a2015-04-10 11:31:20 -07007713
Mikhail Naganovdc769682018-05-04 15:34:08 -07007714status_t AudioPolicyManager::installPatch(const char *caller,
7715 audio_patch_handle_t *patchHandle,
7716 AudioIODescriptorInterface *ioDescriptor,
7717 const struct audio_patch *patch,
7718 int delayMs)
7719{
7720 ssize_t index = mAudioPatches.indexOfKey(
7721 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7722 *patchHandle : ioDescriptor->getPatchHandle());
7723 sp<AudioPatch> patchDesc;
7724 status_t status = installPatch(
7725 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7726 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007727 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007728 }
7729 return status;
7730}
7731
7732status_t AudioPolicyManager::installPatch(const char *caller,
7733 ssize_t index,
7734 audio_patch_handle_t *patchHandle,
7735 const struct audio_patch *patch,
7736 int delayMs,
7737 uid_t uid,
7738 sp<AudioPatch> *patchDescPtr)
7739{
7740 sp<AudioPatch> patchDesc;
7741 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7742 if (index >= 0) {
7743 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007744 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007745 }
7746
7747 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7748 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7749 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7750 if (status == NO_ERROR) {
7751 if (index < 0) {
7752 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007753 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007754 } else {
7755 patchDesc->mPatch = *patch;
7756 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007757 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007758 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007759 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007760 }
7761 nextAudioPortGeneration();
7762 mpClientInterface->onAudioPatchListUpdate();
7763 }
7764 if (patchDescPtr) *patchDescPtr = patchDesc;
7765 return status;
7766}
7767
jiabinbce0c1d2020-10-05 11:20:18 -07007768bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7769{
7770 const TrackClientVector activeClients = output->getActiveClients();
7771 if (activeClients.empty()) {
7772 return true;
7773 }
7774 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7775 if (index < 0) {
7776 ALOGE("%s, no audio patch found while there are active clients on output %d",
7777 __func__, output->getId());
7778 return false;
7779 }
7780 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7781 DeviceVector routedDevices;
7782 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7783 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7784 patchDesc->mPatch.sinks[i].id);
7785 if (device == nullptr) {
7786 ALOGE("%s, no audio device found with id(%d)",
7787 __func__, patchDesc->mPatch.sinks[i].id);
7788 return false;
7789 }
7790 routedDevices.add(device);
7791 }
7792 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007793 if (client->isInvalid()) {
7794 // No need to take care about invalidated clients.
7795 continue;
7796 }
jiabinbce0c1d2020-10-05 11:20:18 -07007797 sp<DeviceDescriptor> preferredDevice =
7798 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7799 if (mEngine->getOutputDevicesForAttributes(
7800 client->attributes(), preferredDevice, false) == routedDevices) {
7801 return false;
7802 }
7803 }
7804 return true;
7805}
7806
7807sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007808 const sp<IOProfile>& profile, const DeviceVector& devices,
7809 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007810{
7811 for (const auto& device : devices) {
7812 // TODO: This should be checking if the profile supports the device combo.
7813 if (!profile->supportsDevice(device)) {
7814 return nullptr;
7815 }
7816 }
7817 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7818 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007819 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007820 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7821 if (status != NO_ERROR) {
7822 return nullptr;
7823 }
7824
7825 // Here is where the out_set_parameters() for card & device gets called
7826 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7827 const audio_devices_t deviceType = device->type();
7828 const String8 &address = String8(device->address().c_str());
7829 if (!address.isEmpty()) {
7830 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7831 mpClientInterface->setParameters(output, String8(param));
7832 free(param);
7833 }
7834 updateAudioProfiles(device, output, profile->getAudioProfiles());
7835 if (!profile->hasValidAudioProfile()) {
7836 ALOGW("%s() missing param", __func__);
7837 desc->close();
7838 return nullptr;
7839 } else if (profile->hasDynamicAudioProfile()) {
7840 desc->close();
7841 output = AUDIO_IO_HANDLE_NONE;
7842 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7843 profile->pickAudioProfile(
7844 config.sample_rate, config.channel_mask, config.format);
7845 config.offload_info.sample_rate = config.sample_rate;
7846 config.offload_info.channel_mask = config.channel_mask;
7847 config.offload_info.format = config.format;
7848
Eric Laurentb4f42a92022-01-17 17:37:31 +01007849 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007850 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7851 if (status != NO_ERROR) {
7852 return nullptr;
7853 }
7854 }
7855
7856 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007857
baek.kim -61c20122022-07-27 10:05:32 +00007858 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7859 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7860
jiabinbce0c1d2020-10-05 11:20:18 -07007861 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7862 sp<AudioPolicyMix> policyMix;
7863 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7864 policyMix->setOutput(desc);
7865 desc->mPolicyMix = policyMix;
7866 } else {
7867 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7868 address.string());
7869 }
7870
baek.kim -61c20122022-07-27 10:05:32 +00007871 } else if (hasPrimaryOutput() && speaker != nullptr
7872 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007873 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7874 // no duplicated output for:
7875 // - direct outputs
7876 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007877 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007878 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7879
7880 //TODO: configure audio effect output stage here
7881
7882 // open a duplicating output thread for the new output and the primary output
7883 sp<SwAudioOutputDescriptor> dupOutputDesc =
7884 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7885 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7886 if (status == NO_ERROR) {
7887 // add duplicated output descriptor
7888 addOutput(duplicatedOutput, dupOutputDesc);
7889 } else {
7890 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7891 mPrimaryOutput->mIoHandle, output);
7892 desc->close();
7893 removeOutput(output);
7894 nextAudioPortGeneration();
7895 return nullptr;
7896 }
7897 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007898 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7899 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7900 mPrimaryOutput = desc;
7901 }
jiabinbce0c1d2020-10-05 11:20:18 -07007902 return desc;
7903}
7904
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007905} // namespace android