blob: 6536e9061261c3c9da2943e3f96f8f6520c40103 [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
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
117 media::AudioPort aidlPort;
118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 audio_port_v7 devicePort;
131 device->toAudioPort(&devicePort);
132 if (status_t status = mpClientInterface->setDeviceConnectedState(
133 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
134 status != OK) {
135 ALOGE("Error %d while setting connected state for device %s", status,
136 device->getDeviceTypeAddr().toString(false).c_str());
137 }
François Gaffie44481e72016-04-20 07:49:57 +0200138}
139
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140status_t AudioPolicyManager::setDeviceConnectionStateInt(
141 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
142 audio_format_t encodedFormat) {
143 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
144 // device_address and device_name are forwarded.
145 if (port.ext.getTag() != AudioPortExt::device) {
146 return BAD_VALUE;
147 }
148 audio_devices_t device_type;
149 std::string device_address;
150 if (status_t status = aidl2legacy_AudioDevice_audio_device(
151 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
152 status != OK) {
153 return status;
154 };
155 const char* device_name = port.name.c_str();
156 // connect/disconnect only 1 device at a time
157 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
158 return BAD_VALUE;
159
160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
161 device_type, device_address.c_str(), device_name, encodedFormat,
162 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
163 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
164}
165
François Gaffie11d30102018-11-02 16:09:09 +0100166status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 const char* device_address,
169 const char* device_name,
170 audio_format_t encodedFormat) {
171 media::AudioPort aidlPort;
172 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
173 status == OK) {
174 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
175 } else {
176 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
177 return status;
178 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179}
Paul McLeane743a472015-01-28 11:07:31 -0800180
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
182 audio_policy_dev_state_t state)
183{
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700186 SortedVector <audio_io_handle_t> outputs;
187
François Gaffie11d30102018-11-02 16:09:09 +0100188 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // save a copy of the opened output descriptors before any output is opened or closed
191 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
192 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100193
194 bool wasLeUnicastActive = isLeUnicastActive();
195
Eric Laurente552edb2014-03-10 17:42:56 -0700196 switch (state)
197 {
198 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800199 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700200 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100201 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700202 return INVALID_OPERATION;
203 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800204 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700205 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200208 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 }
211
François Gaffie44481e72016-04-20 07:49:57 +0200212 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
213 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100214 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200215
François Gaffie11d30102018-11-02 16:09:09 +0100216 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
217 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200218
Francois Gaffie716e1432019-01-14 16:58:59 +0100219 mHwModules.cleanUpForDevice(device);
220
François Gaffie11d30102018-11-02 16:09:09 +0100221 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 return INVALID_OPERATION;
223 }
François Gaffie2110e042015-03-24 08:41:51 +0100224
jiabin1c4794b2020-05-05 10:08:05 -0700225 // Populate encapsulation information when a output device is connected.
226 device->setEncapsulationInfoFromHal(mpClientInterface);
227
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700228 // outputs should never be empty here
229 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
230 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800232
Eric Laurent3ae5f312015-02-03 17:12:08 -0800233 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700234 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700235 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100237 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700238 return INVALID_OPERATION;
239 }
240
François Gaffie11d30102018-11-02 16:09:09 +0100241 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Paul McLeane743a472015-01-28 11:07:31 -0800243 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100244 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100247 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700248
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100249 mOutputs.clearSessionRoutesForDevice(device);
250
François Gaffie11d30102018-11-02 16:09:09 +0100251 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100252
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800253 // Reset active device codec
254 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
255
Kriti Dangef6be8f2020-11-05 11:58:19 +0100256 // remove device from mReportedFormatsMap cache
257 mReportedFormatsMap.erase(device);
258
Eric Laurente552edb2014-03-10 17:42:56 -0700259 } break;
260
261 default:
François Gaffie11d30102018-11-02 16:09:09 +0100262 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700263 return BAD_VALUE;
264 }
265
Eric Laurent736a1022019-03-27 18:28:46 -0700266 // Propagate device availability to Engine
267 setEngineDeviceConnectionState(device, state);
268
Eric Laurentae970022019-01-29 14:25:04 -0800269 // No need to evaluate playback routing when connecting a remote submix
270 // output device used by a dynamic policy of type recorder as no
271 // playback use case is affected.
272 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700273 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800274 for (audio_io_handle_t output : outputs) {
275 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800276 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
277 if (policyMix != nullptr
278 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700279 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800280 doCheckForDeviceAndOutputChanges = false;
281 break;
282 }
283 }
284 }
285
286 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700287 // outputs must be closed after checkOutputForAllStrategies() is executed
288 if (!outputs.isEmpty()) {
289 for (audio_io_handle_t output : outputs) {
290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100291 // close unused outputs after device disconnection or direct outputs that have
292 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200293 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200294 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
295 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200296 (desc->mDirectOpenCount == 0))
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
298 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200299 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 closeOutput(output);
301 }
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
304 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700306 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800307 };
308
309 if (doCheckForDeviceAndOutputChanges) {
310 checkForDeviceAndOutputChanges(checkCloseOutputs);
311 } else {
312 checkCloseOutputs();
313 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100314 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700315 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100316 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700317 const DeviceVector activeMediaDevices =
318 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700319 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700320 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530321 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
322 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100323 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // do not force device change on duplicated output because if device is 0, it will
325 // also force a device 0 for the two outputs it is duplicated to which may override
326 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100327 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100328 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700329 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 // always force when disconnecting (a non-duplicated device)
331 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100332 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 }
jiabinbce0c1d2020-10-05 11:20:18 -0700334 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000335 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700336 desc->supportsDevicesForPlayback(activeMediaDevices)) {
337 // Reopen the output to query the dynamic profiles when there is not active
338 // clients or all active clients will be rerouted. Otherwise, set the flag
339 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
340 // can be reopened to query dynamic profiles when all clients are inactive.
341 if (areAllActiveTracksRerouted(desc)) {
342 outputsToReopen.push_back(mOutputs.keyAt(i));
343 } else {
344 desc->mPendingReopenToQueryProfiles = true;
345 }
346 }
347 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
348 // Clear the flag that previously set for re-querying profiles.
349 desc->mPendingReopenToQueryProfiles = false;
350 }
351 }
352 for (const auto& output : outputsToReopen) {
353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
354 closeOutput(output);
355 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700356 }
357
Eric Laurentd60560a2015-04-10 11:31:20 -0700358 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100359 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700360 }
361
Eric Laurent96d1dda2022-03-14 17:14:19 +0100362 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
363
Eric Laurent72aa32f2014-05-30 18:51:48 -0700364 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700365 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700366 } // end if is output device
367
Eric Laurente552edb2014-03-10 17:42:56 -0700368 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700369 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700371 switch (state)
372 {
373 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700374 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100376 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700377 return INVALID_OPERATION;
378 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700379
380 if (mAvailableInputDevices.add(device) < 0) {
381 return NO_MEMORY;
382 }
383
François Gaffie44481e72016-04-20 07:49:57 +0200384 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
385 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100386 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200387
Eric Laurent0dd51852019-04-19 18:18:58 -0700388 if (checkInputsForDevice(device, state) != NO_ERROR) {
389 mAvailableInputDevices.remove(device);
390
François Gaffie11d30102018-11-02 16:09:09 +0100391 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100392
393 mHwModules.cleanUpForDevice(device);
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 return INVALID_OPERATION;
396 }
397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700402 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700404 return INVALID_OPERATION;
405 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700406
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700408
409 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100410 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700413
414 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100415
416 // remove device from mReportedFormatsMap cache
417 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 default:
François Gaffie11d30102018-11-02 16:09:09 +0100421 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 return BAD_VALUE;
423 }
424
Eric Laurent736a1022019-03-27 18:28:46 -0700425 // Propagate device availability to Engine
426 setEngineDeviceConnectionState(device, state);
427
Eric Laurent0dd51852019-04-19 18:18:58 -0700428 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700429 // As the input device list can impact the output device selection, update
430 // getDeviceForStrategy() cache
431 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700432
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100433 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200434 // Reconnect Audio Source
435 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
436 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
437 checkAudioSourceForAttributes(attributes);
438 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700439 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100440 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700441 }
442
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700444 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700446
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449}
450
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100451status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
452 const char* device_name,
453 media::AudioPort* aidlPort) {
454 DeviceDescriptorBase devDescr(device, device_address);
455 devDescr.setName(device_name);
456 return devDescr.writeToParcelable(aidlPort);
457}
458
Eric Laurent736a1022019-03-27 18:28:46 -0700459void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
460 audio_policy_dev_state_t state) {
461
462 // the Engine does not have to know about remote submix devices used by dynamic audio policies
463 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
464 return;
465 }
466 mEngine->setDeviceConnectionState(device, state);
467}
468
469
Eric Laurente0720872014-03-11 09:30:41 -0700470audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100471 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700472{
Eric Laurent634b7142016-04-20 13:48:02 -0700473 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800474 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
475 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700476 (strlen(device_address) != 0)/*matchAddress*/);
477
478 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100479 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700480 device, device_address);
481 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
482 }
François Gaffie53615e22015-03-19 09:24:12 +0100483
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 DeviceVector *deviceVector;
485
Eric Laurente552edb2014-03-10 17:42:56 -0700486 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700487 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700488 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700489 deviceVector = &mAvailableInputDevices;
490 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100491 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700493 }
Eric Laurent634b7142016-04-20 13:48:02 -0700494
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 return (deviceVector->getDevice(
496 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700497 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800498}
499
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800500status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
501 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 const char *device_name,
503 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504{
505 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700506 String8 reply;
507 AudioParameter param;
508 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
511 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800513 // connect/disconnect only 1 device at a time
514 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700517 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 // Nothing to do: device is not connected
520 return NO_ERROR;
521 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700524 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 // configure codecs.
526 // Handle two specific cases by sending a set parameter to
527 // configure A2DP codecs. No need to toggle device state.
528 // Case 1: A2DP active device switches from primary to primary
529 // module
530 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200531 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700532 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
534 if (availablePrimaryOutputDevices().contains(devDesc) &&
535 (module != 0 && module->getHandle() == primaryHandle)) {
536 reply = mpClientInterface->getParameters(
537 AUDIO_IO_HANDLE_NONE,
538 String8(AudioParameter::keyReconfigA2dpSupported));
539 AudioParameter repliedParameters(reply);
540 repliedParameters.getInt(
541 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
542 if (isReconfigA2dpSupported) {
543 const String8 key(AudioParameter::keyReconfigA2dp);
544 param.add(key, String8("true"));
545 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
546 devDesc->setEncodedFormat(encodedFormat);
547 return NO_ERROR;
548 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700549 }
550 }
cnx421bd2dcc42020-07-11 14:58:44 +0800551 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
552 for (size_t i = 0; i < mOutputs.size(); i++) {
553 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
554 // mute media strategies and delay device switch by the largest
555 // This avoid sending the music tail into the earpiece or headset.
556 setStrategyMute(musicStrategy, true, desc);
557 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
558 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
559 nullptr, true /*fromCache*/).types());
560 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561 // Toggle the device state: UNAVAILABLE -> AVAILABLE
562 // This will force reading again the device configuration
563 status = setDeviceConnectionState(device,
564 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 device_address, device_name,
566 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800567 if (status != NO_ERROR) {
568 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
569 status);
570 return status;
571 }
572
573 status = setDeviceConnectionState(device,
574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
578 status);
579 return status;
580 }
581
582 return NO_ERROR;
583}
584
Pattydd807582021-11-04 21:01:03 +0800585status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
586 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800587{
Pattydd807582021-11-04 21:01:03 +0800588 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800589 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800590 std::unordered_set<audio_format_t> formatSet;
591 sp<HwModule> primaryModule =
592 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700593 if (primaryModule == nullptr) {
594 ALOGE("%s() unable to get primary module", __func__);
595 return NO_INIT;
596 }
Pattydd807582021-11-04 21:01:03 +0800597
598 DeviceTypeSet audioDeviceSet;
599
600 switch(device) {
601 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
602 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
603 break;
604 case AUDIO_DEVICE_OUT_BLE_HEADSET:
605 audioDeviceSet = getAudioDeviceOutAllBleSet();
606 break;
607 default:
608 ALOGE("%s() device type 0x%08x not supported", __func__, device);
609 return BAD_VALUE;
610 }
611
jiabin9a3361e2019-10-01 09:38:30 -0700612 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800613 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 for (const auto& device : declaredDevices) {
615 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800616 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800617 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800618 return status;
619}
620
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100621DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
622{
623 DeviceVector rxSinkdevices{};
624 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
625 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
626 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
627 auto rxSinkDevice = rxSinkdevices.itemAt(0);
628 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
630 // retrieve Rx Source device descriptor
631 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
632 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
633
634 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
635 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
636 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
637 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
638 return DeviceVector(rxSinkDevice);
639 }
640 }
641 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
642 // the device returned is not necessarily reachable via this output
643 // (filter later by setOutputDevices())
644 return getNewOutputDevices(mPrimaryOutput, fromCache);
645}
646
647status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
648{
649 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
650 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
651 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
652 }
653 return INVALID_OPERATION;
654}
655
656status_t AudioPolicyManager::updateCallRoutingInternal(
657 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658{
659 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100660 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700661 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700662 if(!hasPrimaryOutput() ||
663 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700665 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100666 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100667
Francois Gaffie716e1432019-01-14 16:58:59 +0100668 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100669 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100671
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100672 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100673 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
Francois Gaffie601801d2021-06-22 13:27:39 +0200675 disconnectTelephonyAudioSource(mCallRxSourceClient);
676 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677
François Gaffie9eb18552018-11-05 10:33:26 +0100678 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700679 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100680 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700681 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100682 // retrieve Rx Source and Tx Sink device descriptors
683 sp<DeviceDescriptor> rxSourceDevice =
684 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
685 String8(),
686 AUDIO_FORMAT_DEFAULT);
687 sp<DeviceDescriptor> txSinkDevice =
688 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691
692 // RX and TX Telephony device are declared by Primary Audio HAL
693 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
694 (telephonyRxModule->getHalVersionMajor() >= 3)) {
695 if (rxSourceDevice == 0 || txSinkDevice == 0) {
696 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 ALOGE("%s() no telephony Tx and/or RX device", __func__);
698 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100699 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100700 // createAudioPatchInternal now supports both HW / SW bridging
701 createRxPatch = true;
702 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 } else {
704 // If the RX device is on the primary HW module, then use legacy routing method for
705 // voice calls via setOutputDevice() on primary output.
706 // Otherwise, create two audio patches for TX and RX path.
707 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
708 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709 // If the TX device is also on the primary HW module, setOutputDevice() will take care
710 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100711 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
712 (txSinkDevice != 0);
713 }
714 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
715 // Otherwise, create two audio patches for TX and RX path.
716 if (!createRxPatch) {
717 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700718 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200719 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800720 // If the TX device is on the primary HW module but RX device is
721 // on other HW module, SinkMetaData of telephony input should handle it
722 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700724 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100725 // terminate active capture if on the same HW module as the call TX source device
726 // FIXME: would be better to refine to only inputs whose profile connects to the
727 // call TX device but this information is not in the audio patch and logic here must be
728 // symmetric to the one in startInput()
729 for (const auto& activeDesc : mInputs.getActiveInputs()) {
730 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
731 closeActiveClients(activeDesc);
732 }
733 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200734 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800735 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100736 if (waitMs != nullptr) {
737 *waitMs = muteWaitMs;
738 }
739 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800740}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
Mikhail Naganov100f0122018-11-29 11:22:16 -0800742bool AudioPolicyManager::isDeviceOfModule(
743 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
744 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
745 if (module != 0) {
746 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
747 .indexOf(devDesc) != NAME_NOT_FOUND
748 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
749 .indexOf(devDesc) != NAME_NOT_FOUND;
750 }
751 return false;
752}
753
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754void AudioPolicyManager::connectTelephonyRxAudioSource()
755{
Francois Gaffie601801d2021-06-22 13:27:39 +0200756 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200757 const struct audio_port_config source = {
758 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
759 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
760 };
761 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200762 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
763 ALOGE_IF(mCallRxSourceClient == nullptr,
764 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765}
766
Francois Gaffie601801d2021-06-22 13:27:39 +0200767void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768{
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 if (clientDesc == nullptr) {
770 return;
771 }
772 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
773 "%s error stopping audio source", __func__);
774 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200775}
776
777void AudioPolicyManager::connectTelephonyTxAudioSource(
778 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
779 uint32_t delayMs)
780{
Francois Gaffie601801d2021-06-22 13:27:39 +0200781 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 if (srcDevice == nullptr || sinkDevice == nullptr) {
783 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
784 return;
785 }
786 PatchBuilder patchBuilder;
787 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
788 ALOGV("%s between source %s and sink %s", __func__,
789 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200791 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
792 struct audio_port_config source = {};
793 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 mCallTxSourceClient = new InternalSourceClientDescriptor(
795 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 mCommunnicationStrategy, toVolumeSource(aa));
797 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
798 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200799 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
800 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
802 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200804 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805}
806
Eric Laurente0720872014-03-11 09:30:41 -0700807void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700808{
809 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100810 // store previous phone state for management of sonification strategy below
811 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100812 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100813
814 if (mEngine->setPhoneState(state) != NO_ERROR) {
815 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700816 return;
817 }
François Gaffie2110e042015-03-24 08:41:51 +0100818 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700819 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700820 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700821 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800822 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700823 }
824
François Gaffie2110e042015-03-24 08:41:51 +0100825 /**
826 * Switching to or from incall state or switching between telephony and VoIP lead to force
827 * routing command.
828 */
Eric Laurent74b71512019-11-06 17:21:57 -0800829 bool force = ((isStateInCall(oldState) != isStateInCall(state))
830 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700831
832 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700833 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700834
Eric Laurente552edb2014-03-10 17:42:56 -0700835 int delayMs = 0;
836 if (isStateInCall(state)) {
837 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100838 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
839 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700841 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700842 // mute media and sonification strategies and delay device switch by the largest
843 // latency of any output where either strategy is active.
844 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100845 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
846 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
847 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700848 (delayMs < (int)desc->latency()*2)) {
849 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700850 }
François Gaffiec005e562018-11-06 15:04:49 +0100851 setStrategyMute(musicStrategy, true, desc);
852 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
853 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
854 nullptr, true /*fromCache*/).types());
855 setStrategyMute(sonificationStrategy, true, desc);
856 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
857 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
858 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700859 }
860 }
861
Eric Laurent87ffa392015-05-22 10:32:38 -0700862 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700863 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100864 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700865 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100866 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
867 // force routing command to audio hardware when ending call
868 // even if no device change is needed
869 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
870 rxDevices = mPrimaryOutput->devices();
871 }
872 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200873 disconnectTelephonyAudioSource(mCallRxSourceClient);
874 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100875 }
François Gaffie11d30102018-11-02 16:09:09 +0100876 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700877 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700878 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700879
880 // reevaluate routing on all outputs in case tracks have been started during the call
881 for (size_t i = 0; i < mOutputs.size(); i++) {
882 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100883 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200884 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
885 bool forceRouting = !newDevices.isEmpty();
886 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
887 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700888 }
889 }
890
Eric Laurent96d1dda2022-03-14 17:14:19 +0100891 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
892
Eric Laurente552edb2014-03-10 17:42:56 -0700893 if (isStateInCall(state)) {
894 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700895 // force reevaluating accessibility routing when call starts
896 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 }
898
899 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100900 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
901 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700902}
903
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700904audio_mode_t AudioPolicyManager::getPhoneState() {
905 return mEngine->getPhoneState();
906}
907
Eric Laurente0720872014-03-11 09:30:41 -0700908void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100909 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700910{
François Gaffie2110e042015-03-24 08:41:51 +0100911 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700912 if (config == mEngine->getForceUse(usage)) {
913 return;
914 }
Eric Laurente552edb2014-03-10 17:42:56 -0700915
François Gaffie2110e042015-03-24 08:41:51 +0100916 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
917 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
918 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
François Gaffie2110e042015-03-24 08:41:51 +0100920 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
921 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
922 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700923
924 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700925 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800926
Eric Laurent22fcda22019-05-17 16:28:47 -0700927 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
928 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
929 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
930 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
931 }
932
Eric Laurentdc462862016-07-19 12:29:53 -0700933 //FIXME: workaround for truncated touch sounds
934 // to be removed when the problem is handled by system UI
935 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700936 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
937 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
938 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700939
940 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100941 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700942}
943
Eric Laurente0720872014-03-11 09:30:41 -0700944void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700945{
946 ALOGV("setSystemProperty() property %s, value %s", property, value);
947}
948
Dorin Drimusecc9f422022-03-09 17:57:40 +0100949// Find an MSD output profile compatible with the parameters passed.
950// When "directOnly" is set, restrict search to profiles for direct outputs.
951sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
952 const DeviceVector& devices,
953 uint32_t samplingRate,
954 audio_format_t format,
955 audio_channel_mask_t channelMask,
956 audio_output_flags_t flags,
957 bool directOnly)
958{
959 flags = getRelevantFlags(flags, directOnly);
960
961 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
962 if (msdModule != nullptr) {
963 // for the msd module check if there are patches to the output devices
964 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
965 HwModuleCollection modules;
966 modules.add(msdModule);
967 return searchCompatibleProfileHwModules(
968 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
969 flags, directOnly);
970 }
971 }
972 return nullptr;
973}
974
Michael Chana94fbb22018-04-24 14:31:19 +1000975// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
976// search to profiles for direct outputs.
977sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100978 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000979 uint32_t samplingRate,
980 audio_format_t format,
981 audio_channel_mask_t channelMask,
982 audio_output_flags_t flags,
983 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700984{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100985 flags = getRelevantFlags(flags, directOnly);
986
987 return searchCompatibleProfileHwModules(
988 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
989}
990
991audio_output_flags_t AudioPolicyManager::getRelevantFlags (
992 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000993 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100994 // only retain flags that will drive the direct output profile selection
995 // if explicitly requested
996 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000997 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
999 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001000 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001001 return flags;
1002}
Eric Laurent861a6282015-05-18 15:40:16 -07001003
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1005 const HwModuleCollection& hwModules,
1006 const DeviceVector& devices,
1007 uint32_t samplingRate,
1008 audio_format_t format,
1009 audio_channel_mask_t channelMask,
1010 audio_output_flags_t flags,
1011 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001012 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001013 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001014 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001015 if (!curProfile->isCompatibleProfile(devices,
1016 samplingRate, NULL /*updatedSamplingRate*/,
1017 format, NULL /*updatedFormat*/,
1018 channelMask, NULL /*updatedChannelMask*/,
1019 flags)) {
1020 continue;
1021 }
1022 // reject profiles not corresponding to a device currently available
1023 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1024 continue;
1025 }
1026 // reject profiles if connected device does not support codec
1027 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1028 continue;
1029 }
1030 if (!directOnly) {
1031 return curProfile;
1032 }
1033
1034 // when searching for direct outputs, if several profiles are compatible, give priority
1035 // to one with offload capability
1036 if (profile != 0 &&
1037 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001038 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039 }
1040 profile = curProfile;
1041 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1042 break;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
1045 }
Eric Laurent861a6282015-05-18 15:40:16 -07001046 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001047}
1048
Eric Laurentfa0f6742021-08-17 18:39:44 +02001049sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001050 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001051{
1052 for (const auto& hwModule : mHwModules) {
1053 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001054 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001055 continue;
1056 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001057 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001058 // reject profiles not corresponding to a device currently available
1059 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1060 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1061 continue;
1062 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001063 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1064 != devices.size()) {
1065 continue;
1066 }
1067 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001068 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1069 return curProfile;
1070 }
1071 }
1072 return nullptr;
1073}
1074
Eric Laurentf4e63452017-11-06 19:31:46 +00001075audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001076{
François Gaffiec005e562018-11-06 15:04:49 +01001077 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001078
1079 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1080 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1081 // format, flags, etc. This may result in some discrepancy for functions that utilize
1082 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1083 // and AudioSystem::getOutputSamplingRate().
1084
François Gaffie11d30102018-11-02 16:09:09 +01001085 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001086 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001087
François Gaffie11d30102018-11-02 16:09:09 +01001088 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1089 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001090 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001091}
1092
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001093status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1094 const audio_attributes_t *srcAttr,
1095 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001096{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001097 if (srcAttr != NULL) {
1098 if (!isValidAttributes(srcAttr)) {
1099 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1100 __func__,
1101 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1102 srcAttr->tags);
1103 return BAD_VALUE;
1104 }
1105 *dstAttr = *srcAttr;
1106 } else {
1107 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1108 ALOGE("%s: invalid stream type", __func__);
1109 return BAD_VALUE;
1110 }
François Gaffiec005e562018-11-06 15:04:49 +01001111 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001112 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001113
1114 // Only honor audibility enforced when required. The client will be
1115 // forced to reconnect if the forced usage changes.
1116 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001117 dstAttr->flags = static_cast<audio_flags_mask_t>(
1118 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001119 }
1120
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121 return NO_ERROR;
1122}
1123
Kevin Rocard153f92d2018-12-18 18:33:28 -08001124status_t AudioPolicyManager::getOutputForAttrInt(
1125 audio_attributes_t *resultAttr,
1126 audio_io_handle_t *output,
1127 audio_session_t session,
1128 const audio_attributes_t *attr,
1129 audio_stream_type_t *stream,
1130 uid_t uid,
1131 const audio_config_t *config,
1132 audio_output_flags_t *flags,
1133 audio_port_handle_t *selectedDeviceId,
1134 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001135 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001136 output_type_t *outputType,
1137 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001138{
François Gaffiec005e562018-11-06 15:04:49 +01001139 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001140 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001141 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001142 const sp<DeviceDescriptor> requestedDevice =
1143 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1144
Eric Laurent8a1095a2019-11-08 14:44:16 -08001145 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001146 *isSpatialized = false;
1147
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001148 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1149 if (status != NO_ERROR) {
1150 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001151 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001152 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001153 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001154 }
François Gaffiec005e562018-11-06 15:04:49 +01001155 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001156
François Gaffiec005e562018-11-06 15:04:49 +01001157 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1158 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001159
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1161 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1162 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001164 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1165 .channel_mask = config->channel_mask,
1166 .format = config->format,
1167 };
1168 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1169 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001170 if (status != OK) {
1171 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001173
Kevin Rocard153f92d2018-12-18 18:33:28 -08001174 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001175 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001176
1177 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001178 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1179 && !audio_is_linear_pcm(config->format)) {
1180 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 return BAD_VALUE;
1182 }
1183 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001184 sp<DeviceDescriptor> deviceDesc =
1185 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1186 primaryMix->mDeviceAddress,
1187 AUDIO_FORMAT_DEFAULT);
1188 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001189 if (deviceDesc != nullptr
1190 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001191 audio_io_handle_t newOutput;
1192 status = openDirectOutput(
1193 *stream, session, config,
1194 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1195 DeviceVector(deviceDesc), &newOutput);
1196 if (status != NO_ERROR) {
1197 policyDesc = nullptr;
1198 } else {
1199 policyDesc = mOutputs.valueFor(newOutput);
1200 primaryMix->setOutput(policyDesc);
1201 }
1202 }
1203 if (policyDesc != nullptr) {
1204 policyDesc->mPolicyMix = primaryMix;
1205 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001206 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001207
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001208 ALOGV("getOutputForAttr() returns output %d", *output);
1209 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1210 *outputType = API_OUT_MIX_PLAYBACK;
1211 } else {
1212 *outputType = API_OUTPUT_LEGACY;
1213 }
1214 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001215 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001216 }
François Gaffiec005e562018-11-06 15:04:49 +01001217 // Virtual sources must always be dynamicaly or explicitly routed
1218 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1219 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1220 return BAD_VALUE;
1221 }
1222 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1223 // in order to let the choice of the order to future vendor engine
1224 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001225
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001226 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001227 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001228 }
1229
Nadav Barb2f18162018-07-18 13:01:53 +03001230 // Set incall music only if device was explicitly set, and fallback to the device which is
1231 // chosen by the engine if not.
1232 // FIXME: provide a more generic approach which is not device specific and move this back
1233 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001234 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001235 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001236 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001237 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001238 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001239 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001240 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001241 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001242 }
1243 }
1244
François Gaffiec005e562018-11-06 15:04:49 +01001245 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1246 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1247 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001248
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001249 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001250 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001251 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001252 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001253 ALOGV("%s() Using MSD devices %s instead of devices %s",
1254 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001255 } else {
1256 *output = AUDIO_IO_HANDLE_NONE;
1257 }
1258 }
1259 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001260 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001261 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001262 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001263 if (*output == AUDIO_IO_HANDLE_NONE) {
1264 return INVALID_OPERATION;
1265 }
Paul McLeanaa981192015-03-21 09:55:15 -07001266
François Gaffiec005e562018-11-06 15:04:49 +01001267 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001268 for (auto &outputDevice : outputDevices) {
1269 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1270 *selectedDeviceId = outputDevice->getId();
1271 break;
1272 }
1273 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001274
Eric Laurent8a1095a2019-11-08 14:44:16 -08001275 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1276 *outputType = API_OUTPUT_TELEPHONY_TX;
1277 } else {
1278 *outputType = API_OUTPUT_LEGACY;
1279 }
1280
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001281 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1282
1283 return NO_ERROR;
1284}
1285
1286status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1287 audio_io_handle_t *output,
1288 audio_session_t session,
1289 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001290 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001291 const audio_config_t *config,
1292 audio_output_flags_t *flags,
1293 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001294 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001295 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001296 output_type_t *outputType,
1297 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001298{
1299 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1300 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1301 return INVALID_OPERATION;
1302 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001303 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001304 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001305 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001306 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001307 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001308 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001309 const sp<DeviceDescriptor> requestedDevice =
1310 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1311
1312 // Prevent from storing invalid requested device id in clients
1313 const audio_port_handle_t sanitizedRequestedPortId =
1314 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1315 *selectedDeviceId = sanitizedRequestedPortId;
1316
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001317 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001318 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001319 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001320 if (status != NO_ERROR) {
1321 return status;
1322 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001323 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001324 if (secondaryOutputs != nullptr) {
1325 for (auto &secondaryMix : secondaryMixes) {
1326 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1327 if (outputDesc != nullptr &&
1328 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1329 secondaryOutputs->push_back(outputDesc->mIoHandle);
1330 weakSecondaryOutputDescs.push_back(outputDesc);
1331 }
1332 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001333 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001334
Eric Laurent8fc147b2018-07-22 19:13:55 -07001335 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001336 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001337 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001338 };
jiabin4ef93452019-09-10 14:29:54 -07001339 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001340
Eric Laurentc209fe42020-06-05 18:11:23 -07001341 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001342 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001343 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001344 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001345 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001346 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001347 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001348 std::move(weakSecondaryOutputDescs),
1349 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001350 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001351
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001352 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1353 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001354
Eric Laurente83b55d2014-11-14 10:06:21 -08001355 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001356}
1357
Eric Laurentc529cf62020-04-17 18:19:10 -07001358status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1359 audio_session_t session,
1360 const audio_config_t *config,
1361 audio_output_flags_t flags,
1362 const DeviceVector &devices,
1363 audio_io_handle_t *output) {
1364
1365 *output = AUDIO_IO_HANDLE_NONE;
1366
1367 // skip direct output selection if the request can obviously be attached to a mixed output
1368 // and not explicitly requested
1369 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1370 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1371 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1372 return NAME_NOT_FOUND;
1373 }
1374
1375 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1376 // This prevents creating an offloaded track and tearing it down immediately after start
1377 // when audioflinger detects there is an active non offloadable effect.
1378 // FIXME: We should check the audio session here but we do not have it in this context.
1379 // This may prevent offloading in rare situations where effects are left active by apps
1380 // in the background.
1381 sp<IOProfile> profile;
1382 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1383 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1384 profile = getProfileForOutput(
1385 devices, config->sample_rate, config->format, config->channel_mask,
1386 flags, true /* directOnly */);
1387 }
1388
1389 if (profile == nullptr) {
1390 return NAME_NOT_FOUND;
1391 }
1392
1393 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1394 for (size_t i = 0; i < mOutputs.size(); i++) {
1395 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1396 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1397 // reuse direct output if currently open by the same client
1398 // and configured with same parameters
1399 if ((config->sample_rate == desc->getSamplingRate()) &&
1400 (config->format == desc->getFormat()) &&
1401 (config->channel_mask == desc->getChannelMask()) &&
1402 (session == desc->mDirectClientSession)) {
1403 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001404 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001405 mOutputs.keyAt(i), session);
1406 *output = mOutputs.keyAt(i);
1407 return NO_ERROR;
1408 }
1409 }
1410 }
1411
1412 if (!profile->canOpenNewIo()) {
1413 return NAME_NOT_FOUND;
1414 }
1415
1416 sp<SwAudioOutputDescriptor> outputDesc =
1417 new SwAudioOutputDescriptor(profile, mpClientInterface);
1418
Michael Chan6fb34492020-12-08 15:44:49 +11001419 // An MSD patch may be using the only output stream that can service this request. Release
1420 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001421 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001422
Eric Laurentf1f22e72021-07-13 14:04:14 +02001423 status_t status =
1424 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001425
1426 // only accept an output with the requested parameters
1427 if (status != NO_ERROR ||
1428 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1429 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1430 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1431 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1432 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1433 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1434 config->channel_mask, outputDesc->getChannelMask());
1435 if (*output != AUDIO_IO_HANDLE_NONE) {
1436 outputDesc->close();
1437 }
1438 // fall back to mixer output if possible when the direct output could not be open
1439 if (audio_is_linear_pcm(config->format) &&
1440 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1441 return NAME_NOT_FOUND;
1442 }
1443 *output = AUDIO_IO_HANDLE_NONE;
1444 return BAD_VALUE;
1445 }
1446 outputDesc->mDirectOpenCount = 1;
1447 outputDesc->mDirectClientSession = session;
1448
1449 addOutput(*output, outputDesc);
1450 mPreviousOutputs = mOutputs;
1451 ALOGV("%s returns new direct output %d", __func__, *output);
1452 mpClientInterface->onAudioPortListUpdate();
1453 return NO_ERROR;
1454}
1455
François Gaffie11d30102018-11-02 16:09:09 +01001456audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1457 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001458 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001459 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001460 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001461 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001462 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001463 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001464{
Andy Hungc88b0642018-04-27 15:42:35 -07001465 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001466
jiabine375d412019-02-26 12:54:53 -08001467 // Discard haptic channel mask when forcing muting haptic channels.
1468 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001469 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1470 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001471
Eric Laurente552edb2014-03-10 17:42:56 -07001472 // open a direct output if required by specified parameters
1473 //force direct flag if offload flag is set: offloading implies a direct output stream
1474 // and all common behaviors are driven by checking only the direct flag
1475 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001476 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1477 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001478 }
Nadav Bar766fb022018-01-07 12:18:03 +02001479 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1480 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001481 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001482
1483 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1484
Eric Laurente83b55d2014-11-14 10:06:21 -08001485 // only allow deep buffering for music stream type
1486 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001487 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001488 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001489 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001490 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1491 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001492 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001493 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001494 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001495 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001496 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001497 audio_is_linear_pcm(config->format) &&
1498 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001499 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001500 AUDIO_OUTPUT_FLAG_DIRECT);
1501 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001502 }
Eric Laurente552edb2014-03-10 17:42:56 -07001503
Carter Hsua3abb402021-10-26 11:11:20 +08001504 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1505 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1506 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1507 }
1508
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001509 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001510 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001511 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001512 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001513 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001514 }
1515
Eric Laurentc529cf62020-04-17 18:19:10 -07001516 audio_config_t directConfig = *config;
1517 directConfig.channel_mask = channelMask;
1518 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1519 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001520 return output;
1521 }
1522
Eric Laurent14cbfca2016-03-17 09:42:16 -07001523 // A request for HW A/V sync cannot fallback to a mixed output because time
1524 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001525 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001526 return AUDIO_IO_HANDLE_NONE;
1527 }
1528
Eric Laurente552edb2014-03-10 17:42:56 -07001529 // ignoring channel mask due to downmix capability in mixer
1530
1531 // open a non direct output
1532
1533 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001534 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001535 // get which output is suitable for the specified stream. The actual
1536 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001537 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001538
Eric Laurent8838a382014-09-08 16:44:28 -07001539 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001540 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001541 output = selectOutput(
1542 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001543 }
François Gaffie11d30102018-11-02 16:09:09 +01001544 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001545 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001546 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001547
Eric Laurente552edb2014-03-10 17:42:56 -07001548 return output;
1549}
1550
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001551sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001552 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1553 mAvailableInputDevices);
1554 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1555}
1556
1557DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1558 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1559 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001560}
1561
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001562const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001563 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001564 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1565 if (msdModule != 0) {
1566 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1567 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1568 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1569 const struct audio_port_config *source = &patch->mPatch.sources[j];
1570 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1571 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001572 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001573 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001574 }
1575 }
1576 }
1577 return msdPatches;
1578}
1579
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001580bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1581 ssize_t index = mAudioPatches.indexOfKey(handle);
1582 if (index < 0) {
1583 return false;
1584 }
1585 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1586 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1587 if (msdModule == nullptr) {
1588 return false;
1589 }
1590 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1591 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1592 return true;
1593 }
1594 index = getMsdOutputPatches().indexOfKey(handle);
1595 if (index < 0) {
1596 return false;
1597 }
1598 return true;
1599}
1600
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001601status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1602 const InputProfileCollection &inputProfiles,
1603 const OutputProfileCollection &outputProfiles,
1604 const sp<DeviceDescriptor> &sourceDevice,
1605 const sp<DeviceDescriptor> &sinkDevice,
1606 AudioProfileVector& sourceProfiles,
1607 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001608 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001609 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001610 return NO_INIT;
1611 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001612 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001613 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001614 return NO_INIT;
1615 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001616 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001617 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1618 inProfile->supportsDevice(sourceDevice)) {
1619 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001620 }
1621 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001623 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001624 outProfile->supportsDevice(sinkDevice)) {
1625 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 }
1627 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001628 return NO_ERROR;
1629}
1630
1631status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1632 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1633 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1634{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001635 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001636 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1637 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1638 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001639 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001640 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1641 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001642 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001643 }
1644 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1645 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1646 sinkConfig->format = bestSinkConfig.format;
1647 // For encoded streams force direct flag to prevent downstream mixing.
1648 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1649 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001650 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1651 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001652 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001653 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1654 // raw and IEC61937 framed streams.
1655 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1656 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1657 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001658 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1659 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1660 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1661 sourceConfig->format = bestSinkConfig.format;
1662 // Copy input stream directly without any processing (e.g. resampling).
1663 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1664 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1665 if (hwAvSync) {
1666 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1667 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1668 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1669 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1670 }
1671 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1672 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1673 sinkConfig->config_mask |= config_mask;
1674 sourceConfig->config_mask |= config_mask;
1675 return NO_ERROR;
1676}
1677
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001678PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1679 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001680{
1681 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001682 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1683 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1684 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1685 if (deviceModule == nullptr) {
1686 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1687 return patchBuilder;
1688 }
1689 const InputProfileCollection inputProfiles = msdIsSource ?
1690 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1691 const OutputProfileCollection outputProfiles = msdIsSource ?
1692 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1693
1694 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1695 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1696 device : getMsdAudioOutDevices().itemAt(0);
1697 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1698
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001699 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1700 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001701 AudioProfileVector sourceProfiles;
1702 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1704 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001705 for (auto hwAvSync : { true, false }) {
1706 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1707 sourceProfiles, sinkProfiles) != NO_ERROR) {
1708 continue;
1709 }
1710 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1711 &sinkConfig) == NO_ERROR) {
1712 // Found a matching config. Re-create PatchBuilder with this config.
1713 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1714 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001716 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001717 " supporting PCM format conversion.", __func__);
1718 return patchBuilder;
1719}
1720
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001722 DeviceVector devices;
1723 if (outputDevices != nullptr && outputDevices->size() > 0) {
1724 devices.add(*outputDevices);
1725 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 // Use media strategy for unspecified output device. This should only
1727 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1728 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001729 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001730 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001731 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001732 }
Michael Chan6fb34492020-12-08 15:44:49 +11001733 std::vector<PatchBuilder> patchesToCreate;
1734 for (auto i = 0u; i < devices.size(); ++i) {
1735 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001736 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001737 }
1738 // Retain only the MSD patches associated with outputDevices request.
1739 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001740 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001741 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1742 auto retainedPatch = false;
1743 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1744 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1745 patchesToRemove.removeItemsAt(i);
1746 retainedPatch = true;
1747 break;
1748 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001749 }
Michael Chan6fb34492020-12-08 15:44:49 +11001750 if (retainedPatch) {
1751 it = patchesToCreate.erase(it);
1752 continue;
1753 }
1754 ++it;
1755 }
1756 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1757 return NO_ERROR;
1758 }
1759 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1760 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001761 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001762 }
Michael Chan6fb34492020-12-08 15:44:49 +11001763 status_t status = NO_ERROR;
1764 for (const auto &p : patchesToCreate) {
1765 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1766 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1767 char message[256];
1768 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1769 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1770 currStatus == NO_ERROR ? "Success" : "Error",
1771 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1772 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1773 if (currStatus == NO_ERROR) {
1774 ALOGD("%s", message);
1775 } else {
1776 ALOGE("%s", message);
1777 if (status == NO_ERROR) {
1778 status = currStatus;
1779 }
1780 }
1781 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001782 return status;
1783}
1784
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001785void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1786 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001787 for (size_t i = 0; i < msdPatches.size(); i++) {
1788 const auto& patch = msdPatches[i];
1789 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1790 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1791 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1792 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1793 releaseAudioPatch(patch->getHandle(), mUidCached);
1794 break;
1795 }
1796 }
1797 }
1798}
1799
Dorin Drimus94d94412022-02-02 09:05:02 +01001800bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1801 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1802 AudioPatchCollection msdPatches = getMsdOutputPatches();
1803 for (size_t i = 0; i < msdPatches.size(); i++) {
1804 const auto& patch = msdPatches[i];
1805 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1806 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1807 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1808 const auto& foundDevice = devicesToCheck.getDevice(
1809 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1810 if (foundDevice != nullptr) {
1811 devicesToCheck.remove(foundDevice);
1812 if (devicesToCheck.isEmpty()) {
1813 return true;
1814 }
1815 }
1816 }
1817 }
1818 }
1819 return false;
1820}
1821
Eric Laurente0720872014-03-11 09:30:41 -07001822audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001823 audio_output_flags_t flags,
1824 audio_format_t format,
1825 audio_channel_mask_t channelMask,
1826 uint32_t samplingRate,
1827 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001828{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001829 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1830 "%s called with format %#x", __func__, format);
1831
jiabinebb6af42020-06-09 17:31:17 -07001832 // Return the output that haptic-generating attached to when 1) session id is specified,
1833 // 2) haptic-generating effect exists for given session id and 3) the output that
1834 // haptic-generating effect attached to is in given outputs.
1835 if (sessionId != AUDIO_SESSION_NONE) {
1836 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1837 sessionId, FX_IID_HAPTICGENERATOR);
1838 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1839 return hapticGeneratingOutput;
1840 }
1841 }
1842
Eric Laurent16c66dd2019-05-01 17:54:10 -07001843 // Flags disqualifying an output: the match must happen before calling selectOutput()
1844 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1845 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1846
1847 // Flags expressing a functional request: must be honored in priority over
1848 // other criteria
1849 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1850 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001851 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1852 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001853 // Flags expressing a performance request: have lower priority than serving
1854 // requested sampling rate or channel mask
1855 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1856 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1857 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1858
1859 const audio_output_flags_t functionalFlags =
1860 (audio_output_flags_t)(flags & kFunctionalFlags);
1861 const audio_output_flags_t performanceFlags =
1862 (audio_output_flags_t)(flags & kPerformanceFlags);
1863
1864 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1865
Eric Laurente552edb2014-03-10 17:42:56 -07001866 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001867 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001868 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001869 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001870 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001871 // with tiebreak preferring the minimum number of extra functional flags
1872 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001873 // 3: the output supporting the exact channel mask
1874 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001875 // 5: the output with the highest sampling rate if the requested sample rate is
1876 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001877 // 6: the output with the highest number of requested performance flags
1878 // 7: the output with the bit depth the closest to the requested one
1879 // 8: the primary output
1880 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001881
Eric Laurent16c66dd2019-05-01 17:54:10 -07001882 // matching criteria values in priority order for best matching output so far
1883 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001884
Eric Laurent16c66dd2019-05-01 17:54:10 -07001885 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1886 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1887 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001888
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001889 for (audio_io_handle_t output : outputs) {
1890 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001891 // matching criteria values in priority order for current output
1892 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001893
Eric Laurent16c66dd2019-05-01 17:54:10 -07001894 if (outputDesc->isDuplicated()) {
1895 continue;
1896 }
1897 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1898 continue;
1899 }
Eric Laurent8838a382014-09-08 16:44:28 -07001900
Eric Laurent16c66dd2019-05-01 17:54:10 -07001901 // If haptic channel is specified, use the haptic output if present.
1902 // When using haptic output, same audio format and sample rate are required.
1903 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001904 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001905 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1906 continue;
1907 }
1908 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001909 && format == outputDesc->getFormat()
1910 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001911 currentMatchCriteria[0] = outputHapticChannelCount;
1912 }
1913
1914 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001915 const int matchingFunctionalFlags =
1916 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1917 const int totalFunctionalFlags =
1918 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1919 // Prefer matching functional flags, but subtract unnecessary functional flags.
1920 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921
1922 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001923 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1924 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001925 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1926 channelCount <= outputChannelCount) {
1927 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001928 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1929 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001930 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001931 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932 currentMatchCriteria[3] = outputChannelCount;
1933 }
1934
1935 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001936 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001937 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 }
1939
1940 // performance flags match
1941 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1942
1943 // format match
1944 if (format != AUDIO_FORMAT_INVALID) {
1945 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001946 PolicyAudioPort::kFormatDistanceMax -
1947 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001948 }
1949
1950 // primary output match
1951 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1952
1953 // compare match criteria by priority then value
1954 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1955 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1956 bestMatchCriteria = currentMatchCriteria;
1957 bestOutput = output;
1958
1959 std::stringstream result;
1960 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1961 std::ostream_iterator<int>(result, " "));
1962 ALOGV("%s new bestOutput %d criteria %s",
1963 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001964 }
1965 }
1966
Eric Laurent16c66dd2019-05-01 17:54:10 -07001967 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001968}
1969
Eric Laurent8fc147b2018-07-22 19:13:55 -07001970status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001971{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001972 ALOGV("%s portId %d", __FUNCTION__, portId);
1973
1974 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1975 if (outputDesc == 0) {
1976 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001977 return BAD_VALUE;
1978 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001979 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001980
Eric Laurent8fc147b2018-07-22 19:13:55 -07001981 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001982 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001983
Eric Laurent733ce942017-12-07 12:18:25 -08001984 status_t status = outputDesc->start();
1985 if (status != NO_ERROR) {
1986 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001987 }
1988
Eric Laurent97ac8712018-07-27 18:59:02 -07001989 uint32_t delayMs;
1990 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001991
1992 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001993 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001994 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001995 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001996 if (delayMs != 0) {
1997 usleep(delayMs * 1000);
1998 }
1999
2000 return status;
2001}
2002
Eric Laurent96d1dda2022-03-14 17:14:19 +01002003bool AudioPolicyManager::isLeUnicastActive() const {
2004 if (isInCall()) {
2005 return true;
2006 }
2007 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2008}
2009
2010bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2011 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2012 return false;
2013 }
2014 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2015 ALOGV("%s active %d", __func__, active);
2016 return active;
2017}
2018
Eric Laurent97ac8712018-07-27 18:59:02 -07002019status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2020 const sp<TrackClientDescriptor>& client,
2021 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002022{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002023 // cannot start playback of STREAM_TTS if any other output is being used
2024 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002025
2026 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002027 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002028 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002029 auto clientStrategy = client->strategy();
2030 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002031 if (stream == AUDIO_STREAM_TTS) {
2032 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002033 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002034 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002035 return INVALID_OPERATION;
2036 } else {
2037 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2038 }
2039 } else {
2040 // some playback other than beacon starts
2041 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2042 }
2043
Eric Laurent77305a62016-07-25 16:39:22 -07002044 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002045 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002046 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002047
François Gaffie11d30102018-11-02 16:09:09 +01002048 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002049 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002051 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002052 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002053 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002054 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002055 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002056 } else {
2057 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002058 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002059 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2060 AUDIO_FORMAT_DEFAULT);
2061 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2062 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002063 }
2064
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002065 // requiresMuteCheck is false when we can bypass mute strategy.
2066 // It covers a common case when there is no materially active audio
2067 // and muting would result in unnecessary delay and dropped audio.
2068 const uint32_t outputLatencyMs = outputDesc->latency();
2069 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002070 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002071
Eric Laurente552edb2014-03-10 17:42:56 -07002072 // increment usage count for this stream on the requested output:
2073 // NOTE that the usage count is the same for duplicated output and hardware output which is
2074 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002075 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002076
2077 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002078 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2079 client->isPreferredDeviceForExclusiveUse()) {
2080 // Preferred device may be exclusive, use only if no other active clients on this output
2081 devices = DeviceVector(
2082 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2083 } else {
2084 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2085 }
François Gaffie11d30102018-11-02 16:09:09 +01002086 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002087 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002088 }
2089 }
Eric Laurente552edb2014-03-10 17:42:56 -07002090
François Gaffiec005e562018-11-06 15:04:49 +01002091 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002092 selectOutputForMusicEffects();
2093 }
2094
François Gaffie1c878552018-11-22 16:53:21 +01002095 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002096 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002097 if (devices.isEmpty()) {
2098 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002099 }
François Gaffiec005e562018-11-06 15:04:49 +01002100 bool shouldWait =
2101 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2102 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2103 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002104 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002105 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002106 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002107 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002108 // An output has a shared device if
2109 // - managed by the same hw module
2110 // - supports the currently selected device
2111 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002112 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002113
Eric Laurent77305a62016-07-25 16:39:22 -07002114 // force a device change if any other output is:
2115 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002116 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002117 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002118 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002119 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002120 // change the device currently selected by the other output.
2121 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002122 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002123 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002124 force = true;
2125 }
2126 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002127 // a notification so that audio focus effect can propagate, or that a mute/unmute
2128 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002129 const uint32_t latencyMs = desc->latency();
2130 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2131
2132 if (shouldWait && isActive && (waitMs < latencyMs)) {
2133 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002134 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002135
2136 // Require mute check if another output is on a shared device
2137 // and currently active to have proper drain and avoid pops.
2138 // Note restoring AudioTracks onto this output needs to invoke
2139 // a volume ramp if there is no mute.
2140 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002141 }
2142 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002143
2144 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002145 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002146
Eric Laurente552edb2014-03-10 17:42:56 -07002147 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002148 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002149 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002150 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002151 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002152 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002153 outputDesc->useHwGain() /*force*/)) {
2154 // request AudioService to reinitialize the volume curves asynchronously
2155 ALOGE("checkAndSetVolume failed, requesting volume range init");
2156 mpClientInterface->onVolumeRangeInitRequest();
2157 };
Eric Laurente552edb2014-03-10 17:42:56 -07002158
2159 // update the outputs if starting an output with a stream that can affect notification
2160 // routing
2161 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002162
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002163 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002164 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002165 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2166 }
Eric Laurentdc462862016-07-19 12:29:53 -07002167
2168 if (waitMs > muteWaitMs) {
2169 *delayMs = waitMs - muteWaitMs;
2170 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002171
2172 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2173 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2174 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2175 // change occurs after the MixerThread starts and causes a stream volume
2176 // glitch.
2177 //
2178 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002179 }
Eric Laurentdc462862016-07-19 12:29:53 -07002180
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002181 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002182 mEngine->getForceUse(
2183 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002184 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002185 }
2186
Eric Laurent97ac8712018-07-27 18:59:02 -07002187 // Automatically enable the remote submix input when output is started on a re routing mix
2188 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002189 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2190 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002191 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2192 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2193 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002194 "remote-submix",
2195 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002196 }
2197
Eric Laurent96d1dda2022-03-14 17:14:19 +01002198 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2199
Eric Laurente552edb2014-03-10 17:42:56 -07002200 return NO_ERROR;
2201}
2202
Eric Laurent96d1dda2022-03-14 17:14:19 +01002203void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2204 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2205 bool isUnicastActive = isLeUnicastActive();
2206
2207 if (wasUnicastActive != isUnicastActive) {
2208 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2209 for (size_t i = 0; i < mOutputs.size(); i++) {
2210 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2211 if (desc != ignoredOutput && desc->isActive()
2212 && ((isUnicastActive &&
2213 !desc->devices().
2214 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2215 || (wasUnicastActive &&
2216 !desc->devices().getDevicesFromTypes(
2217 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2218 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2219 bool force = desc->devices() != newDevices;
2220 setOutputDevices(desc, newDevices, force, delayMs);
2221 // re-apply device specific volume if not done by setOutputDevice()
2222 if (!force) {
2223 applyStreamVolumes(desc, newDevices.types(), delayMs);
2224 }
2225 }
2226 }
2227 }
2228}
2229
Eric Laurent8fc147b2018-07-22 19:13:55 -07002230status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002231{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002232 ALOGV("%s portId %d", __FUNCTION__, portId);
2233
2234 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2235 if (outputDesc == 0) {
2236 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002237 return BAD_VALUE;
2238 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002239 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002240
Eric Laurent97ac8712018-07-27 18:59:02 -07002241 ALOGV("stopOutput() output %d, stream %d, session %d",
2242 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002243
Eric Laurent97ac8712018-07-27 18:59:02 -07002244 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002245
Eric Laurent733ce942017-12-07 12:18:25 -08002246 if (status == NO_ERROR ) {
2247 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002248 }
2249 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002250}
2251
Eric Laurent97ac8712018-07-27 18:59:02 -07002252status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2253 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002254{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002255 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002256 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002257 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002258 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002259
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002260 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2261
François Gaffie1c878552018-11-22 16:53:21 +01002262 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2263 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 // Automatically disable the remote submix input when output is stopped on a
2265 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002266 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002267 if (isSingleDeviceType(
2268 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002269 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002270 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002271 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2272 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002273 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002274 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002275 }
2276 }
2277 bool forceDeviceUpdate = false;
2278 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002279 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 forceDeviceUpdate = true;
2281 }
2282
Eric Laurente552edb2014-03-10 17:42:56 -07002283 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002284 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002285
Eric Laurente552edb2014-03-10 17:42:56 -07002286 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002287 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002288 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002289 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002290
2291 // If the routing does not change, if an output is routed on a device using HwGain
2292 // (aka setAudioPortConfig) and there are still active clients following different
2293 // volume group(s), force reapply volume
2294 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2295 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2296
Eric Laurente552edb2014-03-10 17:42:56 -07002297 // delay the device switch by twice the latency because stopOutput() is executed when
2298 // the track stop() command is received and at that time the audio track buffer can
2299 // still contain data that needs to be drained. The latency only covers the audio HAL
2300 // and kernel buffers. Also the latency does not always include additional delay in the
2301 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002302 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2303 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002304
2305 // force restoring the device selection on other active outputs if it differs from the
2306 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002307 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002308 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002309 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002310 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002311 desc->isActive() &&
2312 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002313 (newDevices != desc->devices())) {
2314 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2315 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002316
François Gaffie11d30102018-11-02 16:09:09 +01002317 setOutputDevices(desc, newDevices2, force, delayMs);
2318
Eric Laurent57de36c2016-09-28 16:59:11 -07002319 // re-apply device specific volume if not done by setOutputDevice()
2320 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002321 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002322 }
Eric Laurente552edb2014-03-10 17:42:56 -07002323 }
2324 }
2325 // update the outputs if stopping one with a stream that can affect notification routing
2326 handleNotificationRoutingForStream(stream);
2327 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002328
2329 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2330 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002331 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002332 }
2333
François Gaffiec005e562018-11-06 15:04:49 +01002334 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002335 selectOutputForMusicEffects();
2336 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002337
2338 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2339
Eric Laurente552edb2014-03-10 17:42:56 -07002340 return NO_ERROR;
2341 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002342 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002343 return INVALID_OPERATION;
2344 }
2345}
2346
jiabinbce0c1d2020-10-05 11:20:18 -07002347bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002348{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002349 ALOGV("%s portId %d", __FUNCTION__, portId);
2350
2351 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2352 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002353 // If an output descriptor is closed due to a device routing change,
2354 // then there are race conditions with releaseOutput from tracks
2355 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2356 // destroyed shortly thereafter.
2357 //
2358 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002359 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002360 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002361 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002362
2363 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002364
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302365 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2366 if (outputDesc->isClientActive(client)) {
2367 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2368 stopOutput(portId);
2369 }
2370
Eric Laurent8fc147b2018-07-22 19:13:55 -07002371 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2372 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002373 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002374 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002375 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002376 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002377 if (--outputDesc->mDirectOpenCount == 0) {
2378 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002379 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002380 }
2381 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302382
Andy Hung39efb7a2018-09-26 15:39:28 -07002383 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002384 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2385 // The output is pending reopened to query dynamic profiles and
2386 // there is no active clients
2387 closeOutput(outputDesc->mIoHandle);
2388 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2389 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2390 if (newOutputDesc == nullptr) {
2391 ALOGE("%s failed to open output", __func__);
2392 }
2393 return true;
2394 }
2395 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002396}
2397
Eric Laurentcaf7f482014-11-25 17:50:47 -08002398status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2399 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002400 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002401 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002402 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002403 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002404 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002405 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002406 input_type_t *inputType,
2407 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002408{
François Gaffiec005e562018-11-06 15:04:49 +01002409 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002410 "flags %#x attributes=%s requested device ID %d",
2411 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2412 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002413
Eric Laurentad2e7b92017-09-14 20:06:42 -07002414 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002415 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002416 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002417 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002418 sp<AudioInputDescriptor> inputDesc;
2419 sp<RecordClientDescriptor> clientDesc;
2420 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002421 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002422 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002423
2424 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2425 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2426 return INVALID_OPERATION;
2427 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002428
Francois Gaffie716e1432019-01-14 16:58:59 +01002429 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2430 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002431 }
2432
Paul McLean466dc8e2015-04-17 13:15:36 -06002433 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002434 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002435 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002436
Eric Laurentad2e7b92017-09-14 20:06:42 -07002437 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2438 // possible
2439 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2440 *input != AUDIO_IO_HANDLE_NONE) {
2441 ssize_t index = mInputs.indexOfKey(*input);
2442 if (index < 0) {
2443 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2444 status = BAD_VALUE;
2445 goto error;
2446 }
2447 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002448 RecordClientVector clients = inputDesc->getClientsForSession(session);
2449 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002450 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2451 status = BAD_VALUE;
2452 goto error;
2453 }
2454 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2455 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002456 // corresponds to a new client and is only permitted from the same UID.
2457 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002458 if (clients.size() > 1) {
2459 for (const auto& client : clients) {
2460 // The client map is ordered by key values (portId) and portIds are allocated
2461 // incrementaly. So the first client in this list is the one opened by audio flinger
2462 // when the mmap stream is created and should be ignored as it does not correspond
2463 // to an actual client
2464 if (client == *clients.cbegin()) {
2465 continue;
2466 }
2467 if (uid != client->uid() && !client->isSilenced()) {
2468 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2469 uid, client->portId(), client->uid());
2470 status = INVALID_OPERATION;
2471 goto error;
2472 }
Eric Laurent331679c2018-04-16 17:03:16 -07002473 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002474 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002475 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002476 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002477
Eric Laurentfecbceb2021-02-09 14:46:43 +01002478 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002479 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002480 }
2481
2482 *input = AUDIO_IO_HANDLE_NONE;
2483 *inputType = API_INPUT_INVALID;
2484
Francois Gaffie716e1432019-01-14 16:58:59 +01002485 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2486 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2487 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002488 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002489 ALOGW("%s could not find input mix for attr %s",
2490 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002491 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002492 }
jiabinc1de2df2019-05-07 14:26:40 -07002493 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2494 String8(attr->tags + strlen("addr=")),
2495 AUDIO_FORMAT_DEFAULT);
2496 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002497 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002498 __func__, attributes.source, attributes.tags);
2499 status = BAD_VALUE;
2500 goto error;
2501 }
2502
Kevin Rocard25f9b052019-02-27 15:08:54 -08002503 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2504 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2505 } else {
2506 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2507 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002508 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002509 if (explicitRoutingDevice != nullptr) {
2510 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002511 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002512 // Prevent from storing invalid requested device id in clients
2513 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002514 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002515 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2516 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002517 }
François Gaffie11d30102018-11-02 16:09:09 +01002518 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002519 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002520 status = BAD_VALUE;
2521 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002522 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002523 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2524 *inputType = API_INPUT_MIX_CAPTURE;
2525 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002526 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2527 // there is an external policy, but this input is attached to a mix of recorders,
2528 // meaning it receives audio injected into the framework, so the recorder doesn't
2529 // know about it and is therefore considered "legacy"
2530 *inputType = API_INPUT_LEGACY;
2531 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002532 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002533 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002534 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002535 } else {
2536 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002537 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002538
Eric Laurent599c7582015-12-07 18:05:55 -08002539 }
2540
François Gaffiec005e562018-11-06 15:04:49 +01002541 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002542 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002543 status = INVALID_OPERATION;
2544 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002545 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002546
Eric Laurent8f42ea12018-08-08 09:08:25 -07002547exit:
2548
François Gaffiec005e562018-11-06 15:04:49 +01002549 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2550 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002551
Francois Gaffie716e1432019-01-14 16:58:59 +01002552 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002553 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002554 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002555
Mikhail Naganov2996f672019-04-18 12:29:59 -07002556 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002557 requestedDeviceId, attributes.source, flags,
2558 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002559 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002560 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002561
2562 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2563 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002564
Eric Laurent599c7582015-12-07 18:05:55 -08002565 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002566
2567error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002568 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002569}
2570
2571
François Gaffie11d30102018-11-02 16:09:09 +01002572audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002573 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002574 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002575 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002576 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002577 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002578{
2579 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002580 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002581 bool isSoundTrigger = false;
2582
François Gaffiec005e562018-11-06 15:04:49 +01002583 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002584 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2585 if (index >= 0) {
2586 input = mSoundTriggerSessions.valueFor(session);
2587 isSoundTrigger = true;
2588 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2589 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2590 } else {
2591 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002592 }
François Gaffiec005e562018-11-06 15:04:49 +01002593 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002594 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002595 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002596 }
2597
Carter Hsua3abb402021-10-26 11:11:20 +08002598 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2599 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2600 }
2601
Andy Hungf129b032015-04-07 13:45:50 -07002602 // find a compatible input profile (not necessarily identical in parameters)
2603 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002604 // sampling rate and flags may be updated by getInputProfile
2605 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2606 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002607 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002608 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002609 audio_input_flags_t profileFlags = flags;
2610 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002611 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002612 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002613 profileFlags);
2614 if (profile != 0) {
2615 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002616 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2617 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002618 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002619 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2620 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002621 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002622 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002623 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002624 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002625 }
Eric Laurente552edb2014-03-10 17:42:56 -07002626 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002627 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002628 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002629 if (samplingRate == 0) {
2630 samplingRate = profileSamplingRate;
2631 }
Eric Laurente552edb2014-03-10 17:42:56 -07002632
Eric Laurent322b4d22015-04-03 15:57:54 -07002633 if (profile->getModuleHandle() == 0) {
2634 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002635 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002636 }
2637
Eric Laurentec376dc2021-04-08 20:41:22 +02002638 // Reuse an already opened input if a client with the same session ID already exists
2639 // on that input
2640 for (size_t i = 0; i < mInputs.size(); i++) {
2641 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2642 if (desc->mProfile != profile) {
2643 continue;
2644 }
2645 RecordClientVector clients = desc->clientsList();
2646 for (const auto &client : clients) {
2647 if (session == client->session()) {
2648 return desc->mIoHandle;
2649 }
2650 }
2651 }
2652
Eric Laurent3974e3b2017-12-07 17:58:43 -08002653 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002654 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002655 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002656 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002657 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002658 continue;
2659 }
2660 // if sound trigger, reuse input if used by other sound trigger on same session
2661 // else
2662 // reuse input if active client app is not in IDLE state
2663 //
2664 RecordClientVector clients = desc->clientsList();
2665 bool doClose = false;
2666 for (const auto& client : clients) {
2667 if (isSoundTrigger != client->isSoundTrigger()) {
2668 continue;
2669 }
2670 if (client->isSoundTrigger()) {
2671 if (session == client->session()) {
2672 return desc->mIoHandle;
2673 }
2674 continue;
2675 }
2676 if (client->active() && client->appState() != APP_STATE_IDLE) {
2677 return desc->mIoHandle;
2678 }
2679 doClose = true;
2680 }
2681 if (doClose) {
2682 closeInput(desc->mIoHandle);
2683 } else {
2684 i++;
2685 }
2686 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002687 }
2688
Eric Laurentfe231122017-11-17 17:48:06 -08002689 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002690
Eric Laurentfe231122017-11-17 17:48:06 -08002691 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2692 lConfig.sample_rate = profileSamplingRate;
2693 lConfig.channel_mask = profileChannelMask;
2694 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002695
François Gaffie11d30102018-11-02 16:09:09 +01002696 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002697
2698 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002699 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002700 (profileSamplingRate != lConfig.sample_rate) ||
2701 !audio_formats_match(profileFormat, lConfig.format) ||
2702 (profileChannelMask != lConfig.channel_mask)) {
2703 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002704 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002705 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002706 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002707 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002708 }
Eric Laurent599c7582015-12-07 18:05:55 -08002709 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002710 }
2711
Eric Laurentc722f302014-12-10 11:21:49 -08002712 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002713
Eric Laurent599c7582015-12-07 18:05:55 -08002714 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002715 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002716
Eric Laurent599c7582015-12-07 18:05:55 -08002717 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002718}
2719
Eric Laurent4eb58f12018-12-07 16:41:02 -08002720status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002721{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002722 ALOGV("%s portId %d", __FUNCTION__, portId);
2723
2724 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2725 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002726 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002727 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002728 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002729 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002730 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002731 if (client->active()) {
2732 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2733 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002734 }
2735
Eric Laurent8f42ea12018-08-08 09:08:25 -07002736 audio_session_t session = client->session();
2737
Eric Laurent4eb58f12018-12-07 16:41:02 -08002738 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002739
Eric Laurent4eb58f12018-12-07 16:41:02 -08002740 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002741
Eric Laurent4eb58f12018-12-07 16:41:02 -08002742 status_t status = inputDesc->start();
2743 if (status != NO_ERROR) {
2744 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002745 }
Eric Laurente552edb2014-03-10 17:42:56 -07002746
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002747 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002748 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002750
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 // indicate active capture to sound trigger service if starting capture from a mic on
2752 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002753 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002754 if (device != nullptr) {
2755 status = setInputDevice(input, device, true /* force */);
2756 } else {
2757 ALOGW("%s no new input device can be found for descriptor %d",
2758 __FUNCTION__, inputDesc->getId());
2759 status = BAD_VALUE;
2760 }
Eric Laurente552edb2014-03-10 17:42:56 -07002761
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002762 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002763 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002764 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002765 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002766 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2767 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002769 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002770
François Gaffie11d30102018-11-02 16:09:09 +01002771 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2772 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002773 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002774 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002776
Eric Laurent8f42ea12018-08-08 09:08:25 -07002777 // automatically enable the remote submix output when input is started if not
2778 // used by a policy mix of type MIX_TYPE_RECORDERS
2779 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002780 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002781 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002782 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002784 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2785 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002786 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002787 if (address != "") {
2788 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2789 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002790 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002791 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002792 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002793 } else if (status != NO_ERROR) {
2794 // Restore client activity state.
2795 inputDesc->setClientActive(client, false);
2796 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002797 }
2798
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002799 ALOGV("%s input %d source = %d status = %d exit",
2800 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002801
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002802 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002803}
2804
Eric Laurent8fc147b2018-07-22 19:13:55 -07002805status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002806{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002807 ALOGV("%s portId %d", __FUNCTION__, portId);
2808
2809 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2810 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002811 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002812 return BAD_VALUE;
2813 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002814 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002815 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002816 if (!client->active()) {
2817 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002818 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002819 }
Carter Hsue6139d52021-07-08 10:30:20 +08002820 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002821 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002822
Eric Laurent8f42ea12018-08-08 09:08:25 -07002823 inputDesc->stop();
2824 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002825 auto current_source = inputDesc->source();
2826 setInputDevice(input, getNewInputDevice(inputDesc),
2827 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002829 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002830 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002831 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002832 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2833 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002834 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002835 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836
2837 // automatically disable the remote submix output when input is stopped if not
2838 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002839 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002840 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002841 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002843 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2844 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002845 }
2846 if (address != "") {
2847 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2848 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002849 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002850 }
2851 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002852 resetInputDevice(input);
2853
2854 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2855 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002856 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2857 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002858 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002859 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 }
2861 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002862 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002863 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002864}
2865
Eric Laurent8fc147b2018-07-22 19:13:55 -07002866void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002867{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002868 ALOGV("%s portId %d", __FUNCTION__, portId);
2869
2870 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2871 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002873 return;
2874 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002875 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002876 audio_io_handle_t input = inputDesc->mIoHandle;
2877
Eric Laurent8f42ea12018-08-08 09:08:25 -07002878 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002879
Andy Hung39efb7a2018-09-26 15:39:28 -07002880 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002881
Andy Hung39efb7a2018-09-26 15:39:28 -07002882 if (inputDesc->getClientCount() > 0) {
2883 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002884 return;
2885 }
2886
Eric Laurent05b90f82014-08-27 15:32:29 -07002887 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002888 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002890}
2891
Eric Laurent8f42ea12018-08-08 09:08:25 -07002892void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002893{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002894 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895
2896 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002897 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002898 }
2899}
2900
Eric Laurent8f42ea12018-08-08 09:08:25 -07002901void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2902{
2903 stopInput(portId);
2904 releaseInput(portId);
2905}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002906
Eric Laurent0dd51852019-04-19 18:18:58 -07002907void AudioPolicyManager::checkCloseInputs() {
2908 // After connecting or disconnecting an input device, close input if:
2909 // - it has no client (was just opened to check profile) OR
2910 // - none of its supported devices are connected anymore OR
2911 // - one of its clients cannot be routed to one of its supported
2912 // devices anymore. Otherwise update device selection
2913 std::vector<audio_io_handle_t> inputsToClose;
2914 for (size_t i = 0; i < mInputs.size(); i++) {
2915 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2916 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002917 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002918 inputsToClose.push_back(mInputs.keyAt(i));
2919 } else {
2920 bool close = false;
2921 for (const auto& client : input->clientsList()) {
2922 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002923 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002924 if (!input->supportedDevices().contains(device)) {
2925 close = true;
2926 break;
2927 }
2928 }
2929 if (close) {
2930 inputsToClose.push_back(mInputs.keyAt(i));
2931 } else {
2932 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2933 }
2934 }
2935 }
2936
2937 for (const audio_io_handle_t handle : inputsToClose) {
2938 ALOGV("%s closing input %d", __func__, handle);
2939 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002940 }
Eric Laurentd4692962014-05-05 18:13:44 -07002941}
2942
François Gaffie251c7f02018-11-07 10:41:08 +01002943void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002944{
2945 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002946 if (indexMin < 0 || indexMax < 0) {
2947 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2948 return;
2949 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002950 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002951
2952 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002953 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2954 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002955 continue;
2956 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002957 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002958 }
Eric Laurente552edb2014-03-10 17:42:56 -07002959}
2960
Eric Laurente0720872014-03-11 09:30:41 -07002961status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002962 int index,
2963 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002964{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002965 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002966 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2967 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2968 return NO_ERROR;
2969 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002970 ALOGV("%s: stream %s attributes=%s", __func__,
2971 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002972 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002973}
2974
Eric Laurente0720872014-03-11 09:30:41 -07002975status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002976 int *index,
2977 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002978{
François Gaffiec005e562018-11-06 15:04:49 +01002979 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2980 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002981 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002982 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002983 deviceTypes = mEngine->getOutputDevicesForStream(
2984 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002985 }
jiabin9a3361e2019-10-01 09:38:30 -07002986 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002987}
2988
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002989status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002990 int index,
2991 audio_devices_t device)
2992{
2993 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002994 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2995 if (group == VOLUME_GROUP_NONE) {
2996 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002997 return BAD_VALUE;
2998 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002999 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003000 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003001 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003002 VolumeSource vs = toVolumeSource(group);
3003 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3004
3005 status = setVolumeCurveIndex(index, device, curves);
3006 if (status != NO_ERROR) {
3007 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3008 return status;
3009 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003010
jiabin9a3361e2019-10-01 09:38:30 -07003011 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003012 auto curCurvAttrs = curves.getAttributes();
3013 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3014 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003015 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003016 } else if (!curves.getStreamTypes().empty()) {
3017 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003018 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003019 } else {
3020 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3021 return BAD_VALUE;
3022 }
jiabin9a3361e2019-10-01 09:38:30 -07003023 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3024 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003025
François Gaffiecfe17322018-11-07 13:41:29 +01003026 // update volume on all outputs and streams matching the following:
3027 // - The requested stream (or a stream matching for volume control) is active on the output
3028 // - The device (or devices) selected by the engine for this stream includes
3029 // the requested device
3030 // - For non default requested device, currently selected device on the output is either the
3031 // requested device or one of the devices selected by the engine for this stream
3032 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3033 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003034 for (size_t i = 0; i < mOutputs.size(); i++) {
3035 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003036 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003037
jiabin9a3361e2019-10-01 09:38:30 -07003038 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3039 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003040 }
François Gaffieed91f582020-01-31 10:35:37 +01003041 if (!(desc->isActive(vs) || isInCall())) {
3042 continue;
3043 }
3044 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3045 curDevices.find(device) == curDevices.end()) {
3046 continue;
3047 }
3048 bool applyVolume = false;
3049 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3050 curSrcDevices.insert(device);
3051 applyVolume = (curSrcDevices.find(
3052 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3053 } else {
3054 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3055 }
3056 if (!applyVolume) {
3057 continue; // next output
3058 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003059 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3060 // If a higher priority strategy is active, and the output is routed to a device with a
3061 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003062 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003063 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003064 // If the volume source is active with higher priority source, ensure at least Sw Muted
3065 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003066 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3067 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3068 false /*preferredDevice*/);
3069 if (activeClients.empty()) {
3070 continue;
3071 }
3072 bool isPreempted = false;
3073 bool isHigherPriority = productStrategy < strategy;
3074 for (const auto &client : activeClients) {
3075 if (isHigherPriority && (client->volumeSource() != vs)) {
3076 ALOGV("%s: Strategy=%d (\nrequester:\n"
3077 " group %d, volumeGroup=%d attributes=%s)\n"
3078 " higher priority source active:\n"
3079 " volumeGroup=%d attributes=%s) \n"
3080 " on output %zu, bailing out", __func__, productStrategy,
3081 group, group, toString(attributes).c_str(),
3082 client->volumeSource(), toString(client->attributes()).c_str(), i);
3083 applyVolume = false;
3084 isPreempted = true;
3085 break;
3086 }
3087 // However, continue for loop to ensure no higher prio clients running on output
3088 if (client->volumeSource() == vs) {
3089 applyVolume = true;
3090 }
3091 }
3092 if (isPreempted || applyVolume) {
3093 break;
3094 }
3095 }
3096 if (!applyVolume) {
3097 continue; // next output
3098 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003099 }
François Gaffieed91f582020-01-31 10:35:37 +01003100 //FIXME: workaround for truncated touch sounds
3101 // delayed volume change for system stream to be removed when the problem is
3102 // handled by system UI
3103 status_t volStatus = checkAndSetVolume(
3104 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003105 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003106 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3107 if (volStatus != NO_ERROR) {
3108 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003109 }
3110 }
François Gaffiecfe17322018-11-07 13:41:29 +01003111 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3112 return status;
3113}
3114
François Gaffieaaac0fd2018-11-22 17:56:39 +01003115status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003116 audio_devices_t device,
3117 IVolumeCurves &volumeCurves)
3118{
3119 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3120 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003121 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3122 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003123 (index > volumeCurves.getVolumeIndexMax())) {
3124 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3125 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3126 return BAD_VALUE;
3127 }
3128 if (!audio_is_output_device(device)) {
3129 return BAD_VALUE;
3130 }
3131
3132 // Force max volume if stream cannot be muted
3133 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3134
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003136 volumeCurves.addCurrentVolumeIndex(device, index);
3137 return NO_ERROR;
3138}
3139
3140status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3141 int &index,
3142 audio_devices_t device)
3143{
3144 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3145 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003146 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003147 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003148 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3149 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003150 }
jiabin9a3361e2019-10-01 09:38:30 -07003151 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003152}
3153
3154status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3155 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003156 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003157{
jiabin9a3361e2019-10-01 09:38:30 -07003158 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003159 return BAD_VALUE;
3160 }
jiabin9a3361e2019-10-01 09:38:30 -07003161 index = curves.getVolumeIndex(deviceTypes);
3162 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003163 return NO_ERROR;
3164}
3165
3166status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3167 int &index)
3168{
3169 index = getVolumeCurves(attr).getVolumeIndexMin();
3170 return NO_ERROR;
3171}
3172
3173status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3174 int &index)
3175{
3176 index = getVolumeCurves(attr).getVolumeIndexMax();
3177 return NO_ERROR;
3178}
3179
Eric Laurent36829f92017-04-07 19:04:42 -07003180audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003181{
3182 // select one output among several suitable for global effects.
3183 // The priority is as follows:
3184 // 1: An offloaded output. If the effect ends up not being offloadable,
3185 // AudioFlinger will invalidate the track and the offloaded output
3186 // will be closed causing the effect to be moved to a PCM output.
3187 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003188 // 3: The primary output
3189 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003190
François Gaffiec005e562018-11-06 15:04:49 +01003191 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3192 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003193 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003194
Eric Laurent36829f92017-04-07 19:04:42 -07003195 if (outputs.size() == 0) {
3196 return AUDIO_IO_HANDLE_NONE;
3197 }
Eric Laurente552edb2014-03-10 17:42:56 -07003198
Eric Laurent36829f92017-04-07 19:04:42 -07003199 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3200 bool activeOnly = true;
3201
3202 while (output == AUDIO_IO_HANDLE_NONE) {
3203 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3204 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3205 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3206
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003207 for (audio_io_handle_t output : outputs) {
3208 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003209 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003210 continue;
3211 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003212 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3213 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003214 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003215 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003216 }
3217 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003218 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003219 }
3220 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003221 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003222 }
3223 }
3224 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3225 output = outputOffloaded;
3226 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3227 output = outputDeepBuffer;
3228 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3229 output = outputPrimary;
3230 } else {
3231 output = outputs[0];
3232 }
3233 activeOnly = false;
3234 }
3235
3236 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003237 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003238 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3239 mMusicEffectOutput = output;
3240 }
3241
3242 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003243 return output;
3244}
3245
Eric Laurent36829f92017-04-07 19:04:42 -07003246audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3247{
3248 return selectOutputForMusicEffects();
3249}
3250
Eric Laurente0720872014-03-11 09:30:41 -07003251status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003252 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003253 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003254 int session,
3255 int id)
3256{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003257 if (session != AUDIO_SESSION_DEVICE) {
3258 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003259 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003260 index = mInputs.indexOfKey(io);
3261 if (index < 0) {
3262 ALOGW("registerEffect() unknown io %d", io);
3263 return INVALID_OPERATION;
3264 }
Eric Laurente552edb2014-03-10 17:42:56 -07003265 }
3266 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003267 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3268 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3269 || strategy == PRODUCT_STRATEGY_NONE));
3270 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003271}
3272
Eric Laurentc241b0d2018-11-28 09:08:49 -08003273status_t AudioPolicyManager::unregisterEffect(int id)
3274{
3275 if (mEffects.getEffect(id) == nullptr) {
3276 return INVALID_OPERATION;
3277 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003278 if (mEffects.isEffectEnabled(id)) {
3279 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3280 setEffectEnabled(id, false);
3281 }
3282 return mEffects.unregisterEffect(id);
3283}
3284
3285status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3286{
3287 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3288 if (effect == nullptr) {
3289 return INVALID_OPERATION;
3290 }
3291
3292 status_t status = mEffects.setEffectEnabled(id, enabled);
3293 if (status == NO_ERROR) {
3294 mInputs.trackEffectEnabled(effect, enabled);
3295 }
3296 return status;
3297}
3298
Eric Laurent6c796322019-04-09 14:13:17 -07003299
3300status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3301{
3302 mEffects.moveEffects(ids, io);
3303 return NO_ERROR;
3304}
3305
Eric Laurentc75307b2015-03-17 15:29:32 -07003306bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3307{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003308 auto vs = toVolumeSource(stream, false);
3309 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003310}
3311
3312bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3313{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003314 auto vs = toVolumeSource(stream, false);
3315 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003316}
3317
Eric Laurente0720872014-03-11 09:30:41 -07003318bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003319{
3320 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003321 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003322 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003323 return true;
3324 }
3325 }
3326 return false;
3327}
3328
Eric Laurent275e8e92014-11-30 15:14:47 -08003329// Register a list of custom mixes with their attributes and format.
3330// When a mix is registered, corresponding input and output profiles are
3331// added to the remote submix hw module. The profile contains only the
3332// parameters (sampling rate, format...) specified by the mix.
3333// The corresponding input remote submix device is also connected.
3334//
3335// When a remote submix device is connected, the address is checked to select the
3336// appropriate profile and the corresponding input or output stream is opened.
3337//
3338// When capture starts, getInputForAttr() will:
3339// - 1 look for a mix matching the address passed in attribtutes tags if any
3340// - 2 if none found, getDeviceForInputSource() will:
3341// - 2.1 look for a mix matching the attributes source
3342// - 2.2 if none found, default to device selection by policy rules
3343// At this time, the corresponding output remote submix device is also connected
3344// and active playback use cases can be transferred to this mix if needed when reconnecting
3345// after AudioTracks are invalidated
3346//
3347// When playback starts, getOutputForAttr() will:
3348// - 1 look for a mix matching the address passed in attribtutes tags if any
3349// - 2 if none found, look for a mix matching the attributes usage
3350// - 3 if none found, default to device and output selection by policy rules.
3351
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003352status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003353{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003354 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3355 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003356 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003357 sp<HwModule> rSubmixModule;
3358 // examine each mix's route type
3359 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003360 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003361 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3362 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3363 ALOGE("Unsupported Policy Mix %zu of %zu: "
3364 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3365 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003366 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003367 break;
3368 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003369 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3370 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003371 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003372 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3373 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003374 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003375 rSubmixModule = mHwModules.getModuleFromName(
3376 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3377 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003378 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003379 i);
3380 res = INVALID_OPERATION;
3381 break;
3382 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003383 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003384
Eric Laurent97ac8712018-07-27 18:59:02 -07003385 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003386 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003387 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003388 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003389 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3390 } else {
3391 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3392 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003393 }
François Gaffie036e1e92015-03-19 10:16:24 +01003394
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003395 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003396 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003397 res = INVALID_OPERATION;
3398 break;
3399 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003400 audio_config_t outputConfig = mix.mFormat;
3401 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003402 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3403 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003404 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3405 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003406 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003407 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003408 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003409 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003410
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003411 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003412 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3413 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3414 ALOGE("Failed to set remote submix device available, type %u, address %s",
3415 mix.mDeviceType, address.string());
3416 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003417 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003418 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3419 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003420 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003421 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003422 i, mixes.size(), type, address.string());
3423
3424 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3425 mix.mDeviceType, mix.mDeviceAddress,
3426 String8(), AUDIO_FORMAT_DEFAULT);
3427 if (device == nullptr) {
3428 res = INVALID_OPERATION;
3429 break;
3430 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003431
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003432 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003433 // First try to find an already opened output supporting the device
3434 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003435 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003436
Eric Laurentc529cf62020-04-17 18:19:10 -07003437 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003438 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003439 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3440 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003441 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003442 } else {
3443 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003444 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003445 }
3446 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003447 // If no output found, try to find a direct output profile supporting the device
3448 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3449 sp<HwModule> module = mHwModules[i];
3450 for (size_t j = 0;
3451 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3452 j++) {
3453 sp<IOProfile> profile = module->getOutputProfiles()[j];
3454 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3455 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3456 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3457 address.string());
3458 res = INVALID_OPERATION;
3459 } else {
3460 foundOutput = true;
3461 }
3462 }
3463 }
3464 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003465 if (res != NO_ERROR) {
3466 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003467 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003468 res = INVALID_OPERATION;
3469 break;
3470 } else if (!foundOutput) {
3471 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003472 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003473 res = INVALID_OPERATION;
3474 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003475 } else {
3476 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003477 }
Eric Laurentc722f302014-12-10 11:21:49 -08003478 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003479 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003480 if (res != NO_ERROR) {
3481 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003482 } else if (checkOutputs) {
3483 checkForDeviceAndOutputChanges();
3484 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003485 }
3486 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003487}
3488
3489status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3490{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003491 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003492 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003493 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003494 sp<HwModule> rSubmixModule;
3495 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003496 for (const auto& mix : mixes) {
3497 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003498
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003499 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003500 rSubmixModule = mHwModules.getModuleFromName(
3501 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3502 if (rSubmixModule == 0) {
3503 res = INVALID_OPERATION;
3504 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003505 }
3506 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003507
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003508 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003509
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003510 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003511 res = INVALID_OPERATION;
3512 continue;
3513 }
3514
Kevin Rocard04ed0462019-05-02 17:53:24 -07003515 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3516 if (getDeviceConnectionState(device, address.string()) ==
3517 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3518 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3519 address.string(), "remote-submix",
3520 AUDIO_FORMAT_DEFAULT);
3521 if (res != OK) {
3522 ALOGE("Error making RemoteSubmix device unavailable for mix "
3523 "with type %d, address %s", device, address.string());
3524 }
3525 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003526 }
jiabin5740f082019-08-19 15:08:30 -07003527 rSubmixModule->removeOutputProfile(address.c_str());
3528 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003529
Kevin Rocard153f92d2018-12-18 18:33:28 -08003530 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003531 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003532 res = INVALID_OPERATION;
3533 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003534 } else {
3535 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003536 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003537 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003538 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003539 if (res == NO_ERROR && checkOutputs) {
3540 checkForDeviceAndOutputChanges();
3541 updateCallAndOutputRouting();
3542 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003544}
3545
Mikhail Naganov100f0122018-11-29 11:22:16 -08003546void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3547{
3548 size_t i = 0;
3549 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3550 for (const auto& fmt : mManualSurroundFormats) {
3551 if (i++ != 0) dst->append(", ");
3552 std::string sfmt;
3553 FormatConverter::toString(fmt, sfmt);
3554 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3555 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3556 }
3557}
3558
Eric Laurentc529cf62020-04-17 18:19:10 -07003559// Returns true if all devices types match the predicate and are supported by one HW module
3560bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003561 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003562 std::function<bool(audio_devices_t)> predicate,
3563 const char *context) {
3564 for (size_t i = 0; i < devices.size(); i++) {
3565 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003566 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003567 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003568 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003569 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003570 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003571 return false;
3572 }
3573 }
3574 return true;
3575}
3576
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003577status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003578 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003579 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003580 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3581 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003582 }
3583 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003584 if (res != NO_ERROR) {
3585 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3586 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003587 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003588
3589 checkForDeviceAndOutputChanges();
3590 updateCallAndOutputRouting();
3591
3592 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003593}
3594
3595status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3596 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003597 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3598 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003599 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003600 __FUNCTION__, uid);
3601 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003602 }
3603
Eric Laurentc529cf62020-04-17 18:19:10 -07003604 checkForDeviceAndOutputChanges();
3605 updateCallAndOutputRouting();
3606
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003607 return res;
3608}
3609
Eric Laurent2517af32020-11-25 15:31:27 +01003610
jiabin0a488932020-08-07 17:32:40 -07003611status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3612 device_role_t role,
3613 const AudioDeviceTypeAddrVector &devices) {
3614 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3615 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003616
Eric Laurentc529cf62020-04-17 18:19:10 -07003617 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003618 return BAD_VALUE;
3619 }
jiabin0a488932020-08-07 17:32:40 -07003620 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003621 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003622 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3623 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003624 return status;
3625 }
3626
3627 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003628
3629 bool forceVolumeReeval = false;
3630 // FIXME: workaround for truncated touch sounds
3631 // to be removed when the problem is handled by system UI
3632 uint32_t delayMs = 0;
3633 if (strategy == mCommunnicationStrategy) {
3634 forceVolumeReeval = true;
3635 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3636 updateInputRouting();
3637 }
3638 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003639
3640 return NO_ERROR;
3641}
3642
3643void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3644{
3645 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003646 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003647 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003648 // Only apply special touch sound delay once
3649 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003650 }
3651 for (size_t i = 0; i < mOutputs.size(); i++) {
3652 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3653 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003654 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3655 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003656 // As done in setDeviceConnectionState, we could also fix default device issue by
3657 // preventing the force re-routing in case of default dev that distinguishes on address.
3658 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003659 bool forceRouting = !newDevices.isEmpty();
3660 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3661 true /*requiresMuteCheck*/,
3662 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003663 // Only apply special touch sound delay once
3664 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003665 }
3666 if (forceVolumeReeval && !newDevices.isEmpty()) {
3667 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3668 }
3669 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003670 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003671}
3672
Eric Laurent2517af32020-11-25 15:31:27 +01003673void AudioPolicyManager::updateInputRouting() {
3674 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303675 // Skip for hotword recording as the input device switch
3676 // is handled within sound trigger HAL
3677 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3678 continue;
3679 }
Eric Laurent2517af32020-11-25 15:31:27 +01003680 auto newDevice = getNewInputDevice(activeDesc);
3681 // Force new input selection if the new device can not be reached via current input
3682 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3683 setInputDevice(activeDesc->mIoHandle, newDevice);
3684 } else {
3685 closeInput(activeDesc->mIoHandle);
3686 }
3687 }
3688}
3689
jiabin0a488932020-08-07 17:32:40 -07003690status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3691 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003692{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003693 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003694
jiabin0a488932020-08-07 17:32:40 -07003695 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003696 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003697 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3698 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003699 return status;
3700 }
3701
3702 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003703
3704 bool forceVolumeReeval = false;
3705 // FIXME: workaround for truncated touch sounds
3706 // to be removed when the problem is handled by system UI
3707 uint32_t delayMs = 0;
3708 if (strategy == mCommunnicationStrategy) {
3709 forceVolumeReeval = true;
3710 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3711 updateInputRouting();
3712 }
3713 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003714
3715 return NO_ERROR;
3716}
3717
jiabin0a488932020-08-07 17:32:40 -07003718status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3719 device_role_t role,
3720 AudioDeviceTypeAddrVector &devices) {
3721 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003722}
3723
Jiabin Huang3b98d322020-09-03 17:54:16 +00003724status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3725 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3726 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3727 dumpAudioDeviceTypeAddrVector(devices).c_str());
3728
Mikhail Naganov55773032020-10-01 15:08:13 -07003729 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003730 return BAD_VALUE;
3731 }
3732 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3733 ALOGW_IF(status != NO_ERROR,
3734 "Engine could not set preferred devices %s for audio source %d role %d",
3735 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3736
3737 return status;
3738}
3739
3740status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3741 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3742 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3743 dumpAudioDeviceTypeAddrVector(devices).c_str());
3744
Mikhail Naganov55773032020-10-01 15:08:13 -07003745 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003746 return BAD_VALUE;
3747 }
3748 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3749 ALOGW_IF(status != NO_ERROR,
3750 "Engine could not add preferred devices %s for audio source %d role %d",
3751 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3752
Eric Laurent2517af32020-11-25 15:31:27 +01003753 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003754 return status;
3755}
3756
3757status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3758 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3759{
3760 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3761 dumpAudioDeviceTypeAddrVector(devices).c_str());
3762
Mikhail Naganov55773032020-10-01 15:08:13 -07003763 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003764 return BAD_VALUE;
3765 }
3766
3767 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3768 audioSource, role, devices);
3769 ALOGW_IF(status != NO_ERROR,
3770 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3771
Eric Laurent2517af32020-11-25 15:31:27 +01003772 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003773 return status;
3774}
3775
3776status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3777 device_role_t role) {
3778 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3779
3780 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3781 ALOGW_IF(status != NO_ERROR,
3782 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3783
Eric Laurent2517af32020-11-25 15:31:27 +01003784 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003785 return status;
3786}
3787
3788status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3789 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3790 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3791}
3792
Oscar Azucena90e77632019-11-27 17:12:28 -08003793status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003794 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003795 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003796 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3797 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003798 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003799 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3800 if (status != NO_ERROR) {
3801 ALOGE("%s() could not set device affinity for userId %d",
3802 __FUNCTION__, userId);
3803 return status;
3804 }
3805
3806 // reevaluate outputs for all devices
3807 checkForDeviceAndOutputChanges();
3808 updateCallAndOutputRouting();
3809
3810 return NO_ERROR;
3811}
3812
3813status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003814 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003815 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3816 if (status != NO_ERROR) {
3817 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3818 __FUNCTION__, userId);
3819 return status;
3820 }
3821
3822 // reevaluate outputs for all devices
3823 checkForDeviceAndOutputChanges();
3824 updateCallAndOutputRouting();
3825
3826 return NO_ERROR;
3827}
3828
Andy Hungc29d82b2018-10-05 12:23:17 -07003829void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003830{
Andy Hungc29d82b2018-10-05 12:23:17 -07003831 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003832 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003833 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003834 std::string stateLiteral;
3835 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003836 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003837 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3838 "communications", "media", "record", "dock", "system",
3839 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3840 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3841 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003842 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3843 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3844 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3845 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3846 dst->append(" (MANUAL: ");
3847 dumpManualSurroundFormats(dst);
3848 dst->append(")");
3849 }
3850 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003851 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003852 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3853 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003854 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003855 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003856
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003857 dst->append("\n");
3858 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3859 dst->append("\n");
3860 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003861 mHwModulesAll.dump(dst);
3862 mOutputs.dump(dst);
3863 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003864 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003865 mAudioPatches.dump(dst);
3866 mPolicyMixes.dump(dst);
3867 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003868
Kevin Rocardb99cc752019-03-21 20:52:24 -07003869 dst->appendFormat(" AllowedCapturePolicies:\n");
3870 for (auto& policy : mAllowedCapturePolicies) {
3871 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3872 }
3873
François Gaffiec005e562018-11-06 15:04:49 +01003874 dst->appendFormat("\nPolicy Engine dump:\n");
3875 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003876}
3877
3878status_t AudioPolicyManager::dump(int fd)
3879{
3880 String8 result;
3881 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003882 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003883 return NO_ERROR;
3884}
3885
Kevin Rocardb99cc752019-03-21 20:52:24 -07003886status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3887{
3888 mAllowedCapturePolicies[uid] = capturePolicy;
3889 return NO_ERROR;
3890}
3891
Eric Laurente552edb2014-03-10 17:42:56 -07003892// This function checks for the parameters which can be offloaded.
3893// This can be enhanced depending on the capability of the DSP and policy
3894// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003895audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003896{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003897 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003898 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003899 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003900 offloadInfo.format,
3901 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3902 offloadInfo.has_video);
3903
jiabin2b9d5a12021-12-10 01:06:29 +00003904 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003905 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003906 }
3907
3908 // See if there is a profile to support this.
3909 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003910 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003911 offloadInfo.sample_rate,
3912 offloadInfo.format,
3913 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003914 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3915 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003916 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3917 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3918 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003919 if (profile == nullptr) {
3920 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3921 }
3922 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3923 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3924 }
3925 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003926}
3927
Michael Chana94fbb22018-04-24 14:31:19 +10003928bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3929 const audio_attributes_t& attributes) {
3930 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003931 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003932 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3933 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003934 config.sample_rate,
3935 config.format,
3936 config.channel_mask,
3937 output_flags,
3938 true /* directOnly */);
3939 ALOGV("%s() profile %sfound with name: %s, "
3940 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3941 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003942 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003943 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003944
3945 // also try the MSD module if compatible profile not found
3946 if (profile == nullptr) {
3947 profile = getMsdProfileForOutput(outputDevices,
3948 config.sample_rate,
3949 config.format,
3950 config.channel_mask,
3951 output_flags,
3952 true /* directOnly */);
3953 ALOGV("%s() MSD profile %sfound with name: %s, "
3954 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3955 __FUNCTION__, profile != 0 ? "" : "NOT ",
3956 (profile != 0 ? profile->getTagName().c_str() : "null"),
3957 config.sample_rate, config.format, config.channel_mask, output_flags);
3958 }
3959 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003960}
3961
jiabin2b9d5a12021-12-10 01:06:29 +00003962bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3963 bool durationIgnored) {
3964 if (mMasterMono) {
3965 return false; // no offloading if mono is set.
3966 }
3967
3968 // Check if offload has been disabled
3969 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3970 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3971 return false;
3972 }
3973
3974 // Check if stream type is music, then only allow offload as of now.
3975 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3976 {
3977 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3978 return false;
3979 }
3980
3981 //TODO: enable audio offloading with video when ready
3982 const bool allowOffloadWithVideo =
3983 property_get_bool("audio.offload.video", false /* default_value */);
3984 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3985 ALOGV("%s: has_video == true, returning false", __func__);
3986 return false;
3987 }
3988
3989 //If duration is less than minimum value defined in property, return false
3990 const int min_duration_secs = property_get_int32(
3991 "audio.offload.min.duration.secs", -1 /* default_value */);
3992 if (!durationIgnored) {
3993 if (min_duration_secs >= 0) {
3994 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3995 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3996 __func__, min_duration_secs);
3997 return false;
3998 }
3999 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4000 ALOGV("%s: Offload denied by duration < default min(=%u)",
4001 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4002 return false;
4003 }
4004 }
4005
4006 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4007 // creating an offloaded track and tearing it down immediately after start when audioflinger
4008 // detects there is an active non offloadable effect.
4009 // FIXME: We should check the audio session here but we do not have it in this context.
4010 // This may prevent offloading in rare situations where effects are left active by apps
4011 // in the background.
4012 if (mEffects.isNonOffloadableEffectEnabled()) {
4013 return false;
4014 }
4015
4016 return true;
4017}
4018
4019audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4020 const audio_config_t *config) {
4021 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4022 offloadInfo.format = config->format;
4023 offloadInfo.sample_rate = config->sample_rate;
4024 offloadInfo.channel_mask = config->channel_mask;
4025 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4026 offloadInfo.has_video = false;
4027 offloadInfo.is_streaming = false;
4028 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4029
4030 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4031 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4032 audio_flags_to_audio_output_flags(attr->flags, &flags);
4033 // only retain flags that will drive compressed offload or passthrough
4034 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4035 if (offloadPossible) {
4036 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4037 }
4038 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4039
Dorin Drimusfae3c642022-03-17 18:36:30 +01004040 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004041 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004042 DeviceVector outputDevices = engineOutputDevices;
4043 // the MSD module checks for different conditions and output devices
4044 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4045 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4046 continue;
4047 }
4048 outputDevices = getMsdAudioOutDevices();
4049 }
jiabin2b9d5a12021-12-10 01:06:29 +00004050 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004051 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004052 config->sample_rate, nullptr /*updatedSamplingRate*/,
4053 config->format, nullptr /*updatedFormat*/,
4054 config->channel_mask, nullptr /*updatedChannelMask*/,
4055 flags)) {
4056 continue;
4057 }
4058 // reject profiles not corresponding to a device currently available
4059 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4060 continue;
4061 }
4062 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4063 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004064 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004065 != AUDIO_DIRECT_NOT_SUPPORTED) {
4066 // Already reports offload gapless supported. No need to report offload support.
4067 continue;
4068 }
4069 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4070 != AUDIO_OUTPUT_FLAG_NONE) {
4071 // If offload gapless is reported, no need to report offload support.
4072 directMode = (audio_direct_mode_t) ((directMode &
4073 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4074 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4075 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004076 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004077 }
4078 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004079 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004080 }
4081 }
4082 }
4083 return directMode;
4084}
4085
Dorin Drimusf2196d82022-01-03 12:11:18 +01004086status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4087 AudioProfileVector& audioProfilesVector) {
4088 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004089 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004090 if (status != OK) {
4091 return status;
4092 }
4093 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4094 if (devices.empty()) {
4095 return OK; // no output devices for the attributes
4096 }
4097
4098 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004099 // the MSD module checks for different conditions
4100 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4101 continue;
4102 }
4103 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4104 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004105 continue;
4106 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004107 // allow only profiles that support all the available and routed devices
4108 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004109 != devices.size()) {
4110 continue;
4111 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004112 audioProfilesVector.addAllValidProfiles(
4113 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004114 }
4115 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004116
4117 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4118 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4119 if (msdModule != nullptr) {
4120 if (msdHasPatchesToAllDevices(devices)) {
4121 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4122 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4123 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4124 continue;
4125 }
4126 audioProfilesVector.addAllValidProfiles(
4127 outputProfile->asAudioPort()->getAudioProfiles());
4128 }
4129 } else {
4130 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4131 }
4132 }
4133
Dorin Drimusf2196d82022-01-03 12:11:18 +01004134 return NO_ERROR;
4135}
4136
Eric Laurent6a94d692014-05-20 11:18:06 -07004137status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4138 audio_port_type_t type,
4139 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004140 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004141 unsigned int *generation)
4142{
jiabin19cdba52020-11-24 11:28:58 -08004143 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4144 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004145 return BAD_VALUE;
4146 }
4147 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004148 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004149 *num_ports = 0;
4150 }
4151
4152 size_t portsWritten = 0;
4153 size_t portsMax = *num_ports;
4154 *num_ports = 0;
4155 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004156 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4157 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004158 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004159 for (const auto& dev : mAvailableOutputDevices) {
4160 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004161 continue;
4162 }
4163 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004164 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004165 }
4166 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004168 }
4169 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004170 for (const auto& dev : mAvailableInputDevices) {
4171 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004172 continue;
4173 }
4174 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004175 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004176 }
4177 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004178 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 }
4180 }
4181 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4182 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4183 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4184 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4185 }
4186 *num_ports += mInputs.size();
4187 }
4188 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004189 size_t numOutputs = 0;
4190 for (size_t i = 0; i < mOutputs.size(); i++) {
4191 if (!mOutputs[i]->isDuplicated()) {
4192 numOutputs++;
4193 if (portsWritten < portsMax) {
4194 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4195 }
4196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004197 }
Eric Laurent84c70242014-06-23 08:46:27 -07004198 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004199 }
4200 }
4201 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004202 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 return NO_ERROR;
4204}
4205
jiabin19cdba52020-11-24 11:28:58 -08004206status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004207{
Eric Laurent99fcae42018-05-17 16:59:18 -07004208 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4209 return BAD_VALUE;
4210 }
4211 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4212 if (dev != 0) {
4213 dev->toAudioPort(port);
4214 return NO_ERROR;
4215 }
4216 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4217 if (dev != 0) {
4218 dev->toAudioPort(port);
4219 return NO_ERROR;
4220 }
4221 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4222 if (out != 0) {
4223 out->toAudioPort(port);
4224 return NO_ERROR;
4225 }
4226 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4227 if (in != 0) {
4228 in->toAudioPort(port);
4229 return NO_ERROR;
4230 }
4231 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004232}
4233
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004234status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4235 audio_patch_handle_t *handle,
4236 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004237{
François Gaffieafd4cea2019-11-18 15:50:22 +01004238 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004239 if (handle == NULL || patch == NULL) {
4240 return BAD_VALUE;
4241 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004242 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004243 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004244 return BAD_VALUE;
4245 }
4246 // only one source per audio patch supported for now
4247 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004248 return INVALID_OPERATION;
4249 }
Eric Laurent874c42872014-08-08 15:13:39 -07004250 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004251 return INVALID_OPERATION;
4252 }
Eric Laurent874c42872014-08-08 15:13:39 -07004253 for (size_t i = 0; i < patch->num_sinks; i++) {
4254 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4255 return INVALID_OPERATION;
4256 }
4257 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004258
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004259 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4260 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4261 if (srcDevice == nullptr || sinkDevice == nullptr) {
4262 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4263 return BAD_VALUE;
4264 }
4265 ALOGV("%s between source %s and sink %s", __func__,
4266 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4267 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4268 // Default attributes, default volume priority, not to infer with non raw audio patches.
4269 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4270 const struct audio_port_config *source = &patch->sources[0];
4271 sp<SourceClientDescriptor> sourceDesc =
4272 new InternalSourceClientDescriptor(
4273 portId, uid, attributes, *source, srcDevice, sinkDevice,
4274 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4275
4276 status_t status =
4277 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4278
4279 if (status != NO_ERROR) {
4280 return INVALID_OPERATION;
4281 }
4282 mAudioSources.add(portId, sourceDesc);
4283 return NO_ERROR;
4284}
4285
4286status_t AudioPolicyManager::connectAudioSourceToSink(
4287 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4288 const struct audio_patch *patch,
4289 audio_patch_handle_t &handle,
4290 uid_t uid, uint32_t delayMs)
4291{
4292 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4293 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4294 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4295 return INVALID_OPERATION;
4296 }
4297 sourceDesc->connect(handle, sinkDevice);
4298 if (isMsdPatch(handle)) {
4299 return NO_ERROR;
4300 }
4301 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4302 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4303 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4304 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4305 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4306 goto FailurePatchAdded;
4307 }
4308 status = swOutput->start();
4309 if (status != NO_ERROR) {
4310 goto FailureSourceAdded;
4311 }
4312 swOutput->addClient(sourceDesc);
4313 status = startSource(swOutput, sourceDesc, &delayMs);
4314 if (status != NO_ERROR) {
4315 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4316 goto FailureSourceActive;
4317 }
4318 if (delayMs != 0) {
4319 usleep(delayMs * 1000);
4320 }
4321 return NO_ERROR;
4322
4323FailureSourceActive:
4324 swOutput->stop();
4325 releaseOutput(sourceDesc->portId());
4326FailureSourceAdded:
4327 sourceDesc->setSwOutput(nullptr);
4328FailurePatchAdded:
4329 releaseAudioPatchInternal(handle);
4330 return INVALID_OPERATION;
4331}
4332
4333status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4334 audio_patch_handle_t *handle,
4335 uid_t uid, uint32_t delayMs,
4336 const sp<SourceClientDescriptor>& sourceDesc)
4337{
4338 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004339 sp<AudioPatch> patchDesc;
4340 ssize_t index = mAudioPatches.indexOfKey(*handle);
4341
François Gaffieafd4cea2019-11-18 15:50:22 +01004342 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4343 patch->sources[0].role,
4344 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004345#if LOG_NDEBUG == 0
4346 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004347 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4348 patch->sinks[i].role,
4349 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004350 }
4351#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004352
4353 if (index >= 0) {
4354 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004355 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4356 __func__, mUidCached, patchDesc->getUid(), uid);
4357 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004358 return INVALID_OPERATION;
4359 }
4360 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004361 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004362 }
4363
4364 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004365 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004366 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004367 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004368 return BAD_VALUE;
4369 }
Eric Laurent84c70242014-06-23 08:46:27 -07004370 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4371 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004372 if (patchDesc != 0) {
4373 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004374 ALOGV("%s source id differs for patch current id %d new id %d",
4375 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004376 return BAD_VALUE;
4377 }
4378 }
Eric Laurent874c42872014-08-08 15:13:39 -07004379 DeviceVector devices;
4380 for (size_t i = 0; i < patch->num_sinks; i++) {
4381 // Only support mix to devices connection
4382 // TODO add support for mix to mix connection
4383 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004384 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004385 return INVALID_OPERATION;
4386 }
4387 sp<DeviceDescriptor> devDesc =
4388 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4389 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004390 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004391 return BAD_VALUE;
4392 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004393
François Gaffie11d30102018-11-02 16:09:09 +01004394 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004395 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004396 NULL, // updatedSamplingRate
4397 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004398 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004399 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004400 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004401 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004402 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004403 return INVALID_OPERATION;
4404 }
4405 devices.add(devDesc);
4406 }
4407 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004408 return INVALID_OPERATION;
4409 }
Eric Laurent874c42872014-08-08 15:13:39 -07004410
Eric Laurent6a94d692014-05-20 11:18:06 -07004411 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004412 ALOGV("%s setting device %s on output %d",
4413 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004414 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004415 index = mAudioPatches.indexOfKey(*handle);
4416 if (index >= 0) {
4417 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004418 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 }
4420 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004421 patchDesc->setUid(uid);
4422 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004423 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004424 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004425 return INVALID_OPERATION;
4426 }
4427 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4428 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4429 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004430 // only one sink supported when connecting an input device to a mix
4431 if (patch->num_sinks > 1) {
4432 return INVALID_OPERATION;
4433 }
François Gaffie53615e22015-03-19 09:24:12 +01004434 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 if (inputDesc == NULL) {
4436 return BAD_VALUE;
4437 }
4438 if (patchDesc != 0) {
4439 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4440 return BAD_VALUE;
4441 }
4442 }
François Gaffie11d30102018-11-02 16:09:09 +01004443 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004444 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004445 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 return BAD_VALUE;
4447 }
4448
François Gaffie11d30102018-11-02 16:09:09 +01004449 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004450 patch->sinks[0].sample_rate,
4451 NULL, /*updatedSampleRate*/
4452 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004453 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004454 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004455 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004456 // FIXME for the parameter type,
4457 // and the NONE
4458 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004459 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004460 return INVALID_OPERATION;
4461 }
4462 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004463 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004464 device->toString().c_str(), inputDesc->mIoHandle);
4465 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 index = mAudioPatches.indexOfKey(*handle);
4467 if (index >= 0) {
4468 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004469 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 }
4471 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004472 patchDesc->setUid(uid);
4473 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004474 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004475 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004476 return INVALID_OPERATION;
4477 }
4478 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4479 // device to device connection
4480 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004481 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004482 return BAD_VALUE;
4483 }
4484 }
François Gaffie11d30102018-11-02 16:09:09 +01004485 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004486 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004487 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004488 return BAD_VALUE;
4489 }
Eric Laurent874c42872014-08-08 15:13:39 -07004490
Eric Laurent6a94d692014-05-20 11:18:06 -07004491 //update source and sink with our own data as the data passed in the patch may
4492 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004493 PatchBuilder patchBuilder;
4494 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004495
4496 // if first sink is to MSD, establish single MSD patch
4497 if (getMsdAudioOutDevices().contains(
4498 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4499 ALOGV("%s patching to MSD", __FUNCTION__);
4500 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4501 goto installPatch;
4502 }
4503
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4505 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004506
Eric Laurent874c42872014-08-08 15:13:39 -07004507 for (size_t i = 0; i < patch->num_sinks; i++) {
4508 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004509 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004510 return INVALID_OPERATION;
4511 }
François Gaffie11d30102018-11-02 16:09:09 +01004512 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004513 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004514 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004515 return BAD_VALUE;
4516 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004517 audio_port_config sinkPortConfig = {};
4518 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4519 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004520
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004521 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4522 // volume management purpose (tracking activity)
4523 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4524 // in config XML to reach the sink so that is can be declared as available.
4525 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4526 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004527 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004528 // take care of dynamic routing for SwOutput selection,
4529 audio_attributes_t attributes = sourceDesc->attributes();
4530 audio_stream_type_t stream = sourceDesc->stream();
4531 audio_attributes_t resultAttr;
4532 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4533 config.sample_rate = sourceDesc->config().sample_rate;
4534 config.channel_mask = sourceDesc->config().channel_mask;
4535 config.format = sourceDesc->config().format;
4536 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4537 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4538 bool isRequestedDeviceForExclusiveUse = false;
4539 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004540 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004541 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4542 &stream, sourceDesc->uid(), &config, &flags,
4543 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004544 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004545 if (output == AUDIO_IO_HANDLE_NONE) {
4546 ALOGV("%s no output for device %s",
4547 __FUNCTION__, sinkDevice->toString().c_str());
4548 return INVALID_OPERATION;
4549 }
4550 outputDesc = mOutputs.valueFor(output);
4551 if (outputDesc->isDuplicated()) {
4552 ALOGE("%s output is duplicated", __func__);
4553 return INVALID_OPERATION;
4554 }
4555 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004556 } else {
4557 // Same for "raw patches" aka created from createAudioPatch API
4558 SortedVector<audio_io_handle_t> outputs =
4559 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4560 // if the sink device is reachable via an opened output stream, request to
4561 // go via this output stream by adding a second source to the patch
4562 // description
4563 output = selectOutput(outputs);
4564 if (output == AUDIO_IO_HANDLE_NONE) {
4565 ALOGE("%s no output available for internal patch sink", __func__);
4566 return INVALID_OPERATION;
4567 }
4568 outputDesc = mOutputs.valueFor(output);
4569 if (outputDesc->isDuplicated()) {
4570 ALOGV("%s output for device %s is duplicated",
4571 __func__, sinkDevice->toString().c_str());
4572 return INVALID_OPERATION;
4573 }
4574 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004575 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004576 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004577 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004578 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004579 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004580 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4581 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004582 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4583 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004584 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004585 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004586 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004587 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004588 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004589 return INVALID_OPERATION;
4590 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004591 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004592 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004593 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004594 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004595 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004596 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4597 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4598 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004599 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004600 }
Eric Laurent83b88082014-06-20 18:31:16 -07004601 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 }
4603 // TODO: check from routing capabilities in config file and other conflicting patches
4604
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004605installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004606 status_t status = installPatch(
4607 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004608 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004609 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004610 return INVALID_OPERATION;
4611 }
4612 } else {
4613 return BAD_VALUE;
4614 }
4615 } else {
4616 return BAD_VALUE;
4617 }
4618 return NO_ERROR;
4619}
4620
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004621status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004622{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004623 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004624 ssize_t index = mAudioPatches.indexOfKey(handle);
4625
4626 if (index < 0) {
4627 return BAD_VALUE;
4628 }
4629 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004630 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4631 __func__, mUidCached, patchDesc->getUid(), uid);
4632 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004633 return INVALID_OPERATION;
4634 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004635 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4636 for (size_t i = 0; i < mAudioSources.size(); i++) {
4637 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4638 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4639 portId = sourceDesc->portId();
4640 break;
4641 }
4642 }
4643 return portId != AUDIO_PORT_HANDLE_NONE ?
4644 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004645}
Eric Laurent6a94d692014-05-20 11:18:06 -07004646
François Gaffieafd4cea2019-11-18 15:50:22 +01004647status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004648 uint32_t delayMs,
4649 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004650{
4651 ALOGV("%s patch %d", __func__, handle);
4652 if (mAudioPatches.indexOfKey(handle) < 0) {
4653 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4654 return BAD_VALUE;
4655 }
4656 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004657 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004658 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004659 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004660 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004662 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004663 return BAD_VALUE;
4664 }
4665
François Gaffie11d30102018-11-02 16:09:09 +01004666 setOutputDevices(outputDesc,
4667 getNewOutputDevices(outputDesc, true /*fromCache*/),
4668 true,
4669 0,
4670 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4672 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004673 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004675 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004676 return BAD_VALUE;
4677 }
4678 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004679 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 true,
4681 NULL);
4682 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004683 status_t status =
4684 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4685 ALOGV("%s patch panel returned %d patchHandle %d",
4686 __func__, status, patchDesc->getAfHandle());
4687 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004689 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004690 // SW or HW Bridge
4691 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4692 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004693 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004694 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4695 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4696 outputDesc = sourceDesc->swOutput().promote();
4697 }
4698 if (outputDesc == nullptr) {
4699 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4700 // releaseOutput has already called closeOutput in case of direct output
4701 return NO_ERROR;
4702 }
4703 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4704 resetOutputDevice(outputDesc);
4705 } else {
4706 // Reuse patch handle if still valid / do not force rerouting if still routed
4707 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004708 setOutputDevices(outputDesc,
4709 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004710 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004711 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004712 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004713 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004714 } else {
4715 return BAD_VALUE;
4716 }
4717 } else {
4718 return BAD_VALUE;
4719 }
4720 return NO_ERROR;
4721}
4722
4723status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4724 struct audio_patch *patches,
4725 unsigned int *generation)
4726{
François Gaffie53615e22015-03-19 09:24:12 +01004727 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004728 return BAD_VALUE;
4729 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004731 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004732}
4733
Eric Laurente1715a42014-05-20 11:30:42 -07004734status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004735{
Eric Laurente1715a42014-05-20 11:30:42 -07004736 ALOGV("setAudioPortConfig()");
4737
4738 if (config == NULL) {
4739 return BAD_VALUE;
4740 }
4741 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4742 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004743 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4744 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004745 }
4746
Eric Laurenta121f902014-06-03 13:32:54 -07004747 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004748 if (config->type == AUDIO_PORT_TYPE_MIX) {
4749 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004750 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004751 if (outputDesc == NULL) {
4752 return BAD_VALUE;
4753 }
Eric Laurent84c70242014-06-23 08:46:27 -07004754 ALOG_ASSERT(!outputDesc->isDuplicated(),
4755 "setAudioPortConfig() called on duplicated output %d",
4756 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004757 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004758 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004759 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004760 if (inputDesc == NULL) {
4761 return BAD_VALUE;
4762 }
Eric Laurenta121f902014-06-03 13:32:54 -07004763 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004764 } else {
4765 return BAD_VALUE;
4766 }
4767 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4768 sp<DeviceDescriptor> deviceDesc;
4769 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4770 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4771 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4772 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4773 } else {
4774 return BAD_VALUE;
4775 }
4776 if (deviceDesc == NULL) {
4777 return BAD_VALUE;
4778 }
Eric Laurenta121f902014-06-03 13:32:54 -07004779 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004780 } else {
4781 return BAD_VALUE;
4782 }
4783
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004784 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004785 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4786 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004787 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004788 audioPortConfig->toAudioPortConfig(&newConfig, config);
4789 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004790 }
Eric Laurenta121f902014-06-03 13:32:54 -07004791 if (status != NO_ERROR) {
4792 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004793 }
Eric Laurente1715a42014-05-20 11:30:42 -07004794
4795 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004796}
4797
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004798void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4799{
Eric Laurentd60560a2015-04-10 11:31:20 -07004800 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004801 clearAudioPatches(uid);
4802 clearSessionRoutes(uid);
4803}
4804
Eric Laurent6a94d692014-05-20 11:18:06 -07004805void AudioPolicyManager::clearAudioPatches(uid_t uid)
4806{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004807 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004809 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004810 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004811 }
4812 }
4813}
4814
François Gaffiec005e562018-11-06 15:04:49 +01004815void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004816{
François Gaffiec005e562018-11-06 15:04:49 +01004817 // Take the first attributes following the product strategy as it is used to retrieve the routed
4818 // device. All attributes wihin a strategy follows the same "routing strategy"
4819 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4820 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004821 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004822 for (size_t j = 0; j < mOutputs.size(); j++) {
4823 if (mOutputs.keyAt(j) == ouptutToSkip) {
4824 continue;
4825 }
4826 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004827 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004828 continue;
4829 }
4830 // If the default device for this strategy is on another output mix,
4831 // invalidate all tracks in this strategy to force re connection.
4832 // Otherwise select new device on the output mix.
4833 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004834 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4835 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004836 }
4837 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004838 setOutputDevices(
4839 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004840 }
4841 }
4842}
4843
4844void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4845{
4846 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004847 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004848 for (size_t i = 0; i < mOutputs.size(); i++) {
4849 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004850 for (const auto& client : outputDesc->getClientIterable()) {
4851 if (client->hasPreferredDevice() && client->uid() == uid) {
4852 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004853 auto clientStrategy = client->strategy();
4854 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4855 end(affectedStrategies)) {
4856 continue;
4857 }
4858 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004859 }
4860 }
4861 }
4862 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004863 for (const auto& strategy : affectedStrategies) {
4864 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004865 }
4866
4867 // remove input routes associated with this uid
4868 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004869 for (size_t i = 0; i < mInputs.size(); i++) {
4870 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004871 for (const auto& client : inputDesc->getClientIterable()) {
4872 if (client->hasPreferredDevice() && client->uid() == uid) {
4873 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4874 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004875 }
4876 }
4877 }
4878 // reroute inputs if necessary
4879 SortedVector<audio_io_handle_t> inputsToClose;
4880 for (size_t i = 0; i < mInputs.size(); i++) {
4881 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004882 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004883 inputsToClose.add(inputDesc->mIoHandle);
4884 }
4885 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004886 for (const auto& input : inputsToClose) {
4887 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004888 }
4889}
4890
Eric Laurentd60560a2015-04-10 11:31:20 -07004891void AudioPolicyManager::clearAudioSources(uid_t uid)
4892{
4893 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004894 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4895 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004896 stopAudioSource(mAudioSources.keyAt(i));
4897 }
4898 }
4899}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004900
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004901status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4902 audio_io_handle_t *ioHandle,
4903 audio_devices_t *device)
4904{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004905 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4906 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004907 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004908 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004909
François Gaffiedf372692015-03-19 10:43:27 +01004910 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004911}
4912
Eric Laurentd60560a2015-04-10 11:31:20 -07004913status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004914 const audio_attributes_t *attributes,
4915 audio_port_handle_t *portId,
4916 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004917{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004918 ALOGV("%s", __FUNCTION__);
4919 *portId = AUDIO_PORT_HANDLE_NONE;
4920
4921 if (source == NULL || attributes == NULL || portId == NULL) {
4922 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4923 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004924 return BAD_VALUE;
4925 }
4926
Eric Laurentd60560a2015-04-10 11:31:20 -07004927 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4928 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004929 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4930 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004931 return INVALID_OPERATION;
4932 }
4933
François Gaffie11d30102018-11-02 16:09:09 +01004934 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004935 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004936 String8(source->ext.device.address),
4937 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004938 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004939 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004940 return BAD_VALUE;
4941 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004942
jiabin4ef93452019-09-10 14:29:54 -07004943 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004944
François Gaffieaaac0fd2018-11-22 17:56:39 +01004945 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004946 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004947 mEngine->getStreamTypeForAttributes(*attributes),
4948 mEngine->getProductStrategyForAttributes(*attributes),
4949 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004950
4951 status_t status = connectAudioSource(sourceDesc);
4952 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004953 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004954 }
4955 return status;
4956}
4957
Francois Gaffie601801d2021-06-22 13:27:39 +02004958sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4959 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4960{
4961 ALOGV("%s", __FUNCTION__);
4962 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4963
4964 status_t status = startAudioSource(source, attributes, &portId, uid);
4965 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4966 return mAudioSources.valueFor(portId);
4967}
4968
4969
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004970status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004971{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004972 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004973
4974 // make sure we only have one patch per source.
4975 disconnectAudioSource(sourceDesc);
4976
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004977 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004978 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4979 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4980 sourceDesc->srcDevice()->type(),
4981 String8(sourceDesc->srcDevice()->address().c_str()),
4982 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004983 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004984 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004985 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004986 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004987 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4988 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4989 return INVALID_OPERATION;
4990 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004991 PatchBuilder patchBuilder;
4992 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4993 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004994
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004995 return connectAudioSourceToSink(
4996 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004997}
4998
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004999status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005000{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005001 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5002 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005003 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005004 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005005 return BAD_VALUE;
5006 }
5007 status_t status = disconnectAudioSource(sourceDesc);
5008
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005009 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005010 return status;
5011}
5012
Andy Hung2ddee192015-12-18 17:34:44 -08005013status_t AudioPolicyManager::setMasterMono(bool mono)
5014{
5015 if (mMasterMono == mono) {
5016 return NO_ERROR;
5017 }
5018 mMasterMono = mono;
5019 // if enabling mono we close all offloaded devices, which will invalidate the
5020 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5021 // for recreating the new AudioTrack as non-offloaded PCM.
5022 //
5023 // If disabling mono, we leave all tracks as is: we don't know which clients
5024 // and tracks are able to be recreated as offloaded. The next "song" should
5025 // play back offloaded.
5026 if (mMasterMono) {
5027 Vector<audio_io_handle_t> offloaded;
5028 for (size_t i = 0; i < mOutputs.size(); ++i) {
5029 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5030 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5031 offloaded.push(desc->mIoHandle);
5032 }
5033 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005034 for (const auto& handle : offloaded) {
5035 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005036 }
5037 }
5038 // update master mono for all remaining outputs
5039 for (size_t i = 0; i < mOutputs.size(); ++i) {
5040 updateMono(mOutputs.keyAt(i));
5041 }
5042 return NO_ERROR;
5043}
5044
5045status_t AudioPolicyManager::getMasterMono(bool *mono)
5046{
5047 *mono = mMasterMono;
5048 return NO_ERROR;
5049}
5050
Eric Laurentac9cef52017-06-09 15:46:26 -07005051float AudioPolicyManager::getStreamVolumeDB(
5052 audio_stream_type_t stream, int index, audio_devices_t device)
5053{
jiabin9a3361e2019-10-01 09:38:30 -07005054 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005055}
5056
jiabin81772902018-04-02 17:52:27 -07005057status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5058 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005059 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005060{
Kriti Dang6537def2021-03-02 13:46:59 +01005061 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5062 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005063 return BAD_VALUE;
5064 }
Kriti Dang6537def2021-03-02 13:46:59 +01005065 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5066 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005067
5068 size_t formatsWritten = 0;
5069 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005070
Kriti Dang6537def2021-03-02 13:46:59 +01005071 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005072 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5073 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005074 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005075 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005076 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005077 bool formatEnabled = true;
5078 switch (forceUse) {
5079 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005080 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005081 break;
5082 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5083 formatEnabled = false;
5084 break;
5085 default: // AUTO or ALWAYS => true
5086 break;
jiabin81772902018-04-02 17:52:27 -07005087 }
5088 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5089 }
jiabin81772902018-04-02 17:52:27 -07005090 }
5091 return NO_ERROR;
5092}
5093
Kriti Dang6537def2021-03-02 13:46:59 +01005094status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5095 audio_format_t *surroundFormats) {
5096 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5097 return BAD_VALUE;
5098 }
5099 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5100 __func__, *numSurroundFormats, surroundFormats);
5101
5102 size_t formatsWritten = 0;
5103 size_t formatsMax = *numSurroundFormats;
5104 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5105
5106 // Return formats from all device profiles that have already been resolved by
5107 // checkOutputsForDevice().
5108 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5109 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5110 audio_devices_t deviceType = device->type();
5111 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5112 // returns formats reported by HDMI devices.
5113 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5114 continue;
5115 }
5116 // Formats reported by sink devices
5117 std::unordered_set<audio_format_t> formatset;
5118 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5119 formatset.insert(it->second.begin(), it->second.end());
5120 }
5121
5122 // Formats hard-coded in the in policy configuration file (if any).
5123 FormatVector encodedFormats = device->encodedFormats();
5124 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5125 // Filter the formats which are supported by the vendor hardware.
5126 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5127 if (mConfig.getSurroundFormats().count(*it) != 0) {
5128 formats.insert(*it);
5129 } else {
5130 for (const auto& pair : mConfig.getSurroundFormats()) {
5131 if (pair.second.count(*it) != 0) {
5132 formats.insert(pair.first);
5133 break;
5134 }
5135 }
5136 }
5137 }
5138 }
5139 *numSurroundFormats = formats.size();
5140 for (const auto& format: formats) {
5141 if (formatsWritten < formatsMax) {
5142 surroundFormats[formatsWritten++] = format;
5143 }
5144 }
5145 return NO_ERROR;
5146}
5147
jiabin81772902018-04-02 17:52:27 -07005148status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5149{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005150 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005151 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5152 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005153 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005154 return BAD_VALUE;
5155 }
5156
Mikhail Naganov100f0122018-11-29 11:22:16 -08005157 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5158 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005159 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005160 return INVALID_OPERATION;
5161 }
5162
Mikhail Naganov100f0122018-11-29 11:22:16 -08005163 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005164 return NO_ERROR;
5165 }
5166
Mikhail Naganov100f0122018-11-29 11:22:16 -08005167 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005168 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005169 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005170 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005171 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005172 }
5173 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005174 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005175 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005176 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005177 }
5178 }
5179
5180 sp<SwAudioOutputDescriptor> outputDesc;
5181 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005182 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5183 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005184 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5185 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005186 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005187 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005188 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5189 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5190 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005191 name.c_str(),
5192 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005193 if (status != NO_ERROR) {
5194 continue;
5195 }
5196 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5197 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5198 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005199 name.c_str(),
5200 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005201 profileUpdated |= (status == NO_ERROR);
5202 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005203 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005204 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005205 AUDIO_DEVICE_IN_HDMI);
5206 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5207 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005208 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005209 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005210 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5211 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5212 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005213 name.c_str(),
5214 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005215 if (status != NO_ERROR) {
5216 continue;
5217 }
5218 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5219 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5220 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005221 name.c_str(),
5222 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005223 profileUpdated |= (status == NO_ERROR);
5224 }
5225
jiabin81772902018-04-02 17:52:27 -07005226 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005227 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005228 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005229 }
5230
5231 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5232}
5233
Eric Laurent5ada82e2019-08-29 17:53:54 -07005234void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005235{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005236 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005237 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005238 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005239 }
5240}
5241
jiabin6012f912018-11-02 17:06:30 -07005242bool AudioPolicyManager::isHapticPlaybackSupported()
5243{
5244 for (const auto& hwModule : mHwModules) {
5245 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5246 for (const auto &outProfile : outputProfiles) {
5247 struct audio_port audioPort;
5248 outProfile->toAudioPort(&audioPort);
5249 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5250 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5251 return true;
5252 }
5253 }
5254 }
5255 }
5256 return false;
5257}
5258
Carter Hsu325a8eb2022-01-19 19:56:51 +08005259bool AudioPolicyManager::isUltrasoundSupported()
5260{
5261 bool hasUltrasoundOutput = false;
5262 bool hasUltrasoundInput = false;
5263 for (const auto& hwModule : mHwModules) {
5264 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5265 if (!hasUltrasoundOutput) {
5266 for (const auto &outProfile : outputProfiles) {
5267 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5268 hasUltrasoundOutput = true;
5269 break;
5270 }
5271 }
5272 }
5273
5274 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5275 if (!hasUltrasoundInput) {
5276 for (const auto &inputProfile : inputProfiles) {
5277 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5278 hasUltrasoundInput = true;
5279 break;
5280 }
5281 }
5282 }
5283
5284 if (hasUltrasoundOutput && hasUltrasoundInput)
5285 return true;
5286 }
5287 return false;
5288}
5289
Eric Laurent8340e672019-11-06 11:01:08 -08005290bool AudioPolicyManager::isCallScreenModeSupported()
5291{
5292 return getConfig().isCallScreenModeSupported();
5293}
5294
5295
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005296status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005297{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005298 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005299 if (!sourceDesc->isConnected()) {
5300 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5301 return NO_ERROR;
5302 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005303 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5304 if (swOutput != 0) {
5305 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005306 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005307 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005308 }
jiabinbce0c1d2020-10-05 11:20:18 -07005309 if (releaseOutput(sourceDesc->portId())) {
5310 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5311 // no need to release audio patch here but just return NO_ERROR.
5312 return NO_ERROR;
5313 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005314 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005315 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005316 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005317 // close Hwoutput and remove from mHwOutputs
5318 } else {
5319 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5320 }
5321 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005322 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005323 sourceDesc->disconnect();
5324 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005325}
5326
François Gaffiec005e562018-11-06 15:04:49 +01005327sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5328 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005329{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005330 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005331 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005332 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005333 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005334 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5335 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005336 source = sourceDesc;
5337 break;
5338 }
5339 }
5340 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005341}
5342
Eric Laurentb4f42a92022-01-17 17:37:31 +01005343bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005344 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005345 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005346{
5347 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5348 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005349 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005350 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005351 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5352 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5353 return false;
5354 }
5355 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5356 return false;
5357 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005358 }
5359
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005360 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005361 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005362 if (profile == nullptr) {
5363 return false;
5364 }
5365
5366 // The caller can have the audio config criteria ignored by either passing a null ptr or
5367 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005368 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005369 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005370
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005371 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005372 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005373 return false;
5374 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005375 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005376 return true;
5377}
5378
5379void AudioPolicyManager::checkVirtualizerClientRoutes() {
5380 std::set<audio_stream_type_t> streamsToInvalidate;
5381 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005382 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5383 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005384 audio_attributes_t attr = client->attributes();
5385 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5386 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5387 audio_config_base_t clientConfig = client->config();
5388 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005389 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005390 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005391 streamsToInvalidate.insert(client->stream());
5392 }
5393 }
5394 }
5395
5396 for (audio_stream_type_t stream : streamsToInvalidate) {
5397 mpClientInterface->invalidateStream(stream);
5398 }
5399}
5400
Eric Laurente191d1b2022-04-15 11:59:25 +02005401
5402bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5403 const sp<SwAudioOutputDescriptor>& outputDesc) {
5404 if (outputDesc->isDuplicated()) {
5405 return false;
5406 }
5407 DeviceVector devices = outputDesc->supportedDevices();
5408 for (size_t i = 0; i < mOutputs.size(); i++) {
5409 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5410 if (desc == outputDesc || desc->isDuplicated()) {
5411 continue;
5412 }
5413 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5414 if (!sharedDevices.isEmpty()
5415 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5416 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5417 return false;
5418 }
5419 }
5420 return true;
5421}
5422
5423
Eric Laurentfa0f6742021-08-17 18:39:44 +02005424status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005425 const audio_attributes_t *attr,
5426 audio_io_handle_t *output) {
5427 *output = AUDIO_IO_HANDLE_NONE;
5428
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005429 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5430 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5431 audio_config_t *configPtr = nullptr;
5432 audio_config_t config;
5433 if (mixerConfig != nullptr) {
5434 config = audio_config_initializer(mixerConfig);
5435 configPtr = &config;
5436 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005437 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005438 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005439 return BAD_VALUE;
5440 }
5441
5442 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005443 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005444 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005445 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005446 return BAD_VALUE;
5447 }
5448
Eric Laurente191d1b2022-04-15 11:59:25 +02005449 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005450 for (size_t i = 0; i < mOutputs.size(); i++) {
5451 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005452 if (!desc->isDuplicated()
5453 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5454 spatializerOutputs.push_back(desc);
5455 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005456 }
5457 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005458 mSpatializerOutput.clear();
5459 bool outputsChanged = false;
5460 for (const auto& desc : spatializerOutputs) {
5461 if (desc->mProfile == profile
5462 && (configPtr == nullptr
5463 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5464 mSpatializerOutput = desc;
5465 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5466 } else {
5467 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5468 " and devices %s", __func__, desc->mIoHandle,
5469 configPtr != nullptr ? configPtr->channel_mask : 0,
5470 devices.toString().c_str());
5471 closeOutput(desc->mIoHandle);
5472 outputsChanged = true;
5473 }
Eric Laurent39095982021-08-24 18:29:27 +02005474 }
5475
Eric Laurente191d1b2022-04-15 11:59:25 +02005476 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005477 sp<SwAudioOutputDescriptor> desc =
5478 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005479 if (desc != nullptr) {
5480 mSpatializerOutput = desc;
5481 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005482 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005483 }
5484
5485 checkVirtualizerClientRoutes();
5486
Eric Laurente191d1b2022-04-15 11:59:25 +02005487 if (outputsChanged) {
5488 mPreviousOutputs = mOutputs;
5489 mpClientInterface->onAudioPortListUpdate();
5490 }
5491
5492 if (mSpatializerOutput == nullptr) {
5493 ALOGV("%s could not open spatializer output with requested config", __func__);
5494 return BAD_VALUE;
5495 }
Eric Laurent39095982021-08-24 18:29:27 +02005496 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005497 ALOGV("%s returning new spatializer output %d", __func__, *output);
5498 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005499}
5500
Eric Laurentfa0f6742021-08-17 18:39:44 +02005501status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5502 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005503 return INVALID_OPERATION;
5504 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005505 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005506 return BAD_VALUE;
5507 }
Eric Laurent39095982021-08-24 18:29:27 +02005508
Eric Laurente191d1b2022-04-15 11:59:25 +02005509 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5510 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5511 closeOutput(mSpatializerOutput->mIoHandle);
5512 //from now on mSpatializerOutput is null
5513 checkVirtualizerClientRoutes();
5514 }
Eric Laurent39095982021-08-24 18:29:27 +02005515
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005516 return NO_ERROR;
5517}
5518
Eric Laurente552edb2014-03-10 17:42:56 -07005519// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005520// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005521// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005522uint32_t AudioPolicyManager::nextAudioPortGeneration()
5523{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005524 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005525}
5526
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005527static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005528 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5529 !audioPolicyXmlConfigFile.empty()) {
5530 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5531 if (ret == NO_ERROR) {
5532 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005533 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005534 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005535 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005536 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005537}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005538
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005539AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5540 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005541 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005542 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005543 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005544 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005545 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005546 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005547 mAudioPortGeneration(1),
5548 mBeaconMuteRefCount(0),
5549 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005550 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005551 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005552 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005553 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005554{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005555}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005556
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005557AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5558 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5559{
5560 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005561}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005562
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005563void AudioPolicyManager::loadConfig() {
5564 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005565 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005566 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005567 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005568}
5569
5570status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005571 {
5572 auto engLib = EngineLibrary::load(
5573 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5574 if (!engLib) {
5575 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5576 return NO_INIT;
5577 }
5578 mEngine = engLib->createEngine();
5579 if (mEngine == nullptr) {
5580 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5581 return NO_INIT;
5582 }
François Gaffie2110e042015-03-24 08:41:51 +01005583 }
5584 mEngine->setObserver(this);
5585 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005586 if (status != NO_ERROR) {
5587 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5588 return status;
5589 }
François Gaffie2110e042015-03-24 08:41:51 +01005590
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005591 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005592 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5593 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5594
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005595 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005596 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005597 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005598
Eric Laurent3a4311c2014-03-17 12:00:47 -07005599 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005600 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5601 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5602 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005603 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005604 }
jiabin9ff780e2018-03-19 18:19:52 -07005605 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005606 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005607 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005608 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005609 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005610 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005611 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005612 }
5613 }
5614 }
Eric Laurente552edb2014-03-10 17:42:56 -07005615
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005616 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005617
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005618 // Silence ALOGV statements
5619 property_set("log.tag." LOG_TAG, "D");
5620
Eric Laurente552edb2014-03-10 17:42:56 -07005621 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005622 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005623}
5624
Eric Laurente0720872014-03-11 09:30:41 -07005625AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005626{
Eric Laurente552edb2014-03-10 17:42:56 -07005627 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005628 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005629 }
5630 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005631 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005632 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005633 mAvailableOutputDevices.clear();
5634 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005635 mOutputs.clear();
5636 mInputs.clear();
5637 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005638 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005639 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005640}
5641
Eric Laurente0720872014-03-11 09:30:41 -07005642status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005643{
Eric Laurent87ffa392015-05-22 10:32:38 -07005644 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005645}
5646
Eric Laurente552edb2014-03-10 17:42:56 -07005647// ---
5648
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005649void AudioPolicyManager::onNewAudioModulesAvailable()
5650{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005651 DeviceVector newDevices;
5652 onNewAudioModulesAvailableInt(&newDevices);
5653 if (!newDevices.empty()) {
5654 nextAudioPortGeneration();
5655 mpClientInterface->onAudioPortListUpdate();
5656 }
5657}
5658
5659void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5660{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005661 for (const auto& hwModule : mHwModulesAll) {
5662 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5663 continue;
5664 }
5665 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5666 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5667 ALOGW("could not open HW module %s", hwModule->getName());
5668 continue;
5669 }
5670 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005671 // open all output streams needed to access attached devices.
5672 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005673 // This also validates mAvailableOutputDevices list
5674 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5675 if (!outProfile->canOpenNewIo()) {
5676 ALOGE("Invalid Output profile max open count %u for profile %s",
5677 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5678 continue;
5679 }
5680 if (!outProfile->hasSupportedDevices()) {
5681 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5682 continue;
5683 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005684 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5685 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005686 mTtsOutputAvailable = true;
5687 }
5688
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005689 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5690 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5691 sp<DeviceDescriptor> supportedDevice = 0;
5692 if (supportedDevices.contains(mDefaultOutputDevice)) {
5693 supportedDevice = mDefaultOutputDevice;
5694 } else {
5695 // choose first device present in profile's SupportedDevices also part of
5696 // mAvailableOutputDevices.
5697 if (availProfileDevices.isEmpty()) {
5698 continue;
5699 }
5700 supportedDevice = availProfileDevices.itemAt(0);
5701 }
5702 if (!mOutputDevicesAll.contains(supportedDevice)) {
5703 continue;
5704 }
5705 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5706 mpClientInterface);
5707 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005708 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5709 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005710 AUDIO_STREAM_DEFAULT,
5711 AUDIO_OUTPUT_FLAG_NONE, &output);
5712 if (status != NO_ERROR) {
5713 ALOGW("Cannot open output stream for devices %s on hw module %s",
5714 supportedDevice->toString().c_str(), hwModule->getName());
5715 continue;
5716 }
5717 for (const auto &device : availProfileDevices) {
5718 // give a valid ID to an attached device once confirmed it is reachable
5719 if (!device->isAttached()) {
5720 device->attach(hwModule);
5721 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005722 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005723 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005724 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5725 }
5726 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005727 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005728 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5729 mPrimaryOutput = outputDesc;
5730 }
Eric Laurent39095982021-08-24 18:29:27 +02005731 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005732 outputDesc->close();
5733 } else {
5734 addOutput(output, outputDesc);
5735 setOutputDevices(outputDesc,
5736 DeviceVector(supportedDevice),
5737 true,
5738 0,
5739 NULL);
5740 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005741 }
5742 // open input streams needed to access attached devices to validate
5743 // mAvailableInputDevices list
5744 for (const auto& inProfile : hwModule->getInputProfiles()) {
5745 if (!inProfile->canOpenNewIo()) {
5746 ALOGE("Invalid Input profile max open count %u for profile %s",
5747 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5748 continue;
5749 }
5750 if (!inProfile->hasSupportedDevices()) {
5751 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5752 continue;
5753 }
5754 // chose first device present in profile's SupportedDevices also part of
5755 // available input devices
5756 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5757 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5758 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005759 ALOGV("%s: Input device list is empty! for profile %s",
5760 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005761 continue;
5762 }
5763 sp<AudioInputDescriptor> inputDesc =
5764 new AudioInputDescriptor(inProfile, mpClientInterface);
5765
5766 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5767 status_t status = inputDesc->open(nullptr,
5768 availProfileDevices.itemAt(0),
5769 AUDIO_SOURCE_MIC,
5770 AUDIO_INPUT_FLAG_NONE,
5771 &input);
5772 if (status != NO_ERROR) {
5773 ALOGW("Cannot open input stream for device %s on hw module %s",
5774 availProfileDevices.toString().c_str(),
5775 hwModule->getName());
5776 continue;
5777 }
5778 for (const auto &device : availProfileDevices) {
5779 // give a valid ID to an attached device once confirmed it is reachable
5780 if (!device->isAttached()) {
5781 device->attach(hwModule);
5782 device->importAudioPortAndPickAudioProfile(inProfile, true);
5783 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005784 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005785 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5786 }
5787 }
5788 inputDesc->close();
5789 }
5790 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005791
5792 // Check if spatializer outputs can be closed until used.
5793 // mOutputs vector never contains duplicated outputs at this point.
5794 std::vector<audio_io_handle_t> outputsClosed;
5795 for (size_t i = 0; i < mOutputs.size(); i++) {
5796 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5797 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5798 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5799 outputsClosed.push_back(desc->mIoHandle);
5800 desc->close();
5801 }
5802 }
5803 for (auto output : outputsClosed) {
5804 removeOutput(output);
5805 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005806}
5807
Eric Laurent98e38192018-02-15 18:31:53 -08005808void AudioPolicyManager::addOutput(audio_io_handle_t output,
5809 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005810{
Eric Laurent1c333e22014-05-20 10:48:17 -07005811 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005812 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005813 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005814 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005815 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005816}
5817
François Gaffie53615e22015-03-19 09:24:12 +01005818void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5819{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005820 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5821 ALOGV("%s: removing primary output", __func__);
5822 mPrimaryOutput = nullptr;
5823 }
François Gaffie53615e22015-03-19 09:24:12 +01005824 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005825 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005826}
5827
Eric Laurent98e38192018-02-15 18:31:53 -08005828void AudioPolicyManager::addInput(audio_io_handle_t input,
5829 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005830{
Eric Laurent1c333e22014-05-20 10:48:17 -07005831 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005832 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005833}
Eric Laurente552edb2014-03-10 17:42:56 -07005834
François Gaffie11d30102018-11-02 16:09:09 +01005835status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005836 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005837 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005838{
François Gaffie11d30102018-11-02 16:09:09 +01005839 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005840 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005841 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005842
François Gaffie11d30102018-11-02 16:09:09 +01005843 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005844 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005845 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005846 }
Eric Laurente552edb2014-03-10 17:42:56 -07005847
Eric Laurent3b73df72014-03-11 09:06:29 -07005848 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005849 // first call getAudioPort to get the supported attributes from the HAL
5850 struct audio_port_v7 port = {};
5851 device->toAudioPort(&port);
5852 status_t status = mpClientInterface->getAudioPort(&port);
5853 if (status == NO_ERROR) {
5854 device->importAudioPort(port);
5855 }
5856
5857 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005858 for (size_t i = 0; i < mOutputs.size(); i++) {
5859 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005860 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005861 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005862 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5863 mOutputs.keyAt(i), device->toString().c_str());
5864 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005865 }
5866 }
5867 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005868 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005869 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005870 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5871 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005872 if (profile->supportsDevice(device)) {
5873 profiles.add(profile);
5874 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5875 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005876 }
5877 }
5878 }
5879
Eric Laurent7b279bb2015-12-14 10:18:23 -08005880 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005881
Eric Laurente552edb2014-03-10 17:42:56 -07005882 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005883 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005884 return BAD_VALUE;
5885 }
5886
5887 // open outputs for matching profiles if needed. Direct outputs are also opened to
5888 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5889 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005890 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005891
5892 // nothing to do if one output is already opened for this profile
5893 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005894 for (j = 0; j < outputs.size(); j++) {
5895 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005896 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005897 // matching profile: save the sample rates, format and channel masks supported
5898 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005899 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005900 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005901 }
Eric Laurente552edb2014-03-10 17:42:56 -07005902 break;
5903 }
5904 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005905 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005906 continue;
5907 }
5908
Eric Laurent3974e3b2017-12-07 17:58:43 -08005909 if (!profile->canOpenNewIo()) {
5910 ALOGW("Max Output number %u already opened for this profile %s",
5911 profile->maxOpenCount, profile->getTagName().c_str());
5912 continue;
5913 }
5914
Eric Laurent83efe1c2017-07-09 16:51:08 -07005915 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005916 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005917 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5918 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005919 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005920 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005921 profiles.removeAt(profile_index);
5922 profile_index--;
5923 } else {
5924 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005925 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005926 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005927 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5928 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005929 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005930 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005931
François Gaffie11d30102018-11-02 16:09:09 +01005932 if (device_distinguishes_on_address(deviceType)) {
5933 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5934 device->toString().c_str());
5935 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5936 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005937 }
Eric Laurente552edb2014-03-10 17:42:56 -07005938 ALOGV("checkOutputsForDevice(): adding output %d", output);
5939 }
5940 }
5941
5942 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005943 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005944 return BAD_VALUE;
5945 }
Eric Laurentd4692962014-05-05 18:13:44 -07005946 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005947 // check if one opened output is not needed any more after disconnecting one device
5948 for (size_t i = 0; i < mOutputs.size(); i++) {
5949 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005950 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005951 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005952 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005953 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005954 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005955 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005956 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5957 mOutputs.keyAt(i));
5958 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005959 }
Eric Laurente552edb2014-03-10 17:42:56 -07005960 }
5961 }
Eric Laurentd4692962014-05-05 18:13:44 -07005962 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005963 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005964 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5965 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005966 if (!profile->supportsDevice(device)) {
5967 continue;
5968 }
5969 ALOGV("checkOutputsForDevice(): "
5970 "clearing direct output profile %zu on module %s",
5971 j, hwModule->getName());
5972 profile->clearAudioProfiles();
5973 if (!profile->hasDynamicAudioProfile()) {
5974 continue;
5975 }
5976 // When a device is disconnected, if there is an IOProfile that contains dynamic
5977 // profiles and supports the disconnected device, call getAudioPort to repopulate
5978 // the capabilities of the devices that is supported by the IOProfile.
5979 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5980 if (supportedDevice == device ||
5981 !mAvailableOutputDevices.contains(supportedDevice)) {
5982 continue;
5983 }
5984 struct audio_port_v7 port;
5985 supportedDevice->toAudioPort(&port);
5986 status_t status = mpClientInterface->getAudioPort(&port);
5987 if (status == NO_ERROR) {
5988 supportedDevice->importAudioPort(port);
5989 }
Eric Laurente552edb2014-03-10 17:42:56 -07005990 }
5991 }
5992 }
5993 }
5994 return NO_ERROR;
5995}
5996
François Gaffie11d30102018-11-02 16:09:09 +01005997status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005998 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005999{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006000 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006001
François Gaffie11d30102018-11-02 16:09:09 +01006002 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006003 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006004 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006005 }
6006
Eric Laurentd4692962014-05-05 18:13:44 -07006007 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006008 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006009 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006010 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006011 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006012 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006013 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006014 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006015
François Gaffie11d30102018-11-02 16:09:09 +01006016 if (profile->supportsDevice(device)) {
6017 profiles.add(profile);
6018 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6019 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006020 }
6021 }
6022 }
6023
Eric Laurent0dd51852019-04-19 18:18:58 -07006024 if (profiles.isEmpty()) {
6025 ALOGW("%s: No input profile available for device %s",
6026 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006027 return BAD_VALUE;
6028 }
6029
6030 // open inputs for matching profiles if needed. Direct inputs are also opened to
6031 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6032 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6033
Eric Laurent1c333e22014-05-20 10:48:17 -07006034 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006035
Eric Laurentd4692962014-05-05 18:13:44 -07006036 // nothing to do if one input is already opened for this profile
6037 size_t input_index;
6038 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6039 desc = mInputs.valueAt(input_index);
6040 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006041 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006042 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006043 }
Eric Laurentd4692962014-05-05 18:13:44 -07006044 break;
6045 }
6046 }
6047 if (input_index != mInputs.size()) {
6048 continue;
6049 }
6050
Eric Laurent3974e3b2017-12-07 17:58:43 -08006051 if (!profile->canOpenNewIo()) {
6052 ALOGW("Max Input number %u already opened for this profile %s",
6053 profile->maxOpenCount, profile->getTagName().c_str());
6054 continue;
6055 }
6056
Eric Laurentfe231122017-11-17 17:48:06 -08006057 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006058 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006059 status_t status = desc->open(nullptr,
6060 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006061 AUDIO_SOURCE_MIC,
6062 AUDIO_INPUT_FLAG_NONE,
6063 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006064
Eric Laurentcf2c0212014-07-25 16:20:43 -07006065 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006066 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006067 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006068 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006069 mpClientInterface->setParameters(input, String8(param));
6070 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006071 }
François Gaffie11d30102018-11-02 16:09:09 +01006072 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006073 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006074 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006075 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006076 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006077 }
6078
Eric Laurent0dd51852019-04-19 18:18:58 -07006079 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006080 addInput(input, desc);
6081 }
6082 } // endif input != 0
6083
Eric Laurentcf2c0212014-07-25 16:20:43 -07006084 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006085 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006086 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006087 profiles.removeAt(profile_index);
6088 profile_index--;
6089 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006090 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006091 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006092 }
Eric Laurentd4692962014-05-05 18:13:44 -07006093 ALOGV("checkInputsForDevice(): adding input %d", input);
6094 }
6095 } // end scan profiles
6096
6097 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006098 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006099 return BAD_VALUE;
6100 }
6101 } else {
6102 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006103 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006104 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006105 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006106 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006107 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006108 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006109 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006110 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6111 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006112 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006113 }
6114 }
6115 }
6116 } // end disconnect
6117
6118 return NO_ERROR;
6119}
6120
6121
Eric Laurente0720872014-03-11 09:30:41 -07006122void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006123{
6124 ALOGV("closeOutput(%d)", output);
6125
François Gaffie1c878552018-11-22 16:53:21 +01006126 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6127 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006128 ALOGW("closeOutput() unknown output %d", output);
6129 return;
6130 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006131 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006132 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006133
Eric Laurente552edb2014-03-10 17:42:56 -07006134 // look for duplicated outputs connected to the output being removed.
6135 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006136 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6137 if (dupOutput->isDuplicated() &&
6138 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6139 sp<SwAudioOutputDescriptor> remainingOutput =
6140 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006141 // As all active tracks on duplicated output will be deleted,
6142 // and as they were also referenced on the other output, the reference
6143 // count for their stream type must be adjusted accordingly on
6144 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006145 const bool wasActive = remainingOutput->isActive();
6146 // Note: no-op on the closing output where all clients has already been set inactive
6147 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006148 // stop() will be a no op if the output is still active but is needed in case all
6149 // active streams refcounts where cleared above
6150 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006151 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006152 }
Eric Laurente552edb2014-03-10 17:42:56 -07006153 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6154 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6155
6156 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006157 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006158 }
6159 }
6160
Eric Laurent05b90f82014-08-27 15:32:29 -07006161 nextAudioPortGeneration();
6162
François Gaffie1c878552018-11-22 16:53:21 +01006163 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006164 if (index >= 0) {
6165 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006166 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6167 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006168 mAudioPatches.removeItemsAt(index);
6169 mpClientInterface->onAudioPatchListUpdate();
6170 }
6171
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006172 if (closingOutputWasActive) {
6173 closingOutput->stop();
6174 }
François Gaffie1c878552018-11-22 16:53:21 +01006175 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006176
François Gaffie53615e22015-03-19 09:24:12 +01006177 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006178 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006179 if (closingOutput == mSpatializerOutput) {
6180 mSpatializerOutput.clear();
6181 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006182
6183 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6184 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006185 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006186 bool directOutputOpen = false;
6187 for (size_t i = 0; i < mOutputs.size(); i++) {
6188 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6189 directOutputOpen = true;
6190 break;
6191 }
6192 }
6193 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006194 ALOGV("no direct outputs open, reset MSD patches");
6195 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6196 // how output devices for patching are resolved. Avoid by caching and reusing the
6197 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6198 // devices to patch to. This may be complicated by the fact that devices may become
6199 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006200 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006201 }
6202 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006203}
6204
6205void AudioPolicyManager::closeInput(audio_io_handle_t input)
6206{
6207 ALOGV("closeInput(%d)", input);
6208
6209 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6210 if (inputDesc == NULL) {
6211 ALOGW("closeInput() unknown input %d", input);
6212 return;
6213 }
6214
Eric Laurent6a94d692014-05-20 11:18:06 -07006215 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006216
François Gaffie11d30102018-11-02 16:09:09 +01006217 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006218 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006219 if (index >= 0) {
6220 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006221 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6222 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006223 mAudioPatches.removeItemsAt(index);
6224 mpClientInterface->onAudioPatchListUpdate();
6225 }
6226
Eric Laurentfe231122017-11-17 17:48:06 -08006227 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006228 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006229
François Gaffie11d30102018-11-02 16:09:09 +01006230 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6231 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006232 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006233 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006234 }
Eric Laurente552edb2014-03-10 17:42:56 -07006235}
6236
François Gaffie11d30102018-11-02 16:09:09 +01006237SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6238 const DeviceVector &devices,
6239 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006240{
6241 SortedVector<audio_io_handle_t> outputs;
6242
François Gaffie11d30102018-11-02 16:09:09 +01006243 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006244 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006245 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006246 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006247 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006248 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006249 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006250 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006251 outputs.add(openOutputs.keyAt(i));
6252 }
6253 }
6254 return outputs;
6255}
6256
Mikhail Naganov37977152018-07-11 15:54:44 -07006257void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6258{
6259 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6260 // output is suspended before any tracks are moved to it
6261 checkA2dpSuspend();
6262 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006263 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006264 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006265 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006266 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006267 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6268 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6269 // configuration changes will ultimately be rerouted correctly. We can still avoid
6270 // unnecessary rerouting by caching and reusing the arguments to
6271 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6272 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006273 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006274 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006275 // an event that changed routing likely occurred, inform upper layers
6276 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006277}
6278
François Gaffiec005e562018-11-06 15:04:49 +01006279bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6280 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006281{
François Gaffiec005e562018-11-06 15:04:49 +01006282 return mEngine->getProductStrategyForAttributes(lAttr) ==
6283 mEngine->getProductStrategyForAttributes(rAttr);
6284}
6285
Francois Gaffieff1eb522020-05-06 18:37:04 +02006286void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6287{
6288 for (size_t i = 0; i < mAudioSources.size(); i++) {
6289 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6290 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006291 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006292 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006293 connectAudioSource(sourceDesc);
6294 }
6295 }
6296}
6297
6298void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6299{
6300 for (size_t i = 0; i < mAudioSources.size(); i++) {
6301 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6302 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6303 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6304 disconnectAudioSource(sourceDesc);
6305 }
6306 }
6307}
6308
François Gaffiec005e562018-11-06 15:04:49 +01006309void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6310{
6311 auto psId = mEngine->getProductStrategyForAttributes(attr);
6312
6313 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6314 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006315
François Gaffie11d30102018-11-02 16:09:09 +01006316 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6317 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006318
Eric Laurentc209fe42020-06-05 18:11:23 -07006319 uint32_t maxLatency = 0;
6320 bool invalidate = false;
6321 // take into account dynamic audio policies related changes: if a client is now associated
6322 // to a different policy mix than at creation time, invalidate corresponding stream
6323 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6324 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6325 if (desc->isDuplicated()) {
6326 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006327 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006328 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6329 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6330 continue;
6331 }
6332 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006333 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6334 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006335 if (status != OK) {
6336 continue;
6337 }
yucliuf4de36d2020-09-14 14:57:56 -07006338 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006339 invalidate = true;
6340 if (desc->isStrategyActive(psId)) {
6341 maxLatency = desc->latency();
6342 }
6343 break;
6344 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006345 }
6346 }
6347
Eric Laurentc209fe42020-06-05 18:11:23 -07006348 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006349 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6350 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006351 for (audio_io_handle_t srcOut : srcOutputs) {
6352 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006353 if (desc == nullptr) continue;
6354
6355 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006356 maxLatency = desc->latency();
6357 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006358
6359 if (invalidate) continue;
6360
6361 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006362 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006363 // a client on a non direct outputs has necessarily a linear PCM format
6364 // so we can call selectOutput() safely
6365 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6366 client->flags(),
6367 client->config().format,
6368 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006369 client->config().sample_rate,
6370 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006371 if (newOutput != srcOut) {
6372 invalidate = true;
6373 break;
6374 }
6375 } else {
6376 sp<IOProfile> profile = getProfileForOutput(newDevices,
6377 client->config().sample_rate,
6378 client->config().format,
6379 client->config().channel_mask,
6380 client->flags(),
6381 true /* directOnly */);
6382 if (profile != desc->mProfile) {
6383 invalidate = true;
6384 break;
6385 }
6386 }
6387 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006388 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006389
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006390 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006391 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006392 std::to_string(srcOutputs[0]).c_str(),
6393 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006394 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006395 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006396 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006397 if (desc == nullptr) continue;
6398
6399 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006400 setStrategyMute(psId, true, desc);
6401 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006402 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006403 }
François Gaffiec005e562018-11-06 15:04:49 +01006404 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006405 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006406 connectAudioSource(source);
6407 }
Eric Laurente552edb2014-03-10 17:42:56 -07006408 }
6409
François Gaffiec005e562018-11-06 15:04:49 +01006410 // Move effects associated to this stream from previous output to new output
6411 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006412 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006413 }
François Gaffiec005e562018-11-06 15:04:49 +01006414 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006415 if (invalidate) {
6416 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6417 mpClientInterface->invalidateStream(stream);
6418 }
jiabin49256852022-03-09 11:21:35 -08006419 for (audio_io_handle_t srcOut : srcOutputs) {
6420 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6421 if (desc == nullptr) continue;
6422
6423 desc->setTracksInvalidatedStatusByStrategy(psId);
6424 }
Eric Laurente552edb2014-03-10 17:42:56 -07006425 }
6426 }
6427}
6428
Eric Laurente0720872014-03-11 09:30:41 -07006429void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006430{
François Gaffiec005e562018-11-06 15:04:49 +01006431 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6432 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6433 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006434 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006435 }
Eric Laurente552edb2014-03-10 17:42:56 -07006436}
6437
Kevin Rocard153f92d2018-12-18 18:33:28 -08006438void AudioPolicyManager::checkSecondaryOutputs() {
6439 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006440 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006441 for (size_t i = 0; i < mOutputs.size(); i++) {
6442 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6443 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006444 sp<AudioPolicyMix> primaryMix;
6445 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006446 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6447 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006448 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6449 for (auto &secondaryMix : secondaryMixes) {
6450 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6451 if (outputDesc != nullptr &&
6452 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6453 secondaryDescs.push_back(outputDesc);
6454 }
6455 }
6456
jiabin10a03f12021-05-07 23:46:28 +00006457 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006458 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006459 } else if (!std::equal(
6460 client->getSecondaryOutputs().begin(),
6461 client->getSecondaryOutputs().end(),
6462 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006463 if (!audio_is_linear_pcm(client->config().format)) {
6464 // If the format is not PCM, the tracks should be invalidated to get correct
6465 // behavior when the secondary output is changed.
6466 streamsToInvalidate.insert(client->stream());
6467 } else {
6468 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6469 std::vector<audio_io_handle_t> secondaryOutputIds;
6470 for (const auto &secondaryDesc: secondaryDescs) {
6471 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6472 weakSecondaryDescs.push_back(secondaryDesc);
6473 }
6474 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6475 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006476 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006477 }
6478 }
6479 }
jiabin10a03f12021-05-07 23:46:28 +00006480 if (!trackSecondaryOutputs.empty()) {
6481 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6482 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006483 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006484 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006485 mpClientInterface->invalidateStream(stream);
6486 }
6487}
6488
Eric Laurent2517af32020-11-25 15:31:27 +01006489bool AudioPolicyManager::isScoRequestedForComm() const {
6490 AudioDeviceTypeAddrVector devices;
6491 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6492 for (const auto &device : devices) {
6493 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6494 return true;
6495 }
6496 }
6497 return false;
6498}
6499
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006500bool AudioPolicyManager::isHearingAidUsedForComm() const {
6501 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6502 true /*fromCache*/);
6503 for (const auto &device : devices) {
6504 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6505 return true;
6506 }
6507 }
6508 return false;
6509}
6510
6511
Eric Laurente0720872014-03-11 09:30:41 -07006512void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006513{
François Gaffie53615e22015-03-19 09:24:12 +01006514 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006515 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006516 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006517 return;
6518 }
6519
Eric Laurent3a4311c2014-03-17 12:00:47 -07006520 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006521 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6522 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006523 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006524
6525 // if suspended, restore A2DP output if:
6526 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006527 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006528 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006529 //
Eric Laurentf732e072016-08-03 19:30:28 -07006530 // if not suspended, suspend A2DP output if:
6531 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006532 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006533 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006534 //
6535 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006536 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006537 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006538 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006539 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006540
6541 mpClientInterface->restoreOutput(a2dpOutput);
6542 mA2dpSuspended = false;
6543 }
6544 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006545 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006546 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006547 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006548 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006549
6550 mpClientInterface->suspendOutput(a2dpOutput);
6551 mA2dpSuspended = true;
6552 }
6553 }
6554}
6555
François Gaffie11d30102018-11-02 16:09:09 +01006556DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6557 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006558{
François Gaffie11d30102018-11-02 16:09:09 +01006559 DeviceVector devices;
6560
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006561 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006562 if (index >= 0) {
6563 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006564 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006565 ALOGV("%s device %s forced by patch %d", __func__,
6566 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6567 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006568 }
6569 }
6570
Dean Wheatley514b4312020-06-17 21:45:00 +10006571 // Do not retrieve engine device for outputs through MSD
6572 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6573 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6574 return outputDesc->devices();
6575 }
6576
Eric Laurent97ac8712018-07-27 18:59:02 -07006577 // Honor explicit routing requests only if no client using default routing is active on this
6578 // input: a specific app can not force routing for other apps by setting a preferred device.
6579 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006580 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006581 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006582 if (device != nullptr) {
6583 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006584 }
6585
François Gaffiea807ef92018-11-05 10:44:33 +01006586 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6587 // of setForceUse / Default Bus device here
6588 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6589 if (device != nullptr) {
6590 return DeviceVector(device);
6591 }
6592
François Gaffiec005e562018-11-06 15:04:49 +01006593 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6594 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6595 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306596 auto hasStreamActive = [&](auto stream) {
6597 return hasStream(streams, stream) && isStreamActive(stream, 0);
6598 };
Eric Laurent484e9272018-06-07 17:29:23 -07006599
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306600 auto doGetOutputDevicesForVoice = [&]() {
6601 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006602 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306603 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006604 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6605 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306606 };
6607
6608 // With low-latency playing on speaker, music on WFD, when the first low-latency
6609 // output is stopped, getNewOutputDevices checks for a product strategy
6610 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006611 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306612 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6613 // stream is associated to the output descriptor.
6614 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6615 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6616 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6617 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006618 // Retrieval of devices for voice DL is done on primary output profile, cannot
6619 // check the route (would force modifying configuration file for this profile)
6620 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6621 break;
6622 }
Eric Laurente552edb2014-03-10 17:42:56 -07006623 }
François Gaffiec005e562018-11-06 15:04:49 +01006624 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006625 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006626}
6627
François Gaffie11d30102018-11-02 16:09:09 +01006628sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6629 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006630{
François Gaffie11d30102018-11-02 16:09:09 +01006631 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006632
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006633 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006634 if (index >= 0) {
6635 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006636 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006637 ALOGV("getNewInputDevice() device %s forced by patch %d",
6638 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6639 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006640 }
6641 }
6642
Eric Laurent97ac8712018-07-27 18:59:02 -07006643 // Honor explicit routing requests only if no client using default routing is active on this
6644 // input: a specific app can not force routing for other apps by setting a preferred device.
6645 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006646 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6647 if (device != nullptr) {
6648 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006649 }
6650
Eric Laurentdc95a252018-04-12 12:46:56 -07006651 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006652 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006653 audio_attributes_t attributes;
6654 uid_t uid;
6655 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6656 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006657 attributes = topClient->attributes();
6658 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006659 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006660 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6661 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006662 }
6663
Francois Gaffie716e1432019-01-14 16:58:59 +01006664 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6665 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006666 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006667 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006668 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006669 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006670
Eric Laurente552edb2014-03-10 17:42:56 -07006671 return device;
6672}
6673
Eric Laurent794fde22016-03-11 09:50:45 -08006674bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6675 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006676 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006677}
6678
Dorin Drimusf2196d82022-01-03 12:11:18 +01006679// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006680status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006681 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006682 if (devices == nullptr) {
6683 return BAD_VALUE;
6684 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006685
6686 // Devices are determined in the following precedence:
6687 //
6688 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6689 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6690 //
6691 // If no such dynamic policy then
6692 // 2) Devices containing an active client using setPreferredDevice
6693 // with same strategy as the attributes.
6694 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6695 //
6696 // If no corresponding active client with setPreferredDevice then
6697 // 3) Devices associated with the strategy determined by the attributes
6698 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6699 //
6700 // See related getOutputForAttrInt().
6701
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006702 // check dynamic policies but only for primary descriptors (secondary not used for audible
6703 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006704 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006705 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6706 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006707 if (status != OK) {
6708 return status;
6709 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006710
6711 DeviceVector curDevices;
6712 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6713 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6714 // as they are unaffected by device/stream volume
6715 // (per SwAudioOutputDescriptor::isFixedVolume()).
6716 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6717 ) {
6718 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6719 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6720 curDevices.add(deviceDesc);
6721 } else {
6722 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6723 // which selects setPreferredDevice if active. This means forVolume call
6724 // will take an active setPreferredDevice, if such exists.
6725
6726 curDevices = mEngine->getOutputDevicesForAttributes(
6727 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006728 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006729
6730 if (forVolume) {
6731 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6732 // for single volume control in AudioService (such relationship should exist if
6733 // SPEAKER_SAFE is present).
6734 //
6735 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6736 DeviceVector speakerSafeDevices =
6737 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6738 if (!speakerSafeDevices.isEmpty()) {
6739 curDevices.merge(
6740 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6741 curDevices.remove(speakerSafeDevices);
6742 }
6743 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006744 for (const auto& device : curDevices) {
6745 devices->push_back(device->getDeviceTypeAddr());
6746 }
6747 return NO_ERROR;
6748}
6749
Eric Laurente0720872014-03-11 09:30:41 -07006750void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006751 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006752 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006753 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006754 updateDevicesAndOutputs();
6755 break;
6756 default:
6757 break;
6758 }
6759}
6760
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006761uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006762
6763 // skip beacon mute management if a dedicated TTS output is available
6764 if (mTtsOutputAvailable) {
6765 return 0;
6766 }
6767
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006768 switch(event) {
6769 case STARTING_OUTPUT:
6770 mBeaconMuteRefCount++;
6771 break;
6772 case STOPPING_OUTPUT:
6773 if (mBeaconMuteRefCount > 0) {
6774 mBeaconMuteRefCount--;
6775 }
6776 break;
6777 case STARTING_BEACON:
6778 mBeaconPlayingRefCount++;
6779 break;
6780 case STOPPING_BEACON:
6781 if (mBeaconPlayingRefCount > 0) {
6782 mBeaconPlayingRefCount--;
6783 }
6784 break;
6785 }
6786
6787 if (mBeaconMuteRefCount > 0) {
6788 // any playback causes beacon to be muted
6789 return setBeaconMute(true);
6790 } else {
6791 // no other playback: unmute when beacon starts playing, mute when it stops
6792 return setBeaconMute(mBeaconPlayingRefCount == 0);
6793 }
6794}
6795
6796uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6797 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6798 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6799 // keep track of muted state to avoid repeating mute/unmute operations
6800 if (mBeaconMuted != mute) {
6801 // mute/unmute AUDIO_STREAM_TTS on all outputs
6802 ALOGV("\t muting %d", mute);
6803 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006804 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6805 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6806 ALOGV("\t no tts volume source available");
6807 return 0;
6808 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006809 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006810 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006811 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006812 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006813 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006814 maxLatency = latency;
6815 }
6816 }
6817 mBeaconMuted = mute;
6818 return maxLatency;
6819 }
6820 return 0;
6821}
6822
Eric Laurente0720872014-03-11 09:30:41 -07006823void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006824{
François Gaffiec005e562018-11-06 15:04:49 +01006825 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006826 mPreviousOutputs = mOutputs;
6827}
6828
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006829uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006830 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006831 uint32_t delayMs)
6832{
6833 // mute/unmute strategies using an incompatible device combination
6834 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6835 // if unmuting, unmute only after the specified delay
6836 if (outputDesc->isDuplicated()) {
6837 return 0;
6838 }
6839
6840 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006841 DeviceVector devices = outputDesc->devices();
6842 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006843
François Gaffiec005e562018-11-06 15:04:49 +01006844 auto productStrategies = mEngine->getOrderedProductStrategies();
6845 for (const auto &productStrategy : productStrategies) {
6846 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6847 DeviceVector curDevices =
6848 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6849 curDevices = curDevices.filter(outputDesc->supportedDevices());
6850 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006851 bool doMute = false;
6852
François Gaffiec005e562018-11-06 15:04:49 +01006853 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006854 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006855 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6856 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006857 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006858 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006859 }
Eric Laurent99401132014-05-07 19:48:15 -07006860 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006861 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006862 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006863 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006864 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006865 continue;
6866 }
François Gaffiec005e562018-11-06 15:04:49 +01006867 ALOGVV("%s() %s (curDevice %s)", __func__,
6868 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6869 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6870 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006871 if (mute) {
6872 // FIXME: should not need to double latency if volume could be applied
6873 // immediately by the audioflinger mixer. We must account for the delay
6874 // between now and the next time the audioflinger thread for this output
6875 // will process a buffer (which corresponds to one buffer size,
6876 // usually 1/2 or 1/4 of the latency).
6877 if (muteWaitMs < desc->latency() * 2) {
6878 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006879 }
6880 }
6881 }
6882 }
6883 }
6884 }
6885
Eric Laurent99401132014-05-07 19:48:15 -07006886 // temporary mute output if device selection changes to avoid volume bursts due to
6887 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006888 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006889 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006890
Eric Laurentdc462862016-07-19 12:29:53 -07006891 if (muteWaitMs < tempMuteWaitMs) {
6892 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006893 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006894
6895 // If recommended duration is defined, replace temporary mute duration to avoid
6896 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6897 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6898 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6899 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6900 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6901
François Gaffieaaac0fd2018-11-22 17:56:39 +01006902 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6903 // make sure that we do not start the temporary mute period too early in case of
6904 // delayed device change
6905 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6906 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006907 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006908 }
6909 }
6910
Eric Laurente552edb2014-03-10 17:42:56 -07006911 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6912 if (muteWaitMs > delayMs) {
6913 muteWaitMs -= delayMs;
6914 usleep(muteWaitMs * 1000);
6915 return muteWaitMs;
6916 }
6917 return 0;
6918}
6919
François Gaffie11d30102018-11-02 16:09:09 +01006920uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6921 const DeviceVector &devices,
6922 bool force,
6923 int delayMs,
6924 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006925 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006926{
François Gaffie11d30102018-11-02 16:09:09 +01006927 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006928 uint32_t muteWaitMs;
6929
6930 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006931 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6932 nullptr /* patchHandle */, requiresMuteCheck);
6933 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6934 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006935 return muteWaitMs;
6936 }
Eric Laurente552edb2014-03-10 17:42:56 -07006937
6938 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006939 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006940 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006941 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006942
François Gaffie11d30102018-11-02 16:09:09 +01006943 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6944
6945 if (!filteredDevices.isEmpty()) {
6946 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006947 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006948
6949 // if the outputs are not materially active, there is no need to mute.
6950 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006951 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006952 } else {
6953 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6954 muteWaitMs = 0;
6955 }
Eric Laurente552edb2014-03-10 17:42:56 -07006956
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006957 bool outputRouted = outputDesc->isRouted();
6958
Eric Laurent79ea9582020-06-11 18:49:24 -07006959 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6960 // output profile or if new device is not supported AND previous device(s) is(are) still
6961 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006962 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006963 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6964 // restore previous device after evaluating strategy mute state
6965 outputDesc->setDevices(prevDevices);
6966 return muteWaitMs;
6967 }
6968
Eric Laurente552edb2014-03-10 17:42:56 -07006969 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006970 // the requested device is AUDIO_DEVICE_NONE
6971 // OR the requested device is the same as current device
6972 // AND force is not specified
6973 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006974 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006975 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006976 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6977 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006978 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6979 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6980 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6981 }
Eric Laurente552edb2014-03-10 17:42:56 -07006982 return muteWaitMs;
6983 }
6984
François Gaffie11d30102018-11-02 16:09:09 +01006985 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006986
Eric Laurente552edb2014-03-10 17:42:56 -07006987 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006988 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006989 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006990 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006991 PatchBuilder patchBuilder;
6992 patchBuilder.addSource(outputDesc);
6993 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6994 for (const auto &filteredDevice : filteredDevices) {
6995 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006996 }
6997
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006998 // Add half reported latency to delayMs when muteWaitMs is null in order
6999 // to avoid disordered sequence of muting volume and changing devices.
7000 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7001 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007002 }
Eric Laurente552edb2014-03-10 17:42:56 -07007003
7004 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007005 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007006
7007 return muteWaitMs;
7008}
7009
Eric Laurentc75307b2015-03-17 15:29:32 -07007010status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007011 int delayMs,
7012 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007013{
Eric Laurent6a94d692014-05-20 11:18:06 -07007014 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007015 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7016 return INVALID_OPERATION;
7017 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007018 if (patchHandle) {
7019 index = mAudioPatches.indexOfKey(*patchHandle);
7020 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007021 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007022 }
7023 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007024 return INVALID_OPERATION;
7025 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007026 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007027 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007029 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007030 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007031 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007032 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007033 return status;
7034}
7035
7036status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007037 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007038 bool force,
7039 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007040{
7041 status_t status = NO_ERROR;
7042
Eric Laurent1f2f2232014-06-02 12:01:23 -07007043 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007044 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7045 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007046
François Gaffie11d30102018-11-02 16:09:09 +01007047 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007048 PatchBuilder patchBuilder;
7049 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007050 // AUDIO_SOURCE_HOTWORD is for internal use only:
7051 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007052 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7053 auto result = usecase;
7054 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7055 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7056 }
7057 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007058 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007059 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007060 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007061 }
7062 }
7063 return status;
7064}
7065
Eric Laurent6a94d692014-05-20 11:18:06 -07007066status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7067 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007068{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007069 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007070 ssize_t index;
7071 if (patchHandle) {
7072 index = mAudioPatches.indexOfKey(*patchHandle);
7073 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007074 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007075 }
7076 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007077 return INVALID_OPERATION;
7078 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007079 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007080 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007081 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007082 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007083 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007084 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007085 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007086 return status;
7087}
7088
François Gaffie11d30102018-11-02 16:09:09 +01007089sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007090 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007091 audio_format_t& format,
7092 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007093 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007094{
7095 // Choose an input profile based on the requested capture parameters: select the first available
7096 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007097 //
7098 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7099 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007100
Glenn Kasten730b9262018-03-29 15:01:26 -07007101 sp<IOProfile> firstInexact;
7102 uint32_t updatedSamplingRate = 0;
7103 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7104 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007105 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007106 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007107 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007108 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007109 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007110 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007111 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007112 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007113 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007114 &channelMask /*updatedChannelMask*/,
7115 // FIXME ugly cast
7116 (audio_output_flags_t) flags,
7117 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007118 return profile;
7119 }
François Gaffie11d30102018-11-02 16:09:09 +01007120 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007121 samplingRate,
7122 &updatedSamplingRate,
7123 format,
7124 &updatedFormat,
7125 channelMask,
7126 &updatedChannelMask,
7127 // FIXME ugly cast
7128 (audio_output_flags_t) flags,
7129 false /*exactMatchRequiredForInputFlags*/)) {
7130 firstInexact = profile;
7131 }
7132
Eric Laurente552edb2014-03-10 17:42:56 -07007133 }
7134 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007135 if (firstInexact != nullptr) {
7136 samplingRate = updatedSamplingRate;
7137 format = updatedFormat;
7138 channelMask = updatedChannelMask;
7139 return firstInexact;
7140 }
Eric Laurente552edb2014-03-10 17:42:56 -07007141 return NULL;
7142}
7143
François Gaffieaaac0fd2018-11-22 17:56:39 +01007144float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7145 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007146 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007147 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007148{
jiabin9a3361e2019-10-01 09:38:30 -07007149 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007150
7151 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7152 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7153 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7154 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007155 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7156 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7157 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7158 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7159 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007160
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007161 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007162 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7163 mOutputs.isActive(ringVolumeSrc, 0)) {
7164 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007165 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007166 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007167 }
7168
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007169 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007170 if ((volumeSource != callVolumeSrc && (isInCall() ||
7171 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007172 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007173 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7174 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007175 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7176 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7177 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007178 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007179 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007180 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007181 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007182 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007183 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007184 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7185 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7186 // programmatically muted.
7187 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7188 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7189 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007190 bool exemptFromCapping =
7191 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7192 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007193 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7194 volumeSource, volumeDb);
7195 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007196 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7197 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7198 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007199 }
7200 }
Eric Laurente552edb2014-03-10 17:42:56 -07007201 // if a headset is connected, apply the following rules to ring tones and notifications
7202 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007203 // - always attenuate notifications volume by 6dB
7204 // - attenuate ring tones volume by 6dB unless music is not playing and
7205 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007206 // - if music is playing, always limit the volume to current music volume,
7207 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007208 if (!Intersection(deviceTypes,
7209 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7210 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007211 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7212 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007213 ((volumeSource == alarmVolumeSrc ||
7214 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007215 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7216 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7217 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007218 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7219 curves.canBeMuted()) {
7220
Eric Laurente552edb2014-03-10 17:42:56 -07007221 // when the phone is ringing we must consider that music could have been paused just before
7222 // by the music application and behave as if music was active if the last music track was
7223 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007224 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007225 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007226 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007227 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007228 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7229 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007230 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007231 float musicVolDb = computeVolume(musicCurves,
7232 musicVolumeSrc,
7233 musicCurves.getVolumeIndex(musicDevice),
7234 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007235 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7236 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7237 if (volumeDb > minVolDb) {
7238 volumeDb = minVolDb;
7239 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007240 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007241 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7242 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7243 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007244 // on A2DP, also ensure notification volume is not too low compared to media when
7245 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007246 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007247 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007248 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7249 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007250 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7251 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007252 }
7253 }
jiabin9a3361e2019-10-01 09:38:30 -07007254 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007255 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007256 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007257 }
7258 }
7259
François Gaffie43c73442018-11-08 08:21:55 +01007260 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007261}
7262
Eric Laurent3839bc02018-07-10 18:33:34 -07007263int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007264 VolumeSource fromVolumeSource,
7265 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007266{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007267 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007268 return srcIndex;
7269 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007270 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7271 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007272 float minSrc = (float)srcCurves.getVolumeIndexMin();
7273 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7274 float minDst = (float)dstCurves.getVolumeIndexMin();
7275 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007276
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007277 // preserve mute request or correct range
7278 if (srcIndex < minSrc) {
7279 if (srcIndex == 0) {
7280 return 0;
7281 }
7282 srcIndex = minSrc;
7283 } else if (srcIndex > maxSrc) {
7284 srcIndex = maxSrc;
7285 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007286 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7287}
7288
François Gaffieaaac0fd2018-11-22 17:56:39 +01007289status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7290 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007291 int index,
7292 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007293 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007294 int delayMs,
7295 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007296{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007297 // do not change actual attributes volume if the attributes is muted
7298 if (outputDesc->isMuted(volumeSource)) {
7299 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7300 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007301 return NO_ERROR;
7302 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007303 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7304 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7305 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7306 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007307
Eric Laurent2517af32020-11-25 15:31:27 +01007308 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007309 bool isHAUsed = isHearingAidUsedForComm();
7310
Eric Laurente552edb2014-03-10 17:42:56 -07007311 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007312 // if sco and call follow same curves, bypass forceUseForComm
7313 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007314 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007315 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007316 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007317 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007318 // Do not return an error here as AudioService will always set both voice call
7319 // and bluetooth SCO volumes due to stream aliasing.
7320 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007321 }
jiabin9a3361e2019-10-01 09:38:30 -07007322 if (deviceTypes.empty()) {
7323 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007324 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007325
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007326 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7327 ALOGE("invalid volume index range");
7328 return BAD_VALUE;
7329 }
7330
jiabin9a3361e2019-10-01 09:38:30 -07007331 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7332 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007333 // Force VoIP volume to max for bluetooth SCO device except if muted
7334 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007335 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007336 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007337 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007338 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007339 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007340 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007341
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007342 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007343 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007344 // 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 +01007345 if (isVoiceVolSrc) {
7346 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007347 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007348 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007349 }
Eric Laurent18fba842016-03-31 14:41:26 -07007350 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007351 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7352 mLastVoiceVolume = voiceVolume;
7353 }
7354 }
Eric Laurente552edb2014-03-10 17:42:56 -07007355 return NO_ERROR;
7356}
7357
Eric Laurentc75307b2015-03-17 15:29:32 -07007358void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007359 const DeviceTypeSet& deviceTypes,
7360 int delayMs,
7361 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007362{
jiabincd510522020-01-22 09:40:55 -08007363 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007364 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7365 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7366 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007367 curves.getVolumeIndex(deviceTypes),
7368 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007369 }
7370}
7371
François Gaffiec005e562018-11-06 15:04:49 +01007372void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7373 bool on,
7374 const sp<AudioOutputDescriptor>& outputDesc,
7375 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007376 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007377{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007378 std::vector<VolumeSource> sourcesToMute;
7379 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7380 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7381 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007382 VolumeSource source = toVolumeSource(attributes, false);
7383 if ((source != VOLUME_SOURCE_NONE) &&
7384 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7385 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007386 sourcesToMute.push_back(source);
7387 }
Eric Laurente552edb2014-03-10 17:42:56 -07007388 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007389 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007390 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007391 }
7392
Eric Laurente552edb2014-03-10 17:42:56 -07007393}
7394
François Gaffieaaac0fd2018-11-22 17:56:39 +01007395void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7396 bool on,
7397 const sp<AudioOutputDescriptor>& outputDesc,
7398 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007399 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007400{
jiabin9a3361e2019-10-01 09:38:30 -07007401 if (deviceTypes.empty()) {
7402 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007403 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007404 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007405 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007406 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007407 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007408 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007409 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7410 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007411 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007412 }
7413 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007414 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7415 // ignored
7416 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007417 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007418 if (!outputDesc->isMuted(volumeSource)) {
7419 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007420 return;
7421 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007422 if (outputDesc->decMuteCount(volumeSource) == 0) {
7423 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007424 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007425 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007426 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007427 delayMs);
7428 }
7429 }
7430}
7431
François Gaffie53615e22015-03-19 09:24:12 +01007432bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7433{
François Gaffiec005e562018-11-06 15:04:49 +01007434 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007435 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7436 return true;
7437 }
7438
7439 // has known usage?
7440 switch (paa->usage) {
7441 case AUDIO_USAGE_UNKNOWN:
7442 case AUDIO_USAGE_MEDIA:
7443 case AUDIO_USAGE_VOICE_COMMUNICATION:
7444 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7445 case AUDIO_USAGE_ALARM:
7446 case AUDIO_USAGE_NOTIFICATION:
7447 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7448 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7449 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7450 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7451 case AUDIO_USAGE_NOTIFICATION_EVENT:
7452 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7453 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7454 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7455 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007456 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007457 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007458 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007459 case AUDIO_USAGE_EMERGENCY:
7460 case AUDIO_USAGE_SAFETY:
7461 case AUDIO_USAGE_VEHICLE_STATUS:
7462 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007463 break;
7464 default:
7465 return false;
7466 }
7467 return true;
7468}
7469
François Gaffie2110e042015-03-24 08:41:51 +01007470audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7471{
7472 return mEngine->getForceUse(usage);
7473}
7474
Eric Laurent96d1dda2022-03-14 17:14:19 +01007475bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007476 return isStateInCall(mEngine->getPhoneState());
7477}
7478
Eric Laurent96d1dda2022-03-14 17:14:19 +01007479bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007480 return is_state_in_call(state);
7481}
7482
Eric Laurent74b71512019-11-06 17:21:57 -08007483bool AudioPolicyManager::isCallAudioAccessible()
7484{
7485 audio_mode_t mode = mEngine->getPhoneState();
7486 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007487 || (mode == AUDIO_MODE_CALL_SCREEN)
7488 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007489}
7490
Eric Laurentd60560a2015-04-10 11:31:20 -07007491void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7492{
7493 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007494 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007495 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007496 sourceDesc->sinkDevice()->equals(deviceDesc))
7497 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007498 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007499 }
7500 }
7501
7502 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7503 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7504 bool release = false;
7505 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7506 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7507 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7508 source->ext.device.type == deviceDesc->type()) {
7509 release = true;
7510 }
7511 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007512 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007513 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7514 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7515 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007516 sink->ext.device.type == deviceDesc->type() &&
7517 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7518 || strncmp(sink->ext.device.address, address,
7519 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007520 release = true;
7521 }
7522 }
7523 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007524 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7525 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007526 }
7527 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007528
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007529 mInputs.clearSessionRoutesForDevice(deviceDesc);
7530
Francois Gaffie716e1432019-01-14 16:58:59 +01007531 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007532}
7533
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007534void AudioPolicyManager::modifySurroundFormats(
7535 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007536 std::unordered_set<audio_format_t> enforcedSurround(
7537 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007538 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7539 for (const auto& pair : mConfig.getSurroundFormats()) {
7540 allSurround.insert(pair.first);
7541 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7542 }
Phil Burk09bc4612016-02-24 15:58:15 -08007543
7544 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7545 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007546 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007547 // This is the resulting set of formats depending on the surround mode:
7548 // 'all surround' = allSurround
7549 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7550 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7551 // 'manual surround' = mManualSurroundFormats
7552 // AUTO: formats v 'enforced surround'
7553 // ALWAYS: formats v 'all surround' v 'enforced surround'
7554 // NEVER: formats ^ 'non-surround'
7555 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007556
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007557 std::unordered_set<audio_format_t> formatSet;
7558 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7559 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007560 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007561 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007562 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007563 formatSet.insert(*formatIter);
7564 }
7565 }
7566 } else {
7567 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7568 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007569 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007570
jiabin81772902018-04-02 17:52:27 -07007571 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007572 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007573 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7574 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7575 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007576 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007577 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7578 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7579 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007580 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007581 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007582 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007583 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007584 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007585 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007586}
7587
jiabin06e4bab2019-07-29 10:13:34 -07007588void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7589 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007590 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7591 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7592
7593 // If NEVER, then remove support for channelMasks > stereo.
7594 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007595 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7596 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007597 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007598 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007599 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007600 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007601 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007602 }
7603 }
jiabin81772902018-04-02 17:52:27 -07007604 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7605 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7606 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007607 bool supports5dot1 = false;
7608 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007609 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007610 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7611 supports5dot1 = true;
7612 break;
7613 }
7614 }
7615 // If not then add 5.1 support.
7616 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007617 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007618 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007619 }
Phil Burk09bc4612016-02-24 15:58:15 -08007620 }
7621}
7622
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007623void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007624 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007625 AudioProfileVector &profiles)
7626{
7627 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007628 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007629
François Gaffie112b0af2015-11-19 16:13:25 +01007630 // Format MUST be checked first to update the list of AudioProfile
7631 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007632 reply = mpClientInterface->getParameters(
7633 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007634 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007635 AudioParameter repliedParameters(reply);
7636 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007637 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007638 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7639 return;
7640 }
Phil Burk09bc4612016-02-24 15:58:15 -08007641 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007642 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007643 if (device == AUDIO_DEVICE_OUT_HDMI
7644 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007645 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007646 }
jiabin3e277cc2019-09-10 14:27:34 -07007647 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007648 }
François Gaffie112b0af2015-11-19 16:13:25 +01007649
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007650 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007651 ChannelMaskSet channelMasks;
7652 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007653 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007654 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007655
7656 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007657 reply = mpClientInterface->getParameters(
7658 ioHandle,
7659 requestedParameters.toString() + ";" +
7660 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007661 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007662 AudioParameter repliedParameters(reply);
7663 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007664 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007665 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007666 }
7667 }
7668 if (profiles.hasDynamicChannelsFor(format)) {
7669 reply = mpClientInterface->getParameters(ioHandle,
7670 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007671 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007672 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007673 AudioParameter repliedParameters(reply);
7674 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007675 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007676 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007677 if (device == AUDIO_DEVICE_OUT_HDMI
7678 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007679 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007680 }
François Gaffie112b0af2015-11-19 16:13:25 +01007681 }
7682 }
jiabin3e277cc2019-09-10 14:27:34 -07007683 addDynamicAudioProfileAndSort(
7684 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007685 }
7686}
Eric Laurentd60560a2015-04-10 11:31:20 -07007687
Mikhail Naganovdc769682018-05-04 15:34:08 -07007688status_t AudioPolicyManager::installPatch(const char *caller,
7689 audio_patch_handle_t *patchHandle,
7690 AudioIODescriptorInterface *ioDescriptor,
7691 const struct audio_patch *patch,
7692 int delayMs)
7693{
7694 ssize_t index = mAudioPatches.indexOfKey(
7695 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7696 *patchHandle : ioDescriptor->getPatchHandle());
7697 sp<AudioPatch> patchDesc;
7698 status_t status = installPatch(
7699 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7700 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007701 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007702 }
7703 return status;
7704}
7705
7706status_t AudioPolicyManager::installPatch(const char *caller,
7707 ssize_t index,
7708 audio_patch_handle_t *patchHandle,
7709 const struct audio_patch *patch,
7710 int delayMs,
7711 uid_t uid,
7712 sp<AudioPatch> *patchDescPtr)
7713{
7714 sp<AudioPatch> patchDesc;
7715 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7716 if (index >= 0) {
7717 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007718 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007719 }
7720
7721 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7722 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7723 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7724 if (status == NO_ERROR) {
7725 if (index < 0) {
7726 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007727 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007728 } else {
7729 patchDesc->mPatch = *patch;
7730 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007731 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007732 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007733 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007734 }
7735 nextAudioPortGeneration();
7736 mpClientInterface->onAudioPatchListUpdate();
7737 }
7738 if (patchDescPtr) *patchDescPtr = patchDesc;
7739 return status;
7740}
7741
jiabinbce0c1d2020-10-05 11:20:18 -07007742bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7743{
7744 const TrackClientVector activeClients = output->getActiveClients();
7745 if (activeClients.empty()) {
7746 return true;
7747 }
7748 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7749 if (index < 0) {
7750 ALOGE("%s, no audio patch found while there are active clients on output %d",
7751 __func__, output->getId());
7752 return false;
7753 }
7754 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7755 DeviceVector routedDevices;
7756 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7757 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7758 patchDesc->mPatch.sinks[i].id);
7759 if (device == nullptr) {
7760 ALOGE("%s, no audio device found with id(%d)",
7761 __func__, patchDesc->mPatch.sinks[i].id);
7762 return false;
7763 }
7764 routedDevices.add(device);
7765 }
7766 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007767 if (client->isInvalid()) {
7768 // No need to take care about invalidated clients.
7769 continue;
7770 }
jiabinbce0c1d2020-10-05 11:20:18 -07007771 sp<DeviceDescriptor> preferredDevice =
7772 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7773 if (mEngine->getOutputDevicesForAttributes(
7774 client->attributes(), preferredDevice, false) == routedDevices) {
7775 return false;
7776 }
7777 }
7778 return true;
7779}
7780
7781sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007782 const sp<IOProfile>& profile, const DeviceVector& devices,
7783 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007784{
7785 for (const auto& device : devices) {
7786 // TODO: This should be checking if the profile supports the device combo.
7787 if (!profile->supportsDevice(device)) {
7788 return nullptr;
7789 }
7790 }
7791 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7792 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007793 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007794 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7795 if (status != NO_ERROR) {
7796 return nullptr;
7797 }
7798
7799 // Here is where the out_set_parameters() for card & device gets called
7800 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7801 const audio_devices_t deviceType = device->type();
7802 const String8 &address = String8(device->address().c_str());
7803 if (!address.isEmpty()) {
7804 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7805 mpClientInterface->setParameters(output, String8(param));
7806 free(param);
7807 }
7808 updateAudioProfiles(device, output, profile->getAudioProfiles());
7809 if (!profile->hasValidAudioProfile()) {
7810 ALOGW("%s() missing param", __func__);
7811 desc->close();
7812 return nullptr;
7813 } else if (profile->hasDynamicAudioProfile()) {
7814 desc->close();
7815 output = AUDIO_IO_HANDLE_NONE;
7816 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7817 profile->pickAudioProfile(
7818 config.sample_rate, config.channel_mask, config.format);
7819 config.offload_info.sample_rate = config.sample_rate;
7820 config.offload_info.channel_mask = config.channel_mask;
7821 config.offload_info.format = config.format;
7822
Eric Laurentb4f42a92022-01-17 17:37:31 +01007823 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007824 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7825 if (status != NO_ERROR) {
7826 return nullptr;
7827 }
7828 }
7829
7830 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007831
jiabinbce0c1d2020-10-05 11:20:18 -07007832 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7833 sp<AudioPolicyMix> policyMix;
7834 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7835 policyMix->setOutput(desc);
7836 desc->mPolicyMix = policyMix;
7837 } else {
7838 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7839 address.string());
7840 }
7841
Eric Laurentb4f42a92022-01-17 17:37:31 +01007842 } else if (hasPrimaryOutput() && profile->getModule()
7843 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7844 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7845 // no duplicated output for:
7846 // - direct outputs
7847 // - outputs used by dynamic policy mixes
7848 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007849 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7850
7851 //TODO: configure audio effect output stage here
7852
7853 // open a duplicating output thread for the new output and the primary output
7854 sp<SwAudioOutputDescriptor> dupOutputDesc =
7855 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7856 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7857 if (status == NO_ERROR) {
7858 // add duplicated output descriptor
7859 addOutput(duplicatedOutput, dupOutputDesc);
7860 } else {
7861 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7862 mPrimaryOutput->mIoHandle, output);
7863 desc->close();
7864 removeOutput(output);
7865 nextAudioPortGeneration();
7866 return nullptr;
7867 }
7868 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007869 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7870 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7871 mPrimaryOutput = desc;
7872 }
jiabinbce0c1d2020-10-05 11:20:18 -07007873 return desc;
7874}
7875
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007876} // namespace android