blob: d6384f02cb9a8ea2300271f5c993ab867172c34c [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 }
1057 // reject profiles not corresponding to a device currently available
1058 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1059 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1060 continue;
1061 }
1062 if (!devices.empty()) {
1063 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;
1164 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001165 if (status != OK) {
1166 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001168
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001170 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001171
1172 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 if ((usePrimaryOutputFromPolicyMixes
1174 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001175 && !audio_is_linear_pcm(config->format)) {
1176 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001177 return BAD_VALUE;
1178 }
1179 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001180 sp<DeviceDescriptor> deviceDesc =
1181 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1182 primaryMix->mDeviceAddress,
1183 AUDIO_FORMAT_DEFAULT);
1184 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001185 if (deviceDesc != nullptr
1186 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001187 audio_io_handle_t newOutput;
1188 status = openDirectOutput(
1189 *stream, session, config,
1190 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1191 DeviceVector(deviceDesc), &newOutput);
1192 if (status != NO_ERROR) {
1193 policyDesc = nullptr;
1194 } else {
1195 policyDesc = mOutputs.valueFor(newOutput);
1196 primaryMix->setOutput(policyDesc);
1197 }
1198 }
1199 if (policyDesc != nullptr) {
1200 policyDesc->mPolicyMix = primaryMix;
1201 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001202 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001203
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001204 ALOGV("getOutputForAttr() returns output %d", *output);
1205 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1206 *outputType = API_OUT_MIX_PLAYBACK;
1207 } else {
1208 *outputType = API_OUTPUT_LEGACY;
1209 }
1210 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001211 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001212 }
François Gaffiec005e562018-11-06 15:04:49 +01001213 // Virtual sources must always be dynamicaly or explicitly routed
1214 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1215 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1216 return BAD_VALUE;
1217 }
1218 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1219 // in order to let the choice of the order to future vendor engine
1220 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001221
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001222 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001223 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001224 }
1225
Nadav Barb2f18162018-07-18 13:01:53 +03001226 // Set incall music only if device was explicitly set, and fallback to the device which is
1227 // chosen by the engine if not.
1228 // FIXME: provide a more generic approach which is not device specific and move this back
1229 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001230 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001231 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001232 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001233 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001234 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001235 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001236 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001237 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001238 }
1239 }
1240
François Gaffiec005e562018-11-06 15:04:49 +01001241 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1242 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1243 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001244
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001245 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001246 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001247 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001248 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001249 ALOGV("%s() Using MSD devices %s instead of devices %s",
1250 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001251 } else {
1252 *output = AUDIO_IO_HANDLE_NONE;
1253 }
1254 }
1255 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001256 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001257 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001258 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001259 if (*output == AUDIO_IO_HANDLE_NONE) {
1260 return INVALID_OPERATION;
1261 }
Paul McLeanaa981192015-03-21 09:55:15 -07001262
François Gaffiec005e562018-11-06 15:04:49 +01001263 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001264 for (auto &outputDevice : outputDevices) {
1265 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1266 *selectedDeviceId = outputDevice->getId();
1267 break;
1268 }
1269 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001270
Eric Laurent8a1095a2019-11-08 14:44:16 -08001271 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1272 *outputType = API_OUTPUT_TELEPHONY_TX;
1273 } else {
1274 *outputType = API_OUTPUT_LEGACY;
1275 }
1276
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001277 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1278
1279 return NO_ERROR;
1280}
1281
1282status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1283 audio_io_handle_t *output,
1284 audio_session_t session,
1285 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001286 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001287 const audio_config_t *config,
1288 audio_output_flags_t *flags,
1289 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001290 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001291 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001292 output_type_t *outputType,
1293 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001294{
1295 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1296 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1297 return INVALID_OPERATION;
1298 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001299 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001300 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001301 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001302 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001303 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001304 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001305 const sp<DeviceDescriptor> requestedDevice =
1306 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1307
1308 // Prevent from storing invalid requested device id in clients
1309 const audio_port_handle_t sanitizedRequestedPortId =
1310 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1311 *selectedDeviceId = sanitizedRequestedPortId;
1312
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001313 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001314 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001315 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001316 if (status != NO_ERROR) {
1317 return status;
1318 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001319 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001320 if (secondaryOutputs != nullptr) {
1321 for (auto &secondaryMix : secondaryMixes) {
1322 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1323 if (outputDesc != nullptr &&
1324 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1325 secondaryOutputs->push_back(outputDesc->mIoHandle);
1326 weakSecondaryOutputDescs.push_back(outputDesc);
1327 }
1328 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001329 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001330
Eric Laurent8fc147b2018-07-22 19:13:55 -07001331 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001332 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001333 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001334 };
jiabin4ef93452019-09-10 14:29:54 -07001335 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001336
Eric Laurentc209fe42020-06-05 18:11:23 -07001337 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001338 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001339 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001340 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001341 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001342 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001343 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001344 std::move(weakSecondaryOutputDescs),
1345 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001346 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001347
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001348 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1349 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001350
Eric Laurente83b55d2014-11-14 10:06:21 -08001351 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001352}
1353
Eric Laurentc529cf62020-04-17 18:19:10 -07001354status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1355 audio_session_t session,
1356 const audio_config_t *config,
1357 audio_output_flags_t flags,
1358 const DeviceVector &devices,
1359 audio_io_handle_t *output) {
1360
1361 *output = AUDIO_IO_HANDLE_NONE;
1362
1363 // skip direct output selection if the request can obviously be attached to a mixed output
1364 // and not explicitly requested
1365 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1366 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1367 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1368 return NAME_NOT_FOUND;
1369 }
1370
1371 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1372 // This prevents creating an offloaded track and tearing it down immediately after start
1373 // when audioflinger detects there is an active non offloadable effect.
1374 // FIXME: We should check the audio session here but we do not have it in this context.
1375 // This may prevent offloading in rare situations where effects are left active by apps
1376 // in the background.
1377 sp<IOProfile> profile;
1378 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1379 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1380 profile = getProfileForOutput(
1381 devices, config->sample_rate, config->format, config->channel_mask,
1382 flags, true /* directOnly */);
1383 }
1384
1385 if (profile == nullptr) {
1386 return NAME_NOT_FOUND;
1387 }
1388
1389 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1390 for (size_t i = 0; i < mOutputs.size(); i++) {
1391 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1392 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1393 // reuse direct output if currently open by the same client
1394 // and configured with same parameters
1395 if ((config->sample_rate == desc->getSamplingRate()) &&
1396 (config->format == desc->getFormat()) &&
1397 (config->channel_mask == desc->getChannelMask()) &&
1398 (session == desc->mDirectClientSession)) {
1399 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001400 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001401 mOutputs.keyAt(i), session);
1402 *output = mOutputs.keyAt(i);
1403 return NO_ERROR;
1404 }
1405 }
1406 }
1407
1408 if (!profile->canOpenNewIo()) {
1409 return NAME_NOT_FOUND;
1410 }
1411
1412 sp<SwAudioOutputDescriptor> outputDesc =
1413 new SwAudioOutputDescriptor(profile, mpClientInterface);
1414
Michael Chan6fb34492020-12-08 15:44:49 +11001415 // An MSD patch may be using the only output stream that can service this request. Release
1416 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001417 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001418
Eric Laurentf1f22e72021-07-13 14:04:14 +02001419 status_t status =
1420 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001421
1422 // only accept an output with the requested parameters
1423 if (status != NO_ERROR ||
1424 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1425 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1426 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1427 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1428 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1429 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1430 config->channel_mask, outputDesc->getChannelMask());
1431 if (*output != AUDIO_IO_HANDLE_NONE) {
1432 outputDesc->close();
1433 }
1434 // fall back to mixer output if possible when the direct output could not be open
1435 if (audio_is_linear_pcm(config->format) &&
1436 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1437 return NAME_NOT_FOUND;
1438 }
1439 *output = AUDIO_IO_HANDLE_NONE;
1440 return BAD_VALUE;
1441 }
1442 outputDesc->mDirectOpenCount = 1;
1443 outputDesc->mDirectClientSession = session;
1444
1445 addOutput(*output, outputDesc);
1446 mPreviousOutputs = mOutputs;
1447 ALOGV("%s returns new direct output %d", __func__, *output);
1448 mpClientInterface->onAudioPortListUpdate();
1449 return NO_ERROR;
1450}
1451
François Gaffie11d30102018-11-02 16:09:09 +01001452audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1453 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001454 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001455 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001456 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001457 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001458 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001459 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001460{
Andy Hungc88b0642018-04-27 15:42:35 -07001461 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001462
jiabine375d412019-02-26 12:54:53 -08001463 // Discard haptic channel mask when forcing muting haptic channels.
1464 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001465 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1466 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001467
Eric Laurente552edb2014-03-10 17:42:56 -07001468 // open a direct output if required by specified parameters
1469 //force direct flag if offload flag is set: offloading implies a direct output stream
1470 // and all common behaviors are driven by checking only the direct flag
1471 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001472 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1473 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001474 }
Nadav Bar766fb022018-01-07 12:18:03 +02001475 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1476 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001477 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001478
1479 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1480
Eric Laurente83b55d2014-11-14 10:06:21 -08001481 // only allow deep buffering for music stream type
1482 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001483 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001484 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001485 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001486 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1487 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001488 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001489 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001490 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001491 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001492 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001493 audio_is_linear_pcm(config->format) &&
1494 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001495 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001496 AUDIO_OUTPUT_FLAG_DIRECT);
1497 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001498 }
Eric Laurente552edb2014-03-10 17:42:56 -07001499
Carter Hsua3abb402021-10-26 11:11:20 +08001500 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1501 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1502 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1503 }
1504
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001505 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001506 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001507 && canBeSpatializedInt(attr, config,
1508 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001509 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001510 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001511 }
1512
Eric Laurentc529cf62020-04-17 18:19:10 -07001513 audio_config_t directConfig = *config;
1514 directConfig.channel_mask = channelMask;
1515 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1516 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001517 return output;
1518 }
1519
Eric Laurent14cbfca2016-03-17 09:42:16 -07001520 // A request for HW A/V sync cannot fallback to a mixed output because time
1521 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001522 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001523 return AUDIO_IO_HANDLE_NONE;
1524 }
1525
Eric Laurente552edb2014-03-10 17:42:56 -07001526 // ignoring channel mask due to downmix capability in mixer
1527
1528 // open a non direct output
1529
1530 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001531 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001532 // get which output is suitable for the specified stream. The actual
1533 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001534 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001535
Eric Laurent8838a382014-09-08 16:44:28 -07001536 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001537 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001538 output = selectOutput(
1539 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001540 }
François Gaffie11d30102018-11-02 16:09:09 +01001541 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001542 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001543 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001544
Eric Laurente552edb2014-03-10 17:42:56 -07001545 return output;
1546}
1547
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001548sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001549 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1550 mAvailableInputDevices);
1551 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1552}
1553
1554DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1555 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1556 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001557}
1558
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001559const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001560 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001561 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1562 if (msdModule != 0) {
1563 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1564 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1565 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1566 const struct audio_port_config *source = &patch->mPatch.sources[j];
1567 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1568 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001569 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001570 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001571 }
1572 }
1573 }
1574 return msdPatches;
1575}
1576
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001577bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1578 ssize_t index = mAudioPatches.indexOfKey(handle);
1579 if (index < 0) {
1580 return false;
1581 }
1582 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1583 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1584 if (msdModule == nullptr) {
1585 return false;
1586 }
1587 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1588 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1589 return true;
1590 }
1591 index = getMsdOutputPatches().indexOfKey(handle);
1592 if (index < 0) {
1593 return false;
1594 }
1595 return true;
1596}
1597
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001598status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1599 const InputProfileCollection &inputProfiles,
1600 const OutputProfileCollection &outputProfiles,
1601 const sp<DeviceDescriptor> &sourceDevice,
1602 const sp<DeviceDescriptor> &sinkDevice,
1603 AudioProfileVector& sourceProfiles,
1604 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001605 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001606 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001607 return NO_INIT;
1608 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001609 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001611 return NO_INIT;
1612 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001613 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001614 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1615 inProfile->supportsDevice(sourceDevice)) {
1616 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001617 }
1618 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001619 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001620 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001621 outProfile->supportsDevice(sinkDevice)) {
1622 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001623 }
1624 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001625 return NO_ERROR;
1626}
1627
1628status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1629 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1630 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1631{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001633 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1634 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1635 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001637 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1638 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001639 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001640 }
1641 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1642 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1643 sinkConfig->format = bestSinkConfig.format;
1644 // For encoded streams force direct flag to prevent downstream mixing.
1645 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1646 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001647 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1648 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001649 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001650 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1651 // raw and IEC61937 framed streams.
1652 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1653 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1654 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001655 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1656 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1657 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1658 sourceConfig->format = bestSinkConfig.format;
1659 // Copy input stream directly without any processing (e.g. resampling).
1660 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1661 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1662 if (hwAvSync) {
1663 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1664 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1665 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1666 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1667 }
1668 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1669 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1670 sinkConfig->config_mask |= config_mask;
1671 sourceConfig->config_mask |= config_mask;
1672 return NO_ERROR;
1673}
1674
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001675PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1676 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001677{
1678 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001679 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1680 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1681 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1682 if (deviceModule == nullptr) {
1683 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1684 return patchBuilder;
1685 }
1686 const InputProfileCollection inputProfiles = msdIsSource ?
1687 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1688 const OutputProfileCollection outputProfiles = msdIsSource ?
1689 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1690
1691 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1692 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1693 device : getMsdAudioOutDevices().itemAt(0);
1694 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1695
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1697 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001698 AudioProfileVector sourceProfiles;
1699 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001700 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1701 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001702 for (auto hwAvSync : { true, false }) {
1703 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1704 sourceProfiles, sinkProfiles) != NO_ERROR) {
1705 continue;
1706 }
1707 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1708 &sinkConfig) == NO_ERROR) {
1709 // Found a matching config. Re-create PatchBuilder with this config.
1710 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1711 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001714 " supporting PCM format conversion.", __func__);
1715 return patchBuilder;
1716}
1717
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001718status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001719 DeviceVector devices;
1720 if (outputDevices != nullptr && outputDevices->size() > 0) {
1721 devices.add(*outputDevices);
1722 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 // Use media strategy for unspecified output device. This should only
1724 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1725 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001726 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001727 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001728 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001729 }
Michael Chan6fb34492020-12-08 15:44:49 +11001730 std::vector<PatchBuilder> patchesToCreate;
1731 for (auto i = 0u; i < devices.size(); ++i) {
1732 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001733 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001734 }
1735 // Retain only the MSD patches associated with outputDevices request.
1736 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001737 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001738 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1739 auto retainedPatch = false;
1740 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1741 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1742 patchesToRemove.removeItemsAt(i);
1743 retainedPatch = true;
1744 break;
1745 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001746 }
Michael Chan6fb34492020-12-08 15:44:49 +11001747 if (retainedPatch) {
1748 it = patchesToCreate.erase(it);
1749 continue;
1750 }
1751 ++it;
1752 }
1753 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1754 return NO_ERROR;
1755 }
1756 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1757 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001758 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001759 }
Michael Chan6fb34492020-12-08 15:44:49 +11001760 status_t status = NO_ERROR;
1761 for (const auto &p : patchesToCreate) {
1762 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1763 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1764 char message[256];
1765 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1766 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1767 currStatus == NO_ERROR ? "Success" : "Error",
1768 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1769 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1770 if (currStatus == NO_ERROR) {
1771 ALOGD("%s", message);
1772 } else {
1773 ALOGE("%s", message);
1774 if (status == NO_ERROR) {
1775 status = currStatus;
1776 }
1777 }
1778 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 return status;
1780}
1781
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001782void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1783 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001784 for (size_t i = 0; i < msdPatches.size(); i++) {
1785 const auto& patch = msdPatches[i];
1786 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1787 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1788 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1789 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1790 releaseAudioPatch(patch->getHandle(), mUidCached);
1791 break;
1792 }
1793 }
1794 }
1795}
1796
Dorin Drimus94d94412022-02-02 09:05:02 +01001797bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1798 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1799 AudioPatchCollection msdPatches = getMsdOutputPatches();
1800 for (size_t i = 0; i < msdPatches.size(); i++) {
1801 const auto& patch = msdPatches[i];
1802 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1803 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1804 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1805 const auto& foundDevice = devicesToCheck.getDevice(
1806 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1807 if (foundDevice != nullptr) {
1808 devicesToCheck.remove(foundDevice);
1809 if (devicesToCheck.isEmpty()) {
1810 return true;
1811 }
1812 }
1813 }
1814 }
1815 }
1816 return false;
1817}
1818
Eric Laurente0720872014-03-11 09:30:41 -07001819audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001820 audio_output_flags_t flags,
1821 audio_format_t format,
1822 audio_channel_mask_t channelMask,
1823 uint32_t samplingRate,
1824 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001825{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001826 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1827 "%s called with format %#x", __func__, format);
1828
jiabinebb6af42020-06-09 17:31:17 -07001829 // Return the output that haptic-generating attached to when 1) session id is specified,
1830 // 2) haptic-generating effect exists for given session id and 3) the output that
1831 // haptic-generating effect attached to is in given outputs.
1832 if (sessionId != AUDIO_SESSION_NONE) {
1833 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1834 sessionId, FX_IID_HAPTICGENERATOR);
1835 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1836 return hapticGeneratingOutput;
1837 }
1838 }
1839
Eric Laurent16c66dd2019-05-01 17:54:10 -07001840 // Flags disqualifying an output: the match must happen before calling selectOutput()
1841 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1842 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1843
1844 // Flags expressing a functional request: must be honored in priority over
1845 // other criteria
1846 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1847 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001848 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1849 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001850 // Flags expressing a performance request: have lower priority than serving
1851 // requested sampling rate or channel mask
1852 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1853 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1854 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1855
1856 const audio_output_flags_t functionalFlags =
1857 (audio_output_flags_t)(flags & kFunctionalFlags);
1858 const audio_output_flags_t performanceFlags =
1859 (audio_output_flags_t)(flags & kPerformanceFlags);
1860
1861 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1862
Eric Laurente552edb2014-03-10 17:42:56 -07001863 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001864 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001865 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001866 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001867 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001868 // with tiebreak preferring the minimum number of extra functional flags
1869 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001870 // 3: the output supporting the exact channel mask
1871 // 4: the output with a higher channel count than requested
1872 // 5: the output with a higher sampling rate than requested
1873 // 6: the output with the highest number of requested performance flags
1874 // 7: the output with the bit depth the closest to the requested one
1875 // 8: the primary output
1876 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001877
Eric Laurent16c66dd2019-05-01 17:54:10 -07001878 // matching criteria values in priority order for best matching output so far
1879 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001880
Eric Laurent16c66dd2019-05-01 17:54:10 -07001881 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1882 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1883 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001884
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001885 for (audio_io_handle_t output : outputs) {
1886 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001887 // matching criteria values in priority order for current output
1888 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001889
Eric Laurent16c66dd2019-05-01 17:54:10 -07001890 if (outputDesc->isDuplicated()) {
1891 continue;
1892 }
1893 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1894 continue;
1895 }
Eric Laurent8838a382014-09-08 16:44:28 -07001896
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 // If haptic channel is specified, use the haptic output if present.
1898 // When using haptic output, same audio format and sample rate are required.
1899 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001900 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001901 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1902 continue;
1903 }
1904 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001905 && format == outputDesc->getFormat()
1906 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001907 currentMatchCriteria[0] = outputHapticChannelCount;
1908 }
1909
1910 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001911 const int matchingFunctionalFlags =
1912 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1913 const int totalFunctionalFlags =
1914 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1915 // Prefer matching functional flags, but subtract unnecessary functional flags.
1916 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917
1918 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001919 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1920 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1922 channelCount <= outputChannelCount) {
1923 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001924 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1925 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001926 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001927 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001928 currentMatchCriteria[3] = outputChannelCount;
1929 }
1930
1931 // sampling rate match
1932 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001933 samplingRate <= outputDesc->getSamplingRate()) {
1934 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001935 }
1936
1937 // performance flags match
1938 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1939
1940 // format match
1941 if (format != AUDIO_FORMAT_INVALID) {
1942 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001943 PolicyAudioPort::kFormatDistanceMax -
1944 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001945 }
1946
1947 // primary output match
1948 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1949
1950 // compare match criteria by priority then value
1951 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1952 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1953 bestMatchCriteria = currentMatchCriteria;
1954 bestOutput = output;
1955
1956 std::stringstream result;
1957 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1958 std::ostream_iterator<int>(result, " "));
1959 ALOGV("%s new bestOutput %d criteria %s",
1960 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001961 }
1962 }
1963
Eric Laurent16c66dd2019-05-01 17:54:10 -07001964 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001965}
1966
Eric Laurent8fc147b2018-07-22 19:13:55 -07001967status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001968{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001969 ALOGV("%s portId %d", __FUNCTION__, portId);
1970
1971 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1972 if (outputDesc == 0) {
1973 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001974 return BAD_VALUE;
1975 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001976 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001977
Eric Laurent8fc147b2018-07-22 19:13:55 -07001978 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001979 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001980
Eric Laurent733ce942017-12-07 12:18:25 -08001981 status_t status = outputDesc->start();
1982 if (status != NO_ERROR) {
1983 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001984 }
1985
Eric Laurent97ac8712018-07-27 18:59:02 -07001986 uint32_t delayMs;
1987 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001988
1989 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001990 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001991 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001992 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001993 if (delayMs != 0) {
1994 usleep(delayMs * 1000);
1995 }
1996
1997 return status;
1998}
1999
Eric Laurent96d1dda2022-03-14 17:14:19 +01002000bool AudioPolicyManager::isLeUnicastActive() const {
2001 if (isInCall()) {
2002 return true;
2003 }
2004 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2005}
2006
2007bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2008 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2009 return false;
2010 }
2011 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2012 ALOGV("%s active %d", __func__, active);
2013 return active;
2014}
2015
Eric Laurent97ac8712018-07-27 18:59:02 -07002016status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2017 const sp<TrackClientDescriptor>& client,
2018 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002019{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002020 // cannot start playback of STREAM_TTS if any other output is being used
2021 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002022
2023 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002024 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002025 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002026 auto clientStrategy = client->strategy();
2027 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002028 if (stream == AUDIO_STREAM_TTS) {
2029 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002030 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002031 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002032 return INVALID_OPERATION;
2033 } else {
2034 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2035 }
2036 } else {
2037 // some playback other than beacon starts
2038 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2039 }
2040
Eric Laurent77305a62016-07-25 16:39:22 -07002041 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002042 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002043 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002044
François Gaffie11d30102018-11-02 16:09:09 +01002045 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002046 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002047 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002048 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002049 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002051 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002052 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002053 } else {
2054 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002055 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002056 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2057 AUDIO_FORMAT_DEFAULT);
2058 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2059 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002060 }
2061
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002062 // requiresMuteCheck is false when we can bypass mute strategy.
2063 // It covers a common case when there is no materially active audio
2064 // and muting would result in unnecessary delay and dropped audio.
2065 const uint32_t outputLatencyMs = outputDesc->latency();
2066 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002067 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002068
Eric Laurente552edb2014-03-10 17:42:56 -07002069 // increment usage count for this stream on the requested output:
2070 // NOTE that the usage count is the same for duplicated output and hardware output which is
2071 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002072 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002073
2074 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002075 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2076 client->isPreferredDeviceForExclusiveUse()) {
2077 // Preferred device may be exclusive, use only if no other active clients on this output
2078 devices = DeviceVector(
2079 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2080 } else {
2081 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2082 }
François Gaffie11d30102018-11-02 16:09:09 +01002083 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002084 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002085 }
2086 }
Eric Laurente552edb2014-03-10 17:42:56 -07002087
François Gaffiec005e562018-11-06 15:04:49 +01002088 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002089 selectOutputForMusicEffects();
2090 }
2091
François Gaffie1c878552018-11-22 16:53:21 +01002092 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002093 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002094 if (devices.isEmpty()) {
2095 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002096 }
François Gaffiec005e562018-11-06 15:04:49 +01002097 bool shouldWait =
2098 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2099 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2100 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002101 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002102 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002103 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002104 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002105 // An output has a shared device if
2106 // - managed by the same hw module
2107 // - supports the currently selected device
2108 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002109 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002110
Eric Laurent77305a62016-07-25 16:39:22 -07002111 // force a device change if any other output is:
2112 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002113 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002114 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002115 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002116 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002117 // change the device currently selected by the other output.
2118 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002119 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002120 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002121 force = true;
2122 }
2123 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002124 // a notification so that audio focus effect can propagate, or that a mute/unmute
2125 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002126 const uint32_t latencyMs = desc->latency();
2127 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2128
2129 if (shouldWait && isActive && (waitMs < latencyMs)) {
2130 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002131 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002132
2133 // Require mute check if another output is on a shared device
2134 // and currently active to have proper drain and avoid pops.
2135 // Note restoring AudioTracks onto this output needs to invoke
2136 // a volume ramp if there is no mute.
2137 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002138 }
2139 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002140
2141 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002142 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002143
Eric Laurente552edb2014-03-10 17:42:56 -07002144 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002145 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002146 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002147 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002148 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002149 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002150 outputDesc->useHwGain() /*force*/)) {
2151 // request AudioService to reinitialize the volume curves asynchronously
2152 ALOGE("checkAndSetVolume failed, requesting volume range init");
2153 mpClientInterface->onVolumeRangeInitRequest();
2154 };
Eric Laurente552edb2014-03-10 17:42:56 -07002155
2156 // update the outputs if starting an output with a stream that can affect notification
2157 // routing
2158 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002159
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002160 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002161 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002162 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2163 }
Eric Laurentdc462862016-07-19 12:29:53 -07002164
2165 if (waitMs > muteWaitMs) {
2166 *delayMs = waitMs - muteWaitMs;
2167 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002168
2169 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2170 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2171 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2172 // change occurs after the MixerThread starts and causes a stream volume
2173 // glitch.
2174 //
2175 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002176 }
Eric Laurentdc462862016-07-19 12:29:53 -07002177
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002178 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002179 mEngine->getForceUse(
2180 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002181 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002182 }
2183
Eric Laurent97ac8712018-07-27 18:59:02 -07002184 // Automatically enable the remote submix input when output is started on a re routing mix
2185 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002186 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2187 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002188 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2189 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2190 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002191 "remote-submix",
2192 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002193 }
2194
Eric Laurent96d1dda2022-03-14 17:14:19 +01002195 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2196
Eric Laurente552edb2014-03-10 17:42:56 -07002197 return NO_ERROR;
2198}
2199
Eric Laurent96d1dda2022-03-14 17:14:19 +01002200void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2201 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2202 bool isUnicastActive = isLeUnicastActive();
2203
2204 if (wasUnicastActive != isUnicastActive) {
2205 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2206 for (size_t i = 0; i < mOutputs.size(); i++) {
2207 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2208 if (desc != ignoredOutput && desc->isActive()
2209 && ((isUnicastActive &&
2210 !desc->devices().
2211 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2212 || (wasUnicastActive &&
2213 !desc->devices().getDevicesFromTypes(
2214 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2215 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2216 bool force = desc->devices() != newDevices;
2217 setOutputDevices(desc, newDevices, force, delayMs);
2218 // re-apply device specific volume if not done by setOutputDevice()
2219 if (!force) {
2220 applyStreamVolumes(desc, newDevices.types(), delayMs);
2221 }
2222 }
2223 }
2224 }
2225}
2226
Eric Laurent8fc147b2018-07-22 19:13:55 -07002227status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002228{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002229 ALOGV("%s portId %d", __FUNCTION__, portId);
2230
2231 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2232 if (outputDesc == 0) {
2233 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002234 return BAD_VALUE;
2235 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002236 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002237
Eric Laurent97ac8712018-07-27 18:59:02 -07002238 ALOGV("stopOutput() output %d, stream %d, session %d",
2239 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002240
Eric Laurent97ac8712018-07-27 18:59:02 -07002241 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002242
Eric Laurent733ce942017-12-07 12:18:25 -08002243 if (status == NO_ERROR ) {
2244 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002245 }
2246 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002247}
2248
Eric Laurent97ac8712018-07-27 18:59:02 -07002249status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2250 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002251{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002252 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002253 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002254 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002255 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002256
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002257 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2258
François Gaffie1c878552018-11-22 16:53:21 +01002259 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2260 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002261 // Automatically disable the remote submix input when output is stopped on a
2262 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002263 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002264 if (isSingleDeviceType(
2265 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002266 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002267 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002268 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2269 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002270 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002271 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 }
2273 }
2274 bool forceDeviceUpdate = false;
2275 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002276 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002277 forceDeviceUpdate = true;
2278 }
2279
Eric Laurente552edb2014-03-10 17:42:56 -07002280 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002281 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002282
Eric Laurente552edb2014-03-10 17:42:56 -07002283 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002284 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002285 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002286 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002287
2288 // If the routing does not change, if an output is routed on a device using HwGain
2289 // (aka setAudioPortConfig) and there are still active clients following different
2290 // volume group(s), force reapply volume
2291 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2292 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2293
Eric Laurente552edb2014-03-10 17:42:56 -07002294 // delay the device switch by twice the latency because stopOutput() is executed when
2295 // the track stop() command is received and at that time the audio track buffer can
2296 // still contain data that needs to be drained. The latency only covers the audio HAL
2297 // and kernel buffers. Also the latency does not always include additional delay in the
2298 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002299 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2300 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002301
2302 // force restoring the device selection on other active outputs if it differs from the
2303 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002304 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002305 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002306 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002307 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002308 desc->isActive() &&
2309 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002310 (newDevices != desc->devices())) {
2311 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2312 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002313
François Gaffie11d30102018-11-02 16:09:09 +01002314 setOutputDevices(desc, newDevices2, force, delayMs);
2315
Eric Laurent57de36c2016-09-28 16:59:11 -07002316 // re-apply device specific volume if not done by setOutputDevice()
2317 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002318 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002319 }
Eric Laurente552edb2014-03-10 17:42:56 -07002320 }
2321 }
2322 // update the outputs if stopping one with a stream that can affect notification routing
2323 handleNotificationRoutingForStream(stream);
2324 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002325
2326 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2327 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002328 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002329 }
2330
François Gaffiec005e562018-11-06 15:04:49 +01002331 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002332 selectOutputForMusicEffects();
2333 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002334
2335 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2336
Eric Laurente552edb2014-03-10 17:42:56 -07002337 return NO_ERROR;
2338 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002339 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002340 return INVALID_OPERATION;
2341 }
2342}
2343
jiabinbce0c1d2020-10-05 11:20:18 -07002344bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002345{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002346 ALOGV("%s portId %d", __FUNCTION__, portId);
2347
2348 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2349 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002350 // If an output descriptor is closed due to a device routing change,
2351 // then there are race conditions with releaseOutput from tracks
2352 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2353 // destroyed shortly thereafter.
2354 //
2355 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002356 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002357 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002358 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002359
2360 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002361
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302362 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2363 if (outputDesc->isClientActive(client)) {
2364 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2365 stopOutput(portId);
2366 }
2367
Eric Laurent8fc147b2018-07-22 19:13:55 -07002368 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2369 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002370 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002371 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002372 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002373 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002374 if (--outputDesc->mDirectOpenCount == 0) {
2375 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002376 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002377 }
2378 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302379
Andy Hung39efb7a2018-09-26 15:39:28 -07002380 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002381 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2382 // The output is pending reopened to query dynamic profiles and
2383 // there is no active clients
2384 closeOutput(outputDesc->mIoHandle);
2385 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2386 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2387 if (newOutputDesc == nullptr) {
2388 ALOGE("%s failed to open output", __func__);
2389 }
2390 return true;
2391 }
2392 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002393}
2394
Eric Laurentcaf7f482014-11-25 17:50:47 -08002395status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2396 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002397 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002398 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002399 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002400 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002401 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002402 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002403 input_type_t *inputType,
2404 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002405{
François Gaffiec005e562018-11-06 15:04:49 +01002406 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002407 "flags %#x attributes=%s requested device ID %d",
2408 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2409 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002410
Eric Laurentad2e7b92017-09-14 20:06:42 -07002411 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002412 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002413 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002414 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002415 sp<AudioInputDescriptor> inputDesc;
2416 sp<RecordClientDescriptor> clientDesc;
2417 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002418 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002419 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002420
2421 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2422 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2423 return INVALID_OPERATION;
2424 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002425
Francois Gaffie716e1432019-01-14 16:58:59 +01002426 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2427 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002428 }
2429
Paul McLean466dc8e2015-04-17 13:15:36 -06002430 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002431 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002432 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002433
Eric Laurentad2e7b92017-09-14 20:06:42 -07002434 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2435 // possible
2436 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2437 *input != AUDIO_IO_HANDLE_NONE) {
2438 ssize_t index = mInputs.indexOfKey(*input);
2439 if (index < 0) {
2440 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2441 status = BAD_VALUE;
2442 goto error;
2443 }
2444 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002445 RecordClientVector clients = inputDesc->getClientsForSession(session);
2446 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002447 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2448 status = BAD_VALUE;
2449 goto error;
2450 }
2451 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2452 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002453 // corresponds to a new client and is only permitted from the same UID.
2454 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002455 if (clients.size() > 1) {
2456 for (const auto& client : clients) {
2457 // The client map is ordered by key values (portId) and portIds are allocated
2458 // incrementaly. So the first client in this list is the one opened by audio flinger
2459 // when the mmap stream is created and should be ignored as it does not correspond
2460 // to an actual client
2461 if (client == *clients.cbegin()) {
2462 continue;
2463 }
2464 if (uid != client->uid() && !client->isSilenced()) {
2465 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2466 uid, client->portId(), client->uid());
2467 status = INVALID_OPERATION;
2468 goto error;
2469 }
Eric Laurent331679c2018-04-16 17:03:16 -07002470 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002471 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002472 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002473 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002474
Eric Laurentfecbceb2021-02-09 14:46:43 +01002475 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002476 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002477 }
2478
2479 *input = AUDIO_IO_HANDLE_NONE;
2480 *inputType = API_INPUT_INVALID;
2481
Francois Gaffie716e1432019-01-14 16:58:59 +01002482 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2483 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2484 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002485 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002486 ALOGW("%s could not find input mix for attr %s",
2487 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002488 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002489 }
jiabinc1de2df2019-05-07 14:26:40 -07002490 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2491 String8(attr->tags + strlen("addr=")),
2492 AUDIO_FORMAT_DEFAULT);
2493 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002494 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002495 __func__, attributes.source, attributes.tags);
2496 status = BAD_VALUE;
2497 goto error;
2498 }
2499
Kevin Rocard25f9b052019-02-27 15:08:54 -08002500 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2501 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2502 } else {
2503 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2504 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002505 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002506 if (explicitRoutingDevice != nullptr) {
2507 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002508 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002509 // Prevent from storing invalid requested device id in clients
2510 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002511 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002512 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2513 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002514 }
François Gaffie11d30102018-11-02 16:09:09 +01002515 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002516 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002517 status = BAD_VALUE;
2518 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002519 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002520 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2521 *inputType = API_INPUT_MIX_CAPTURE;
2522 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002523 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2524 // there is an external policy, but this input is attached to a mix of recorders,
2525 // meaning it receives audio injected into the framework, so the recorder doesn't
2526 // know about it and is therefore considered "legacy"
2527 *inputType = API_INPUT_LEGACY;
2528 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002529 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002530 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002531 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002532 } else {
2533 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002534 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002535
Eric Laurent599c7582015-12-07 18:05:55 -08002536 }
2537
François Gaffiec005e562018-11-06 15:04:49 +01002538 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002539 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002540 status = INVALID_OPERATION;
2541 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002542 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002543
Eric Laurent8f42ea12018-08-08 09:08:25 -07002544exit:
2545
François Gaffiec005e562018-11-06 15:04:49 +01002546 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2547 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002548
Francois Gaffie716e1432019-01-14 16:58:59 +01002549 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002550 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002551 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002552
Mikhail Naganov2996f672019-04-18 12:29:59 -07002553 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002554 requestedDeviceId, attributes.source, flags,
2555 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002556 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002557 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002558
2559 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2560 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002561
Eric Laurent599c7582015-12-07 18:05:55 -08002562 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002563
2564error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002565 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002566}
2567
2568
François Gaffie11d30102018-11-02 16:09:09 +01002569audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002570 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002571 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002572 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002573 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002574 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002575{
2576 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002577 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002578 bool isSoundTrigger = false;
2579
François Gaffiec005e562018-11-06 15:04:49 +01002580 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002581 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2582 if (index >= 0) {
2583 input = mSoundTriggerSessions.valueFor(session);
2584 isSoundTrigger = true;
2585 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2586 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2587 } else {
2588 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002589 }
François Gaffiec005e562018-11-06 15:04:49 +01002590 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002591 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002592 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002593 }
2594
Carter Hsua3abb402021-10-26 11:11:20 +08002595 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2596 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2597 }
2598
Andy Hungf129b032015-04-07 13:45:50 -07002599 // find a compatible input profile (not necessarily identical in parameters)
2600 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002601 // sampling rate and flags may be updated by getInputProfile
2602 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2603 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002604 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002605 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002606 audio_input_flags_t profileFlags = flags;
2607 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002608 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002609 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002610 profileFlags);
2611 if (profile != 0) {
2612 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002613 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2614 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002615 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002616 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2617 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002618 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002619 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002620 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002621 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002622 }
Eric Laurente552edb2014-03-10 17:42:56 -07002623 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002624 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002625 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002626 if (samplingRate == 0) {
2627 samplingRate = profileSamplingRate;
2628 }
Eric Laurente552edb2014-03-10 17:42:56 -07002629
Eric Laurent322b4d22015-04-03 15:57:54 -07002630 if (profile->getModuleHandle() == 0) {
2631 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002632 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002633 }
2634
Eric Laurentec376dc2021-04-08 20:41:22 +02002635 // Reuse an already opened input if a client with the same session ID already exists
2636 // on that input
2637 for (size_t i = 0; i < mInputs.size(); i++) {
2638 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2639 if (desc->mProfile != profile) {
2640 continue;
2641 }
2642 RecordClientVector clients = desc->clientsList();
2643 for (const auto &client : clients) {
2644 if (session == client->session()) {
2645 return desc->mIoHandle;
2646 }
2647 }
2648 }
2649
Eric Laurent3974e3b2017-12-07 17:58:43 -08002650 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002651 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002652 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002653 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002654 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002655 continue;
2656 }
2657 // if sound trigger, reuse input if used by other sound trigger on same session
2658 // else
2659 // reuse input if active client app is not in IDLE state
2660 //
2661 RecordClientVector clients = desc->clientsList();
2662 bool doClose = false;
2663 for (const auto& client : clients) {
2664 if (isSoundTrigger != client->isSoundTrigger()) {
2665 continue;
2666 }
2667 if (client->isSoundTrigger()) {
2668 if (session == client->session()) {
2669 return desc->mIoHandle;
2670 }
2671 continue;
2672 }
2673 if (client->active() && client->appState() != APP_STATE_IDLE) {
2674 return desc->mIoHandle;
2675 }
2676 doClose = true;
2677 }
2678 if (doClose) {
2679 closeInput(desc->mIoHandle);
2680 } else {
2681 i++;
2682 }
2683 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002684 }
2685
Eric Laurentfe231122017-11-17 17:48:06 -08002686 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002687
Eric Laurentfe231122017-11-17 17:48:06 -08002688 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2689 lConfig.sample_rate = profileSamplingRate;
2690 lConfig.channel_mask = profileChannelMask;
2691 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002692
François Gaffie11d30102018-11-02 16:09:09 +01002693 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002694
2695 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002696 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002697 (profileSamplingRate != lConfig.sample_rate) ||
2698 !audio_formats_match(profileFormat, lConfig.format) ||
2699 (profileChannelMask != lConfig.channel_mask)) {
2700 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002701 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002702 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002703 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002704 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002705 }
Eric Laurent599c7582015-12-07 18:05:55 -08002706 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002707 }
2708
Eric Laurentc722f302014-12-10 11:21:49 -08002709 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002710
Eric Laurent599c7582015-12-07 18:05:55 -08002711 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002712 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002713
Eric Laurent599c7582015-12-07 18:05:55 -08002714 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002715}
2716
Eric Laurent4eb58f12018-12-07 16:41:02 -08002717status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002718{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002719 ALOGV("%s portId %d", __FUNCTION__, portId);
2720
2721 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2722 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002723 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002724 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002726 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002727 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002728 if (client->active()) {
2729 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2730 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002731 }
2732
Eric Laurent8f42ea12018-08-08 09:08:25 -07002733 audio_session_t session = client->session();
2734
Eric Laurent4eb58f12018-12-07 16:41:02 -08002735 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002736
Eric Laurent4eb58f12018-12-07 16:41:02 -08002737 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002738
Eric Laurent4eb58f12018-12-07 16:41:02 -08002739 status_t status = inputDesc->start();
2740 if (status != NO_ERROR) {
2741 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002742 }
Eric Laurente552edb2014-03-10 17:42:56 -07002743
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002744 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002745 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002746 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002747
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748 // indicate active capture to sound trigger service if starting capture from a mic on
2749 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002750 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002751 if (device != nullptr) {
2752 status = setInputDevice(input, device, true /* force */);
2753 } else {
2754 ALOGW("%s no new input device can be found for descriptor %d",
2755 __FUNCTION__, inputDesc->getId());
2756 status = BAD_VALUE;
2757 }
Eric Laurente552edb2014-03-10 17:42:56 -07002758
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002759 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002760 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002761 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002762 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002763 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2764 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002765 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002766 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002767
François Gaffie11d30102018-11-02 16:09:09 +01002768 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2769 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002771 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002772 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002773
Eric Laurent8f42ea12018-08-08 09:08:25 -07002774 // automatically enable the remote submix output when input is started if not
2775 // used by a policy mix of type MIX_TYPE_RECORDERS
2776 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002777 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002778 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002779 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002781 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2782 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002783 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002784 if (address != "") {
2785 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2786 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002787 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002788 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002789 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002790 } else if (status != NO_ERROR) {
2791 // Restore client activity state.
2792 inputDesc->setClientActive(client, false);
2793 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002794 }
2795
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002796 ALOGV("%s input %d source = %d status = %d exit",
2797 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002798
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002799 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002800}
2801
Eric Laurent8fc147b2018-07-22 19:13:55 -07002802status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002803{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002804 ALOGV("%s portId %d", __FUNCTION__, portId);
2805
2806 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2807 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002808 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002809 return BAD_VALUE;
2810 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002811 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002812 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002813 if (!client->active()) {
2814 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002815 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002816 }
Carter Hsue6139d52021-07-08 10:30:20 +08002817 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002818 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002819
Eric Laurent8f42ea12018-08-08 09:08:25 -07002820 inputDesc->stop();
2821 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002822 auto current_source = inputDesc->source();
2823 setInputDevice(input, getNewInputDevice(inputDesc),
2824 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002825 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002826 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002827 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002828 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002829 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2830 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002831 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002832 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002833
2834 // automatically disable the remote submix output when input is stopped if not
2835 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002836 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002838 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002839 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002840 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2841 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 }
2843 if (address != "") {
2844 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2845 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002846 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002847 }
2848 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002849 resetInputDevice(input);
2850
2851 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2852 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002853 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2854 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002856 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002857 }
2858 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002859 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002860 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002861}
2862
Eric Laurent8fc147b2018-07-22 19:13:55 -07002863void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002864{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002865 ALOGV("%s portId %d", __FUNCTION__, portId);
2866
2867 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2868 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002870 return;
2871 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002872 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002873 audio_io_handle_t input = inputDesc->mIoHandle;
2874
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002876
Andy Hung39efb7a2018-09-26 15:39:28 -07002877 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002878
Andy Hung39efb7a2018-09-26 15:39:28 -07002879 if (inputDesc->getClientCount() > 0) {
2880 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002881 return;
2882 }
2883
Eric Laurent05b90f82014-08-27 15:32:29 -07002884 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002885 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002886 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002887}
2888
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002890{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892
2893 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002894 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895 }
2896}
2897
Eric Laurent8f42ea12018-08-08 09:08:25 -07002898void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2899{
2900 stopInput(portId);
2901 releaseInput(portId);
2902}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002903
Eric Laurent0dd51852019-04-19 18:18:58 -07002904void AudioPolicyManager::checkCloseInputs() {
2905 // After connecting or disconnecting an input device, close input if:
2906 // - it has no client (was just opened to check profile) OR
2907 // - none of its supported devices are connected anymore OR
2908 // - one of its clients cannot be routed to one of its supported
2909 // devices anymore. Otherwise update device selection
2910 std::vector<audio_io_handle_t> inputsToClose;
2911 for (size_t i = 0; i < mInputs.size(); i++) {
2912 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2913 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002914 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002915 inputsToClose.push_back(mInputs.keyAt(i));
2916 } else {
2917 bool close = false;
2918 for (const auto& client : input->clientsList()) {
2919 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002920 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002921 if (!input->supportedDevices().contains(device)) {
2922 close = true;
2923 break;
2924 }
2925 }
2926 if (close) {
2927 inputsToClose.push_back(mInputs.keyAt(i));
2928 } else {
2929 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2930 }
2931 }
2932 }
2933
2934 for (const audio_io_handle_t handle : inputsToClose) {
2935 ALOGV("%s closing input %d", __func__, handle);
2936 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002937 }
Eric Laurentd4692962014-05-05 18:13:44 -07002938}
2939
François Gaffie251c7f02018-11-07 10:41:08 +01002940void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002941{
2942 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002943 if (indexMin < 0 || indexMax < 0) {
2944 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2945 return;
2946 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002947 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002948
2949 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002950 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2951 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002952 continue;
2953 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002954 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002955 }
Eric Laurente552edb2014-03-10 17:42:56 -07002956}
2957
Eric Laurente0720872014-03-11 09:30:41 -07002958status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002959 int index,
2960 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002961{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002962 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002963 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2964 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2965 return NO_ERROR;
2966 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002967 ALOGV("%s: stream %s attributes=%s", __func__,
2968 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002969 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002970}
2971
Eric Laurente0720872014-03-11 09:30:41 -07002972status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002973 int *index,
2974 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002975{
François Gaffiec005e562018-11-06 15:04:49 +01002976 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2977 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002978 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002979 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002980 deviceTypes = mEngine->getOutputDevicesForStream(
2981 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002982 }
jiabin9a3361e2019-10-01 09:38:30 -07002983 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002984}
2985
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002986status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002987 int index,
2988 audio_devices_t device)
2989{
2990 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002991 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2992 if (group == VOLUME_GROUP_NONE) {
2993 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002994 return BAD_VALUE;
2995 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002996 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002997 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002998 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002999 VolumeSource vs = toVolumeSource(group);
3000 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3001
3002 status = setVolumeCurveIndex(index, device, curves);
3003 if (status != NO_ERROR) {
3004 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3005 return status;
3006 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003007
jiabin9a3361e2019-10-01 09:38:30 -07003008 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003009 auto curCurvAttrs = curves.getAttributes();
3010 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3011 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003012 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003013 } else if (!curves.getStreamTypes().empty()) {
3014 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003015 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003016 } else {
3017 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3018 return BAD_VALUE;
3019 }
jiabin9a3361e2019-10-01 09:38:30 -07003020 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3021 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003022
François Gaffiecfe17322018-11-07 13:41:29 +01003023 // update volume on all outputs and streams matching the following:
3024 // - The requested stream (or a stream matching for volume control) is active on the output
3025 // - The device (or devices) selected by the engine for this stream includes
3026 // the requested device
3027 // - For non default requested device, currently selected device on the output is either the
3028 // requested device or one of the devices selected by the engine for this stream
3029 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3030 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003031 for (size_t i = 0; i < mOutputs.size(); i++) {
3032 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003033 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003034
jiabin9a3361e2019-10-01 09:38:30 -07003035 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3036 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003037 }
François Gaffieed91f582020-01-31 10:35:37 +01003038 if (!(desc->isActive(vs) || isInCall())) {
3039 continue;
3040 }
3041 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3042 curDevices.find(device) == curDevices.end()) {
3043 continue;
3044 }
3045 bool applyVolume = false;
3046 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3047 curSrcDevices.insert(device);
3048 applyVolume = (curSrcDevices.find(
3049 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3050 } else {
3051 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3052 }
3053 if (!applyVolume) {
3054 continue; // next output
3055 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003056 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3057 // If a higher priority strategy is active, and the output is routed to a device with a
3058 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003059 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003060 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003061 // If the volume source is active with higher priority source, ensure at least Sw Muted
3062 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003063 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3064 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3065 false /*preferredDevice*/);
3066 if (activeClients.empty()) {
3067 continue;
3068 }
3069 bool isPreempted = false;
3070 bool isHigherPriority = productStrategy < strategy;
3071 for (const auto &client : activeClients) {
3072 if (isHigherPriority && (client->volumeSource() != vs)) {
3073 ALOGV("%s: Strategy=%d (\nrequester:\n"
3074 " group %d, volumeGroup=%d attributes=%s)\n"
3075 " higher priority source active:\n"
3076 " volumeGroup=%d attributes=%s) \n"
3077 " on output %zu, bailing out", __func__, productStrategy,
3078 group, group, toString(attributes).c_str(),
3079 client->volumeSource(), toString(client->attributes()).c_str(), i);
3080 applyVolume = false;
3081 isPreempted = true;
3082 break;
3083 }
3084 // However, continue for loop to ensure no higher prio clients running on output
3085 if (client->volumeSource() == vs) {
3086 applyVolume = true;
3087 }
3088 }
3089 if (isPreempted || applyVolume) {
3090 break;
3091 }
3092 }
3093 if (!applyVolume) {
3094 continue; // next output
3095 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003096 }
François Gaffieed91f582020-01-31 10:35:37 +01003097 //FIXME: workaround for truncated touch sounds
3098 // delayed volume change for system stream to be removed when the problem is
3099 // handled by system UI
3100 status_t volStatus = checkAndSetVolume(
3101 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003102 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003103 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3104 if (volStatus != NO_ERROR) {
3105 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003106 }
3107 }
François Gaffiecfe17322018-11-07 13:41:29 +01003108 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3109 return status;
3110}
3111
François Gaffieaaac0fd2018-11-22 17:56:39 +01003112status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003113 audio_devices_t device,
3114 IVolumeCurves &volumeCurves)
3115{
3116 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3117 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003118 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3119 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003120 (index > volumeCurves.getVolumeIndexMax())) {
3121 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3122 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3123 return BAD_VALUE;
3124 }
3125 if (!audio_is_output_device(device)) {
3126 return BAD_VALUE;
3127 }
3128
3129 // Force max volume if stream cannot be muted
3130 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3131
François Gaffieaaac0fd2018-11-22 17:56:39 +01003132 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003133 volumeCurves.addCurrentVolumeIndex(device, index);
3134 return NO_ERROR;
3135}
3136
3137status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3138 int &index,
3139 audio_devices_t device)
3140{
3141 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3142 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003143 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003144 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003145 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3146 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003147 }
jiabin9a3361e2019-10-01 09:38:30 -07003148 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003149}
3150
3151status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3152 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003153 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003154{
jiabin9a3361e2019-10-01 09:38:30 -07003155 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003156 return BAD_VALUE;
3157 }
jiabin9a3361e2019-10-01 09:38:30 -07003158 index = curves.getVolumeIndex(deviceTypes);
3159 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003160 return NO_ERROR;
3161}
3162
3163status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3164 int &index)
3165{
3166 index = getVolumeCurves(attr).getVolumeIndexMin();
3167 return NO_ERROR;
3168}
3169
3170status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3171 int &index)
3172{
3173 index = getVolumeCurves(attr).getVolumeIndexMax();
3174 return NO_ERROR;
3175}
3176
Eric Laurent36829f92017-04-07 19:04:42 -07003177audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003178{
3179 // select one output among several suitable for global effects.
3180 // The priority is as follows:
3181 // 1: An offloaded output. If the effect ends up not being offloadable,
3182 // AudioFlinger will invalidate the track and the offloaded output
3183 // will be closed causing the effect to be moved to a PCM output.
3184 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003185 // 3: The primary output
3186 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003187
François Gaffiec005e562018-11-06 15:04:49 +01003188 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3189 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003190 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003191
Eric Laurent36829f92017-04-07 19:04:42 -07003192 if (outputs.size() == 0) {
3193 return AUDIO_IO_HANDLE_NONE;
3194 }
Eric Laurente552edb2014-03-10 17:42:56 -07003195
Eric Laurent36829f92017-04-07 19:04:42 -07003196 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3197 bool activeOnly = true;
3198
3199 while (output == AUDIO_IO_HANDLE_NONE) {
3200 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3201 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3202 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3203
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003204 for (audio_io_handle_t output : outputs) {
3205 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003206 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003207 continue;
3208 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003209 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3210 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003211 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003212 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003213 }
3214 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003215 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003216 }
3217 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003218 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003219 }
3220 }
3221 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3222 output = outputOffloaded;
3223 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3224 output = outputDeepBuffer;
3225 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3226 output = outputPrimary;
3227 } else {
3228 output = outputs[0];
3229 }
3230 activeOnly = false;
3231 }
3232
3233 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003234 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003235 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3236 mMusicEffectOutput = output;
3237 }
3238
3239 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003240 return output;
3241}
3242
Eric Laurent36829f92017-04-07 19:04:42 -07003243audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3244{
3245 return selectOutputForMusicEffects();
3246}
3247
Eric Laurente0720872014-03-11 09:30:41 -07003248status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003249 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003250 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003251 int session,
3252 int id)
3253{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003254 if (session != AUDIO_SESSION_DEVICE) {
3255 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003256 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003257 index = mInputs.indexOfKey(io);
3258 if (index < 0) {
3259 ALOGW("registerEffect() unknown io %d", io);
3260 return INVALID_OPERATION;
3261 }
Eric Laurente552edb2014-03-10 17:42:56 -07003262 }
3263 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003264 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3265 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3266 || strategy == PRODUCT_STRATEGY_NONE));
3267 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003268}
3269
Eric Laurentc241b0d2018-11-28 09:08:49 -08003270status_t AudioPolicyManager::unregisterEffect(int id)
3271{
3272 if (mEffects.getEffect(id) == nullptr) {
3273 return INVALID_OPERATION;
3274 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003275 if (mEffects.isEffectEnabled(id)) {
3276 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3277 setEffectEnabled(id, false);
3278 }
3279 return mEffects.unregisterEffect(id);
3280}
3281
3282status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3283{
3284 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3285 if (effect == nullptr) {
3286 return INVALID_OPERATION;
3287 }
3288
3289 status_t status = mEffects.setEffectEnabled(id, enabled);
3290 if (status == NO_ERROR) {
3291 mInputs.trackEffectEnabled(effect, enabled);
3292 }
3293 return status;
3294}
3295
Eric Laurent6c796322019-04-09 14:13:17 -07003296
3297status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3298{
3299 mEffects.moveEffects(ids, io);
3300 return NO_ERROR;
3301}
3302
Eric Laurentc75307b2015-03-17 15:29:32 -07003303bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3304{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003305 auto vs = toVolumeSource(stream, false);
3306 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003307}
3308
3309bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3310{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003311 auto vs = toVolumeSource(stream, false);
3312 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003313}
3314
Eric Laurente0720872014-03-11 09:30:41 -07003315bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003316{
3317 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003318 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003319 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003320 return true;
3321 }
3322 }
3323 return false;
3324}
3325
Eric Laurent275e8e92014-11-30 15:14:47 -08003326// Register a list of custom mixes with their attributes and format.
3327// When a mix is registered, corresponding input and output profiles are
3328// added to the remote submix hw module. The profile contains only the
3329// parameters (sampling rate, format...) specified by the mix.
3330// The corresponding input remote submix device is also connected.
3331//
3332// When a remote submix device is connected, the address is checked to select the
3333// appropriate profile and the corresponding input or output stream is opened.
3334//
3335// When capture starts, getInputForAttr() will:
3336// - 1 look for a mix matching the address passed in attribtutes tags if any
3337// - 2 if none found, getDeviceForInputSource() will:
3338// - 2.1 look for a mix matching the attributes source
3339// - 2.2 if none found, default to device selection by policy rules
3340// At this time, the corresponding output remote submix device is also connected
3341// and active playback use cases can be transferred to this mix if needed when reconnecting
3342// after AudioTracks are invalidated
3343//
3344// When playback starts, getOutputForAttr() will:
3345// - 1 look for a mix matching the address passed in attribtutes tags if any
3346// - 2 if none found, look for a mix matching the attributes usage
3347// - 3 if none found, default to device and output selection by policy rules.
3348
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003349status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003350{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003351 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3352 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003353 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003354 sp<HwModule> rSubmixModule;
3355 // examine each mix's route type
3356 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003357 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003358 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3359 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3360 ALOGE("Unsupported Policy Mix %zu of %zu: "
3361 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3362 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003363 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003364 break;
3365 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003366 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3367 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003368 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003369 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3370 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003371 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003372 rSubmixModule = mHwModules.getModuleFromName(
3373 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3374 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003375 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003376 i);
3377 res = INVALID_OPERATION;
3378 break;
3379 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003381
Eric Laurent97ac8712018-07-27 18:59:02 -07003382 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003383 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003384 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003385 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003386 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3387 } else {
3388 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3389 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003390 }
François Gaffie036e1e92015-03-19 10:16:24 +01003391
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003392 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003393 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003394 res = INVALID_OPERATION;
3395 break;
3396 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003397 audio_config_t outputConfig = mix.mFormat;
3398 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003399 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3400 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003401 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3402 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003403 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003404 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003405 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003406 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003407
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003408 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003409 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3410 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3411 ALOGE("Failed to set remote submix device available, type %u, address %s",
3412 mix.mDeviceType, address.string());
3413 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003414 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003415 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3416 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003417 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003418 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003419 i, mixes.size(), type, address.string());
3420
3421 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3422 mix.mDeviceType, mix.mDeviceAddress,
3423 String8(), AUDIO_FORMAT_DEFAULT);
3424 if (device == nullptr) {
3425 res = INVALID_OPERATION;
3426 break;
3427 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003428
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003429 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003430 // First try to find an already opened output supporting the device
3431 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003432 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003433
Eric Laurentc529cf62020-04-17 18:19:10 -07003434 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003435 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003436 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3437 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003438 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003439 } else {
3440 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003441 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003442 }
3443 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003444 // If no output found, try to find a direct output profile supporting the device
3445 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3446 sp<HwModule> module = mHwModules[i];
3447 for (size_t j = 0;
3448 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3449 j++) {
3450 sp<IOProfile> profile = module->getOutputProfiles()[j];
3451 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3452 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3453 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3454 address.string());
3455 res = INVALID_OPERATION;
3456 } else {
3457 foundOutput = true;
3458 }
3459 }
3460 }
3461 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003462 if (res != NO_ERROR) {
3463 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003464 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003465 res = INVALID_OPERATION;
3466 break;
3467 } else if (!foundOutput) {
3468 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003469 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003470 res = INVALID_OPERATION;
3471 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003472 } else {
3473 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003474 }
Eric Laurentc722f302014-12-10 11:21:49 -08003475 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003476 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003477 if (res != NO_ERROR) {
3478 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003479 } else if (checkOutputs) {
3480 checkForDeviceAndOutputChanges();
3481 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003482 }
3483 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003484}
3485
3486status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3487{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003488 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003489 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003490 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003491 sp<HwModule> rSubmixModule;
3492 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003493 for (const auto& mix : mixes) {
3494 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003495
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003496 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003497 rSubmixModule = mHwModules.getModuleFromName(
3498 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3499 if (rSubmixModule == 0) {
3500 res = INVALID_OPERATION;
3501 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003502 }
3503 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003504
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003505 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003506
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003507 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003508 res = INVALID_OPERATION;
3509 continue;
3510 }
3511
Kevin Rocard04ed0462019-05-02 17:53:24 -07003512 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3513 if (getDeviceConnectionState(device, address.string()) ==
3514 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3515 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3516 address.string(), "remote-submix",
3517 AUDIO_FORMAT_DEFAULT);
3518 if (res != OK) {
3519 ALOGE("Error making RemoteSubmix device unavailable for mix "
3520 "with type %d, address %s", device, address.string());
3521 }
3522 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003523 }
jiabin5740f082019-08-19 15:08:30 -07003524 rSubmixModule->removeOutputProfile(address.c_str());
3525 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003526
Kevin Rocard153f92d2018-12-18 18:33:28 -08003527 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003528 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003529 res = INVALID_OPERATION;
3530 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003531 } else {
3532 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003533 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003534 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003535 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003536 if (res == NO_ERROR && checkOutputs) {
3537 checkForDeviceAndOutputChanges();
3538 updateCallAndOutputRouting();
3539 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003540 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003541}
3542
Mikhail Naganov100f0122018-11-29 11:22:16 -08003543void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3544{
3545 size_t i = 0;
3546 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3547 for (const auto& fmt : mManualSurroundFormats) {
3548 if (i++ != 0) dst->append(", ");
3549 std::string sfmt;
3550 FormatConverter::toString(fmt, sfmt);
3551 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3552 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3553 }
3554}
3555
Eric Laurentc529cf62020-04-17 18:19:10 -07003556// Returns true if all devices types match the predicate and are supported by one HW module
3557bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003558 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003559 std::function<bool(audio_devices_t)> predicate,
3560 const char *context) {
3561 for (size_t i = 0; i < devices.size(); i++) {
3562 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003563 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003564 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003565 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003566 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003567 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003568 return false;
3569 }
3570 }
3571 return true;
3572}
3573
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003574status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003575 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003576 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003577 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3578 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003579 }
3580 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003581 if (res != NO_ERROR) {
3582 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3583 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003584 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003585
3586 checkForDeviceAndOutputChanges();
3587 updateCallAndOutputRouting();
3588
3589 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003590}
3591
3592status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3593 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003594 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3595 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003596 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003597 __FUNCTION__, uid);
3598 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003599 }
3600
Eric Laurentc529cf62020-04-17 18:19:10 -07003601 checkForDeviceAndOutputChanges();
3602 updateCallAndOutputRouting();
3603
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003604 return res;
3605}
3606
Eric Laurent2517af32020-11-25 15:31:27 +01003607
jiabin0a488932020-08-07 17:32:40 -07003608status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3609 device_role_t role,
3610 const AudioDeviceTypeAddrVector &devices) {
3611 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3612 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003613
Eric Laurentc529cf62020-04-17 18:19:10 -07003614 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003615 return BAD_VALUE;
3616 }
jiabin0a488932020-08-07 17:32:40 -07003617 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003618 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003619 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3620 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003621 return status;
3622 }
3623
3624 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003625
3626 bool forceVolumeReeval = false;
3627 // FIXME: workaround for truncated touch sounds
3628 // to be removed when the problem is handled by system UI
3629 uint32_t delayMs = 0;
3630 if (strategy == mCommunnicationStrategy) {
3631 forceVolumeReeval = true;
3632 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3633 updateInputRouting();
3634 }
3635 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003636
3637 return NO_ERROR;
3638}
3639
3640void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3641{
3642 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003643 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003644 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003645 // Only apply special touch sound delay once
3646 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003647 }
3648 for (size_t i = 0; i < mOutputs.size(); i++) {
3649 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3650 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003651 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3652 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003653 // As done in setDeviceConnectionState, we could also fix default device issue by
3654 // preventing the force re-routing in case of default dev that distinguishes on address.
3655 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003656 bool forceRouting = !newDevices.isEmpty();
3657 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3658 true /*requiresMuteCheck*/,
3659 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003660 // Only apply special touch sound delay once
3661 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003662 }
3663 if (forceVolumeReeval && !newDevices.isEmpty()) {
3664 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3665 }
3666 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003667 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003668}
3669
Eric Laurent2517af32020-11-25 15:31:27 +01003670void AudioPolicyManager::updateInputRouting() {
3671 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303672 // Skip for hotword recording as the input device switch
3673 // is handled within sound trigger HAL
3674 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3675 continue;
3676 }
Eric Laurent2517af32020-11-25 15:31:27 +01003677 auto newDevice = getNewInputDevice(activeDesc);
3678 // Force new input selection if the new device can not be reached via current input
3679 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3680 setInputDevice(activeDesc->mIoHandle, newDevice);
3681 } else {
3682 closeInput(activeDesc->mIoHandle);
3683 }
3684 }
3685}
3686
jiabin0a488932020-08-07 17:32:40 -07003687status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3688 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003689{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003690 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003691
jiabin0a488932020-08-07 17:32:40 -07003692 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003693 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003694 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3695 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003696 return status;
3697 }
3698
3699 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003700
3701 bool forceVolumeReeval = false;
3702 // FIXME: workaround for truncated touch sounds
3703 // to be removed when the problem is handled by system UI
3704 uint32_t delayMs = 0;
3705 if (strategy == mCommunnicationStrategy) {
3706 forceVolumeReeval = true;
3707 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3708 updateInputRouting();
3709 }
3710 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003711
3712 return NO_ERROR;
3713}
3714
jiabin0a488932020-08-07 17:32:40 -07003715status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3716 device_role_t role,
3717 AudioDeviceTypeAddrVector &devices) {
3718 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003719}
3720
Jiabin Huang3b98d322020-09-03 17:54:16 +00003721status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3722 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3723 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3724 dumpAudioDeviceTypeAddrVector(devices).c_str());
3725
Mikhail Naganov55773032020-10-01 15:08:13 -07003726 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003727 return BAD_VALUE;
3728 }
3729 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3730 ALOGW_IF(status != NO_ERROR,
3731 "Engine could not set preferred devices %s for audio source %d role %d",
3732 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3733
3734 return status;
3735}
3736
3737status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3738 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3739 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3740 dumpAudioDeviceTypeAddrVector(devices).c_str());
3741
Mikhail Naganov55773032020-10-01 15:08:13 -07003742 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003743 return BAD_VALUE;
3744 }
3745 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3746 ALOGW_IF(status != NO_ERROR,
3747 "Engine could not add preferred devices %s for audio source %d role %d",
3748 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3749
Eric Laurent2517af32020-11-25 15:31:27 +01003750 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003751 return status;
3752}
3753
3754status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3755 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3756{
3757 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3758 dumpAudioDeviceTypeAddrVector(devices).c_str());
3759
Mikhail Naganov55773032020-10-01 15:08:13 -07003760 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003761 return BAD_VALUE;
3762 }
3763
3764 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3765 audioSource, role, devices);
3766 ALOGW_IF(status != NO_ERROR,
3767 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3768
Eric Laurent2517af32020-11-25 15:31:27 +01003769 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003770 return status;
3771}
3772
3773status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3774 device_role_t role) {
3775 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3776
3777 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3778 ALOGW_IF(status != NO_ERROR,
3779 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3780
Eric Laurent2517af32020-11-25 15:31:27 +01003781 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003782 return status;
3783}
3784
3785status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3786 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3787 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3788}
3789
Oscar Azucena90e77632019-11-27 17:12:28 -08003790status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003791 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003792 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003793 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3794 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003795 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003796 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3797 if (status != NO_ERROR) {
3798 ALOGE("%s() could not set device affinity for userId %d",
3799 __FUNCTION__, userId);
3800 return status;
3801 }
3802
3803 // reevaluate outputs for all devices
3804 checkForDeviceAndOutputChanges();
3805 updateCallAndOutputRouting();
3806
3807 return NO_ERROR;
3808}
3809
3810status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003811 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003812 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3813 if (status != NO_ERROR) {
3814 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3815 __FUNCTION__, userId);
3816 return status;
3817 }
3818
3819 // reevaluate outputs for all devices
3820 checkForDeviceAndOutputChanges();
3821 updateCallAndOutputRouting();
3822
3823 return NO_ERROR;
3824}
3825
Andy Hungc29d82b2018-10-05 12:23:17 -07003826void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003827{
Andy Hungc29d82b2018-10-05 12:23:17 -07003828 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003829 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003830 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003831 std::string stateLiteral;
3832 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003833 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003834 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3835 "communications", "media", "record", "dock", "system",
3836 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3837 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3838 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003839 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3840 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3841 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3842 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3843 dst->append(" (MANUAL: ");
3844 dumpManualSurroundFormats(dst);
3845 dst->append(")");
3846 }
3847 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003848 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003849 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3850 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003851 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003852 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003853
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003854 dst->append("\n");
3855 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3856 dst->append("\n");
3857 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003858 mHwModulesAll.dump(dst);
3859 mOutputs.dump(dst);
3860 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003861 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003862 mAudioPatches.dump(dst);
3863 mPolicyMixes.dump(dst);
3864 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003865
Kevin Rocardb99cc752019-03-21 20:52:24 -07003866 dst->appendFormat(" AllowedCapturePolicies:\n");
3867 for (auto& policy : mAllowedCapturePolicies) {
3868 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3869 }
3870
François Gaffiec005e562018-11-06 15:04:49 +01003871 dst->appendFormat("\nPolicy Engine dump:\n");
3872 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003873}
3874
3875status_t AudioPolicyManager::dump(int fd)
3876{
3877 String8 result;
3878 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003879 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003880 return NO_ERROR;
3881}
3882
Kevin Rocardb99cc752019-03-21 20:52:24 -07003883status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3884{
3885 mAllowedCapturePolicies[uid] = capturePolicy;
3886 return NO_ERROR;
3887}
3888
Eric Laurente552edb2014-03-10 17:42:56 -07003889// This function checks for the parameters which can be offloaded.
3890// This can be enhanced depending on the capability of the DSP and policy
3891// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003892audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003893{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003894 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003895 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003896 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003897 offloadInfo.format,
3898 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3899 offloadInfo.has_video);
3900
jiabin2b9d5a12021-12-10 01:06:29 +00003901 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003902 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003903 }
3904
3905 // See if there is a profile to support this.
3906 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003907 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003908 offloadInfo.sample_rate,
3909 offloadInfo.format,
3910 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003911 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3912 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003913 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3914 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3915 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003916 if (profile == nullptr) {
3917 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3918 }
3919 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3920 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3921 }
3922 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003923}
3924
Michael Chana94fbb22018-04-24 14:31:19 +10003925bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3926 const audio_attributes_t& attributes) {
3927 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003928 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003929 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3930 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003931 config.sample_rate,
3932 config.format,
3933 config.channel_mask,
3934 output_flags,
3935 true /* directOnly */);
3936 ALOGV("%s() profile %sfound with name: %s, "
3937 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3938 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003939 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003940 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003941
3942 // also try the MSD module if compatible profile not found
3943 if (profile == nullptr) {
3944 profile = getMsdProfileForOutput(outputDevices,
3945 config.sample_rate,
3946 config.format,
3947 config.channel_mask,
3948 output_flags,
3949 true /* directOnly */);
3950 ALOGV("%s() MSD profile %sfound with name: %s, "
3951 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3952 __FUNCTION__, profile != 0 ? "" : "NOT ",
3953 (profile != 0 ? profile->getTagName().c_str() : "null"),
3954 config.sample_rate, config.format, config.channel_mask, output_flags);
3955 }
3956 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003957}
3958
jiabin2b9d5a12021-12-10 01:06:29 +00003959bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3960 bool durationIgnored) {
3961 if (mMasterMono) {
3962 return false; // no offloading if mono is set.
3963 }
3964
3965 // Check if offload has been disabled
3966 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3967 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3968 return false;
3969 }
3970
3971 // Check if stream type is music, then only allow offload as of now.
3972 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3973 {
3974 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3975 return false;
3976 }
3977
3978 //TODO: enable audio offloading with video when ready
3979 const bool allowOffloadWithVideo =
3980 property_get_bool("audio.offload.video", false /* default_value */);
3981 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3982 ALOGV("%s: has_video == true, returning false", __func__);
3983 return false;
3984 }
3985
3986 //If duration is less than minimum value defined in property, return false
3987 const int min_duration_secs = property_get_int32(
3988 "audio.offload.min.duration.secs", -1 /* default_value */);
3989 if (!durationIgnored) {
3990 if (min_duration_secs >= 0) {
3991 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3992 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3993 __func__, min_duration_secs);
3994 return false;
3995 }
3996 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3997 ALOGV("%s: Offload denied by duration < default min(=%u)",
3998 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3999 return false;
4000 }
4001 }
4002
4003 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4004 // creating an offloaded track and tearing it down immediately after start when audioflinger
4005 // detects there is an active non offloadable effect.
4006 // FIXME: We should check the audio session here but we do not have it in this context.
4007 // This may prevent offloading in rare situations where effects are left active by apps
4008 // in the background.
4009 if (mEffects.isNonOffloadableEffectEnabled()) {
4010 return false;
4011 }
4012
4013 return true;
4014}
4015
4016audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4017 const audio_config_t *config) {
4018 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4019 offloadInfo.format = config->format;
4020 offloadInfo.sample_rate = config->sample_rate;
4021 offloadInfo.channel_mask = config->channel_mask;
4022 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4023 offloadInfo.has_video = false;
4024 offloadInfo.is_streaming = false;
4025 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4026
4027 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4028 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4029 audio_flags_to_audio_output_flags(attr->flags, &flags);
4030 // only retain flags that will drive compressed offload or passthrough
4031 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4032 if (offloadPossible) {
4033 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4034 }
4035 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4036
Dorin Drimusfae3c642022-03-17 18:36:30 +01004037 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004038 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004039 DeviceVector outputDevices = engineOutputDevices;
4040 // the MSD module checks for different conditions and output devices
4041 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4042 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4043 continue;
4044 }
4045 outputDevices = getMsdAudioOutDevices();
4046 }
jiabin2b9d5a12021-12-10 01:06:29 +00004047 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004048 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004049 config->sample_rate, nullptr /*updatedSamplingRate*/,
4050 config->format, nullptr /*updatedFormat*/,
4051 config->channel_mask, nullptr /*updatedChannelMask*/,
4052 flags)) {
4053 continue;
4054 }
4055 // reject profiles not corresponding to a device currently available
4056 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4057 continue;
4058 }
4059 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4060 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004061 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004062 != AUDIO_DIRECT_NOT_SUPPORTED) {
4063 // Already reports offload gapless supported. No need to report offload support.
4064 continue;
4065 }
4066 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4067 != AUDIO_OUTPUT_FLAG_NONE) {
4068 // If offload gapless is reported, no need to report offload support.
4069 directMode = (audio_direct_mode_t) ((directMode &
4070 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4071 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4072 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004073 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004074 }
4075 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004076 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004077 }
4078 }
4079 }
4080 return directMode;
4081}
4082
Dorin Drimusf2196d82022-01-03 12:11:18 +01004083status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4084 AudioProfileVector& audioProfilesVector) {
4085 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004086 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004087 if (status != OK) {
4088 return status;
4089 }
4090 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4091 if (devices.empty()) {
4092 return OK; // no output devices for the attributes
4093 }
4094
4095 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004096 // the MSD module checks for different conditions
4097 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4098 continue;
4099 }
4100 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4101 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004102 continue;
4103 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004104 // allow only profiles that support all the available and routed devices
4105 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004106 != devices.size()) {
4107 continue;
4108 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004109 audioProfilesVector.addAllValidProfiles(
4110 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004111 }
4112 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004113
4114 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4115 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4116 if (msdModule != nullptr) {
4117 if (msdHasPatchesToAllDevices(devices)) {
4118 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4119 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4120 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4121 continue;
4122 }
4123 audioProfilesVector.addAllValidProfiles(
4124 outputProfile->asAudioPort()->getAudioProfiles());
4125 }
4126 } else {
4127 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4128 }
4129 }
4130
Dorin Drimusf2196d82022-01-03 12:11:18 +01004131 return NO_ERROR;
4132}
4133
Eric Laurent6a94d692014-05-20 11:18:06 -07004134status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4135 audio_port_type_t type,
4136 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004137 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004138 unsigned int *generation)
4139{
jiabin19cdba52020-11-24 11:28:58 -08004140 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4141 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004142 return BAD_VALUE;
4143 }
4144 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004145 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004146 *num_ports = 0;
4147 }
4148
4149 size_t portsWritten = 0;
4150 size_t portsMax = *num_ports;
4151 *num_ports = 0;
4152 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004153 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4154 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004156 for (const auto& dev : mAvailableOutputDevices) {
4157 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004158 continue;
4159 }
4160 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004161 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004162 }
4163 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004164 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 }
4166 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004167 for (const auto& dev : mAvailableInputDevices) {
4168 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004169 continue;
4170 }
4171 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004172 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004173 }
4174 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004176 }
4177 }
4178 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4179 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4180 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4181 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4182 }
4183 *num_ports += mInputs.size();
4184 }
4185 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004186 size_t numOutputs = 0;
4187 for (size_t i = 0; i < mOutputs.size(); i++) {
4188 if (!mOutputs[i]->isDuplicated()) {
4189 numOutputs++;
4190 if (portsWritten < portsMax) {
4191 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4192 }
4193 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004194 }
Eric Laurent84c70242014-06-23 08:46:27 -07004195 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 }
4197 }
4198 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004199 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004200 return NO_ERROR;
4201}
4202
jiabin19cdba52020-11-24 11:28:58 -08004203status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004204{
Eric Laurent99fcae42018-05-17 16:59:18 -07004205 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4206 return BAD_VALUE;
4207 }
4208 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4209 if (dev != 0) {
4210 dev->toAudioPort(port);
4211 return NO_ERROR;
4212 }
4213 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4214 if (dev != 0) {
4215 dev->toAudioPort(port);
4216 return NO_ERROR;
4217 }
4218 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4219 if (out != 0) {
4220 out->toAudioPort(port);
4221 return NO_ERROR;
4222 }
4223 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4224 if (in != 0) {
4225 in->toAudioPort(port);
4226 return NO_ERROR;
4227 }
4228 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004229}
4230
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004231status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4232 audio_patch_handle_t *handle,
4233 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004234{
François Gaffieafd4cea2019-11-18 15:50:22 +01004235 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004236 if (handle == NULL || patch == NULL) {
4237 return BAD_VALUE;
4238 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004239 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004240 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004241 return BAD_VALUE;
4242 }
4243 // only one source per audio patch supported for now
4244 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004245 return INVALID_OPERATION;
4246 }
Eric Laurent874c42872014-08-08 15:13:39 -07004247 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004248 return INVALID_OPERATION;
4249 }
Eric Laurent874c42872014-08-08 15:13:39 -07004250 for (size_t i = 0; i < patch->num_sinks; i++) {
4251 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4252 return INVALID_OPERATION;
4253 }
4254 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004255
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004256 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4257 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4258 if (srcDevice == nullptr || sinkDevice == nullptr) {
4259 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4260 return BAD_VALUE;
4261 }
4262 ALOGV("%s between source %s and sink %s", __func__,
4263 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4264 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4265 // Default attributes, default volume priority, not to infer with non raw audio patches.
4266 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4267 const struct audio_port_config *source = &patch->sources[0];
4268 sp<SourceClientDescriptor> sourceDesc =
4269 new InternalSourceClientDescriptor(
4270 portId, uid, attributes, *source, srcDevice, sinkDevice,
4271 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4272
4273 status_t status =
4274 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4275
4276 if (status != NO_ERROR) {
4277 return INVALID_OPERATION;
4278 }
4279 mAudioSources.add(portId, sourceDesc);
4280 return NO_ERROR;
4281}
4282
4283status_t AudioPolicyManager::connectAudioSourceToSink(
4284 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4285 const struct audio_patch *patch,
4286 audio_patch_handle_t &handle,
4287 uid_t uid, uint32_t delayMs)
4288{
4289 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4290 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4291 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4292 return INVALID_OPERATION;
4293 }
4294 sourceDesc->connect(handle, sinkDevice);
4295 if (isMsdPatch(handle)) {
4296 return NO_ERROR;
4297 }
4298 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4299 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4300 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4301 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4302 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4303 goto FailurePatchAdded;
4304 }
4305 status = swOutput->start();
4306 if (status != NO_ERROR) {
4307 goto FailureSourceAdded;
4308 }
4309 swOutput->addClient(sourceDesc);
4310 status = startSource(swOutput, sourceDesc, &delayMs);
4311 if (status != NO_ERROR) {
4312 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4313 goto FailureSourceActive;
4314 }
4315 if (delayMs != 0) {
4316 usleep(delayMs * 1000);
4317 }
4318 return NO_ERROR;
4319
4320FailureSourceActive:
4321 swOutput->stop();
4322 releaseOutput(sourceDesc->portId());
4323FailureSourceAdded:
4324 sourceDesc->setSwOutput(nullptr);
4325FailurePatchAdded:
4326 releaseAudioPatchInternal(handle);
4327 return INVALID_OPERATION;
4328}
4329
4330status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4331 audio_patch_handle_t *handle,
4332 uid_t uid, uint32_t delayMs,
4333 const sp<SourceClientDescriptor>& sourceDesc)
4334{
4335 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004336 sp<AudioPatch> patchDesc;
4337 ssize_t index = mAudioPatches.indexOfKey(*handle);
4338
François Gaffieafd4cea2019-11-18 15:50:22 +01004339 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4340 patch->sources[0].role,
4341 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004342#if LOG_NDEBUG == 0
4343 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004344 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4345 patch->sinks[i].role,
4346 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004347 }
4348#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004349
4350 if (index >= 0) {
4351 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004352 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4353 __func__, mUidCached, patchDesc->getUid(), uid);
4354 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004355 return INVALID_OPERATION;
4356 }
4357 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004358 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004359 }
4360
4361 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004362 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004363 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004364 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004365 return BAD_VALUE;
4366 }
Eric Laurent84c70242014-06-23 08:46:27 -07004367 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4368 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004369 if (patchDesc != 0) {
4370 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004371 ALOGV("%s source id differs for patch current id %d new id %d",
4372 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 return BAD_VALUE;
4374 }
4375 }
Eric Laurent874c42872014-08-08 15:13:39 -07004376 DeviceVector devices;
4377 for (size_t i = 0; i < patch->num_sinks; i++) {
4378 // Only support mix to devices connection
4379 // TODO add support for mix to mix connection
4380 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004381 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004382 return INVALID_OPERATION;
4383 }
4384 sp<DeviceDescriptor> devDesc =
4385 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4386 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004387 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004388 return BAD_VALUE;
4389 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004390
François Gaffie11d30102018-11-02 16:09:09 +01004391 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004392 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004393 NULL, // updatedSamplingRate
4394 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004395 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004396 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004397 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004398 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004399 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004400 return INVALID_OPERATION;
4401 }
4402 devices.add(devDesc);
4403 }
4404 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 return INVALID_OPERATION;
4406 }
Eric Laurent874c42872014-08-08 15:13:39 -07004407
Eric Laurent6a94d692014-05-20 11:18:06 -07004408 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004409 ALOGV("%s setting device %s on output %d",
4410 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004411 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004412 index = mAudioPatches.indexOfKey(*handle);
4413 if (index >= 0) {
4414 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004415 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004416 }
4417 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004418 patchDesc->setUid(uid);
4419 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004420 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004421 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 return INVALID_OPERATION;
4423 }
4424 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4425 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4426 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004427 // only one sink supported when connecting an input device to a mix
4428 if (patch->num_sinks > 1) {
4429 return INVALID_OPERATION;
4430 }
François Gaffie53615e22015-03-19 09:24:12 +01004431 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 if (inputDesc == NULL) {
4433 return BAD_VALUE;
4434 }
4435 if (patchDesc != 0) {
4436 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4437 return BAD_VALUE;
4438 }
4439 }
François Gaffie11d30102018-11-02 16:09:09 +01004440 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004442 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004443 return BAD_VALUE;
4444 }
4445
François Gaffie11d30102018-11-02 16:09:09 +01004446 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004447 patch->sinks[0].sample_rate,
4448 NULL, /*updatedSampleRate*/
4449 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004450 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004451 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004452 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004453 // FIXME for the parameter type,
4454 // and the NONE
4455 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004456 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 return INVALID_OPERATION;
4458 }
4459 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004460 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004461 device->toString().c_str(), inputDesc->mIoHandle);
4462 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004463 index = mAudioPatches.indexOfKey(*handle);
4464 if (index >= 0) {
4465 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004466 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004467 }
4468 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004469 patchDesc->setUid(uid);
4470 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004471 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004472 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004473 return INVALID_OPERATION;
4474 }
4475 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4476 // device to device connection
4477 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004478 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004479 return BAD_VALUE;
4480 }
4481 }
François Gaffie11d30102018-11-02 16:09:09 +01004482 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004484 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004485 return BAD_VALUE;
4486 }
Eric Laurent874c42872014-08-08 15:13:39 -07004487
Eric Laurent6a94d692014-05-20 11:18:06 -07004488 //update source and sink with our own data as the data passed in the patch may
4489 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004490 PatchBuilder patchBuilder;
4491 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004492
4493 // if first sink is to MSD, establish single MSD patch
4494 if (getMsdAudioOutDevices().contains(
4495 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4496 ALOGV("%s patching to MSD", __FUNCTION__);
4497 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4498 goto installPatch;
4499 }
4500
François Gaffieafd4cea2019-11-18 15:50:22 +01004501 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4502 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004503
Eric Laurent874c42872014-08-08 15:13:39 -07004504 for (size_t i = 0; i < patch->num_sinks; i++) {
4505 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004506 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004507 return INVALID_OPERATION;
4508 }
François Gaffie11d30102018-11-02 16:09:09 +01004509 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004510 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004511 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004512 return BAD_VALUE;
4513 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004514 audio_port_config sinkPortConfig = {};
4515 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4516 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004517
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004518 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4519 // volume management purpose (tracking activity)
4520 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4521 // in config XML to reach the sink so that is can be declared as available.
4522 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4523 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004524 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004525 // take care of dynamic routing for SwOutput selection,
4526 audio_attributes_t attributes = sourceDesc->attributes();
4527 audio_stream_type_t stream = sourceDesc->stream();
4528 audio_attributes_t resultAttr;
4529 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4530 config.sample_rate = sourceDesc->config().sample_rate;
4531 config.channel_mask = sourceDesc->config().channel_mask;
4532 config.format = sourceDesc->config().format;
4533 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4534 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4535 bool isRequestedDeviceForExclusiveUse = false;
4536 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004537 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004538 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4539 &stream, sourceDesc->uid(), &config, &flags,
4540 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004541 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004542 if (output == AUDIO_IO_HANDLE_NONE) {
4543 ALOGV("%s no output for device %s",
4544 __FUNCTION__, sinkDevice->toString().c_str());
4545 return INVALID_OPERATION;
4546 }
4547 outputDesc = mOutputs.valueFor(output);
4548 if (outputDesc->isDuplicated()) {
4549 ALOGE("%s output is duplicated", __func__);
4550 return INVALID_OPERATION;
4551 }
4552 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004553 } else {
4554 // Same for "raw patches" aka created from createAudioPatch API
4555 SortedVector<audio_io_handle_t> outputs =
4556 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4557 // if the sink device is reachable via an opened output stream, request to
4558 // go via this output stream by adding a second source to the patch
4559 // description
4560 output = selectOutput(outputs);
4561 if (output == AUDIO_IO_HANDLE_NONE) {
4562 ALOGE("%s no output available for internal patch sink", __func__);
4563 return INVALID_OPERATION;
4564 }
4565 outputDesc = mOutputs.valueFor(output);
4566 if (outputDesc->isDuplicated()) {
4567 ALOGV("%s output for device %s is duplicated",
4568 __func__, sinkDevice->toString().c_str());
4569 return INVALID_OPERATION;
4570 }
4571 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004572 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004573 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004574 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004575 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004576 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004577 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4578 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004579 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4580 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004581 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004582 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004583 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004584 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004585 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004586 return INVALID_OPERATION;
4587 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004588 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004589 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004590 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004591 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004592 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004593 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4594 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4595 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004596 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004597 }
Eric Laurent83b88082014-06-20 18:31:16 -07004598 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004599 }
4600 // TODO: check from routing capabilities in config file and other conflicting patches
4601
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004602installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004603 status_t status = installPatch(
4604 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004605 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004606 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 return INVALID_OPERATION;
4608 }
4609 } else {
4610 return BAD_VALUE;
4611 }
4612 } else {
4613 return BAD_VALUE;
4614 }
4615 return NO_ERROR;
4616}
4617
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004618status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004619{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004620 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004621 ssize_t index = mAudioPatches.indexOfKey(handle);
4622
4623 if (index < 0) {
4624 return BAD_VALUE;
4625 }
4626 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004627 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4628 __func__, mUidCached, patchDesc->getUid(), uid);
4629 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004630 return INVALID_OPERATION;
4631 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004632 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4633 for (size_t i = 0; i < mAudioSources.size(); i++) {
4634 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4635 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4636 portId = sourceDesc->portId();
4637 break;
4638 }
4639 }
4640 return portId != AUDIO_PORT_HANDLE_NONE ?
4641 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004642}
Eric Laurent6a94d692014-05-20 11:18:06 -07004643
François Gaffieafd4cea2019-11-18 15:50:22 +01004644status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004645 uint32_t delayMs,
4646 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004647{
4648 ALOGV("%s patch %d", __func__, handle);
4649 if (mAudioPatches.indexOfKey(handle) < 0) {
4650 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4651 return BAD_VALUE;
4652 }
4653 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004654 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004655 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004656 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004657 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004658 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004659 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 return BAD_VALUE;
4661 }
4662
François Gaffie11d30102018-11-02 16:09:09 +01004663 setOutputDevices(outputDesc,
4664 getNewOutputDevices(outputDesc, true /*fromCache*/),
4665 true,
4666 0,
4667 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4669 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004670 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004672 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 return BAD_VALUE;
4674 }
4675 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004676 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004677 true,
4678 NULL);
4679 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004680 status_t status =
4681 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4682 ALOGV("%s patch panel returned %d patchHandle %d",
4683 __func__, status, patchDesc->getAfHandle());
4684 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004686 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004687 // SW or HW Bridge
4688 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4689 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004690 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004691 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4692 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4693 outputDesc = sourceDesc->swOutput().promote();
4694 }
4695 if (outputDesc == nullptr) {
4696 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4697 // releaseOutput has already called closeOutput in case of direct output
4698 return NO_ERROR;
4699 }
4700 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4701 resetOutputDevice(outputDesc);
4702 } else {
4703 // Reuse patch handle if still valid / do not force rerouting if still routed
4704 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004705 setOutputDevices(outputDesc,
4706 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004707 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004708 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004709 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004710 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004711 } else {
4712 return BAD_VALUE;
4713 }
4714 } else {
4715 return BAD_VALUE;
4716 }
4717 return NO_ERROR;
4718}
4719
4720status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4721 struct audio_patch *patches,
4722 unsigned int *generation)
4723{
François Gaffie53615e22015-03-19 09:24:12 +01004724 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 return BAD_VALUE;
4726 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004727 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004728 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004729}
4730
Eric Laurente1715a42014-05-20 11:30:42 -07004731status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004732{
Eric Laurente1715a42014-05-20 11:30:42 -07004733 ALOGV("setAudioPortConfig()");
4734
4735 if (config == NULL) {
4736 return BAD_VALUE;
4737 }
4738 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4739 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004740 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4741 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004742 }
4743
Eric Laurenta121f902014-06-03 13:32:54 -07004744 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004745 if (config->type == AUDIO_PORT_TYPE_MIX) {
4746 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004747 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004748 if (outputDesc == NULL) {
4749 return BAD_VALUE;
4750 }
Eric Laurent84c70242014-06-23 08:46:27 -07004751 ALOG_ASSERT(!outputDesc->isDuplicated(),
4752 "setAudioPortConfig() called on duplicated output %d",
4753 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004754 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004755 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004756 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004757 if (inputDesc == NULL) {
4758 return BAD_VALUE;
4759 }
Eric Laurenta121f902014-06-03 13:32:54 -07004760 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004761 } else {
4762 return BAD_VALUE;
4763 }
4764 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4765 sp<DeviceDescriptor> deviceDesc;
4766 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4767 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4768 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4769 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4770 } else {
4771 return BAD_VALUE;
4772 }
4773 if (deviceDesc == NULL) {
4774 return BAD_VALUE;
4775 }
Eric Laurenta121f902014-06-03 13:32:54 -07004776 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004777 } else {
4778 return BAD_VALUE;
4779 }
4780
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004781 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004782 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4783 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004784 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004785 audioPortConfig->toAudioPortConfig(&newConfig, config);
4786 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004787 }
Eric Laurenta121f902014-06-03 13:32:54 -07004788 if (status != NO_ERROR) {
4789 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004790 }
Eric Laurente1715a42014-05-20 11:30:42 -07004791
4792 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004793}
4794
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004795void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4796{
Eric Laurentd60560a2015-04-10 11:31:20 -07004797 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004798 clearAudioPatches(uid);
4799 clearSessionRoutes(uid);
4800}
4801
Eric Laurent6a94d692014-05-20 11:18:06 -07004802void AudioPolicyManager::clearAudioPatches(uid_t uid)
4803{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004804 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004805 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004806 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004807 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004808 }
4809 }
4810}
4811
François Gaffiec005e562018-11-06 15:04:49 +01004812void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004813{
François Gaffiec005e562018-11-06 15:04:49 +01004814 // Take the first attributes following the product strategy as it is used to retrieve the routed
4815 // device. All attributes wihin a strategy follows the same "routing strategy"
4816 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4817 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004818 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004819 for (size_t j = 0; j < mOutputs.size(); j++) {
4820 if (mOutputs.keyAt(j) == ouptutToSkip) {
4821 continue;
4822 }
4823 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004824 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004825 continue;
4826 }
4827 // If the default device for this strategy is on another output mix,
4828 // invalidate all tracks in this strategy to force re connection.
4829 // Otherwise select new device on the output mix.
4830 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004831 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4832 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004833 }
4834 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004835 setOutputDevices(
4836 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004837 }
4838 }
4839}
4840
4841void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4842{
4843 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004844 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004845 for (size_t i = 0; i < mOutputs.size(); i++) {
4846 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004847 for (const auto& client : outputDesc->getClientIterable()) {
4848 if (client->hasPreferredDevice() && client->uid() == uid) {
4849 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004850 auto clientStrategy = client->strategy();
4851 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4852 end(affectedStrategies)) {
4853 continue;
4854 }
4855 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004856 }
4857 }
4858 }
4859 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004860 for (const auto& strategy : affectedStrategies) {
4861 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004862 }
4863
4864 // remove input routes associated with this uid
4865 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004866 for (size_t i = 0; i < mInputs.size(); i++) {
4867 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004868 for (const auto& client : inputDesc->getClientIterable()) {
4869 if (client->hasPreferredDevice() && client->uid() == uid) {
4870 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4871 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004872 }
4873 }
4874 }
4875 // reroute inputs if necessary
4876 SortedVector<audio_io_handle_t> inputsToClose;
4877 for (size_t i = 0; i < mInputs.size(); i++) {
4878 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004879 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004880 inputsToClose.add(inputDesc->mIoHandle);
4881 }
4882 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004883 for (const auto& input : inputsToClose) {
4884 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004885 }
4886}
4887
Eric Laurentd60560a2015-04-10 11:31:20 -07004888void AudioPolicyManager::clearAudioSources(uid_t uid)
4889{
4890 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004891 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4892 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004893 stopAudioSource(mAudioSources.keyAt(i));
4894 }
4895 }
4896}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004897
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004898status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4899 audio_io_handle_t *ioHandle,
4900 audio_devices_t *device)
4901{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004902 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4903 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004904 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004905 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004906
François Gaffiedf372692015-03-19 10:43:27 +01004907 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004908}
4909
Eric Laurentd60560a2015-04-10 11:31:20 -07004910status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004911 const audio_attributes_t *attributes,
4912 audio_port_handle_t *portId,
4913 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004914{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004915 ALOGV("%s", __FUNCTION__);
4916 *portId = AUDIO_PORT_HANDLE_NONE;
4917
4918 if (source == NULL || attributes == NULL || portId == NULL) {
4919 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4920 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004921 return BAD_VALUE;
4922 }
4923
Eric Laurentd60560a2015-04-10 11:31:20 -07004924 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4925 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004926 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4927 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004928 return INVALID_OPERATION;
4929 }
4930
François Gaffie11d30102018-11-02 16:09:09 +01004931 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004932 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004933 String8(source->ext.device.address),
4934 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004935 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004936 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004937 return BAD_VALUE;
4938 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004939
jiabin4ef93452019-09-10 14:29:54 -07004940 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004941
François Gaffieaaac0fd2018-11-22 17:56:39 +01004942 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004943 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004944 mEngine->getStreamTypeForAttributes(*attributes),
4945 mEngine->getProductStrategyForAttributes(*attributes),
4946 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004947
4948 status_t status = connectAudioSource(sourceDesc);
4949 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004950 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004951 }
4952 return status;
4953}
4954
Francois Gaffie601801d2021-06-22 13:27:39 +02004955sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4956 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4957{
4958 ALOGV("%s", __FUNCTION__);
4959 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4960
4961 status_t status = startAudioSource(source, attributes, &portId, uid);
4962 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4963 return mAudioSources.valueFor(portId);
4964}
4965
4966
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004967status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004968{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004969 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004970
4971 // make sure we only have one patch per source.
4972 disconnectAudioSource(sourceDesc);
4973
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004974 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004975 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4976 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4977 sourceDesc->srcDevice()->type(),
4978 String8(sourceDesc->srcDevice()->address().c_str()),
4979 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004980 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004981 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004982 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004983 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004984 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4985 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4986 return INVALID_OPERATION;
4987 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004988 PatchBuilder patchBuilder;
4989 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4990 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004991
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004992 return connectAudioSourceToSink(
4993 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004994}
4995
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004996status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004997{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004998 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4999 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005000 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005001 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005002 return BAD_VALUE;
5003 }
5004 status_t status = disconnectAudioSource(sourceDesc);
5005
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005006 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005007 return status;
5008}
5009
Andy Hung2ddee192015-12-18 17:34:44 -08005010status_t AudioPolicyManager::setMasterMono(bool mono)
5011{
5012 if (mMasterMono == mono) {
5013 return NO_ERROR;
5014 }
5015 mMasterMono = mono;
5016 // if enabling mono we close all offloaded devices, which will invalidate the
5017 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5018 // for recreating the new AudioTrack as non-offloaded PCM.
5019 //
5020 // If disabling mono, we leave all tracks as is: we don't know which clients
5021 // and tracks are able to be recreated as offloaded. The next "song" should
5022 // play back offloaded.
5023 if (mMasterMono) {
5024 Vector<audio_io_handle_t> offloaded;
5025 for (size_t i = 0; i < mOutputs.size(); ++i) {
5026 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5027 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5028 offloaded.push(desc->mIoHandle);
5029 }
5030 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005031 for (const auto& handle : offloaded) {
5032 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005033 }
5034 }
5035 // update master mono for all remaining outputs
5036 for (size_t i = 0; i < mOutputs.size(); ++i) {
5037 updateMono(mOutputs.keyAt(i));
5038 }
5039 return NO_ERROR;
5040}
5041
5042status_t AudioPolicyManager::getMasterMono(bool *mono)
5043{
5044 *mono = mMasterMono;
5045 return NO_ERROR;
5046}
5047
Eric Laurentac9cef52017-06-09 15:46:26 -07005048float AudioPolicyManager::getStreamVolumeDB(
5049 audio_stream_type_t stream, int index, audio_devices_t device)
5050{
jiabin9a3361e2019-10-01 09:38:30 -07005051 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005052}
5053
jiabin81772902018-04-02 17:52:27 -07005054status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5055 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005056 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005057{
Kriti Dang6537def2021-03-02 13:46:59 +01005058 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5059 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005060 return BAD_VALUE;
5061 }
Kriti Dang6537def2021-03-02 13:46:59 +01005062 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5063 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005064
5065 size_t formatsWritten = 0;
5066 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005067
Kriti Dang6537def2021-03-02 13:46:59 +01005068 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005069 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5070 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005071 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005072 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005073 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005074 bool formatEnabled = true;
5075 switch (forceUse) {
5076 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005077 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005078 break;
5079 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5080 formatEnabled = false;
5081 break;
5082 default: // AUTO or ALWAYS => true
5083 break;
jiabin81772902018-04-02 17:52:27 -07005084 }
5085 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5086 }
jiabin81772902018-04-02 17:52:27 -07005087 }
5088 return NO_ERROR;
5089}
5090
Kriti Dang6537def2021-03-02 13:46:59 +01005091status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5092 audio_format_t *surroundFormats) {
5093 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5094 return BAD_VALUE;
5095 }
5096 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5097 __func__, *numSurroundFormats, surroundFormats);
5098
5099 size_t formatsWritten = 0;
5100 size_t formatsMax = *numSurroundFormats;
5101 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5102
5103 // Return formats from all device profiles that have already been resolved by
5104 // checkOutputsForDevice().
5105 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5106 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5107 audio_devices_t deviceType = device->type();
5108 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5109 // returns formats reported by HDMI devices.
5110 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5111 continue;
5112 }
5113 // Formats reported by sink devices
5114 std::unordered_set<audio_format_t> formatset;
5115 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5116 formatset.insert(it->second.begin(), it->second.end());
5117 }
5118
5119 // Formats hard-coded in the in policy configuration file (if any).
5120 FormatVector encodedFormats = device->encodedFormats();
5121 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5122 // Filter the formats which are supported by the vendor hardware.
5123 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5124 if (mConfig.getSurroundFormats().count(*it) != 0) {
5125 formats.insert(*it);
5126 } else {
5127 for (const auto& pair : mConfig.getSurroundFormats()) {
5128 if (pair.second.count(*it) != 0) {
5129 formats.insert(pair.first);
5130 break;
5131 }
5132 }
5133 }
5134 }
5135 }
5136 *numSurroundFormats = formats.size();
5137 for (const auto& format: formats) {
5138 if (formatsWritten < formatsMax) {
5139 surroundFormats[formatsWritten++] = format;
5140 }
5141 }
5142 return NO_ERROR;
5143}
5144
jiabin81772902018-04-02 17:52:27 -07005145status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5146{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005147 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005148 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5149 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005150 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005151 return BAD_VALUE;
5152 }
5153
Mikhail Naganov100f0122018-11-29 11:22:16 -08005154 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5155 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005156 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005157 return INVALID_OPERATION;
5158 }
5159
Mikhail Naganov100f0122018-11-29 11:22:16 -08005160 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005161 return NO_ERROR;
5162 }
5163
Mikhail Naganov100f0122018-11-29 11:22:16 -08005164 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005165 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005166 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005167 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005168 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005169 }
5170 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005171 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005172 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005173 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005174 }
5175 }
5176
5177 sp<SwAudioOutputDescriptor> outputDesc;
5178 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005179 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5180 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005181 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5182 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005183 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005184 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005185 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5186 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5187 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005188 name.c_str(),
5189 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005190 if (status != NO_ERROR) {
5191 continue;
5192 }
5193 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5194 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5195 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005196 name.c_str(),
5197 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005198 profileUpdated |= (status == NO_ERROR);
5199 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005200 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005201 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005202 AUDIO_DEVICE_IN_HDMI);
5203 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5204 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005205 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005206 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005207 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5208 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5209 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005210 name.c_str(),
5211 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005212 if (status != NO_ERROR) {
5213 continue;
5214 }
5215 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5216 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5217 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005218 name.c_str(),
5219 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005220 profileUpdated |= (status == NO_ERROR);
5221 }
5222
jiabin81772902018-04-02 17:52:27 -07005223 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005224 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005225 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005226 }
5227
5228 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5229}
5230
Eric Laurent5ada82e2019-08-29 17:53:54 -07005231void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005232{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005233 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005234 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005235 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005236 }
5237}
5238
jiabin6012f912018-11-02 17:06:30 -07005239bool AudioPolicyManager::isHapticPlaybackSupported()
5240{
5241 for (const auto& hwModule : mHwModules) {
5242 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5243 for (const auto &outProfile : outputProfiles) {
5244 struct audio_port audioPort;
5245 outProfile->toAudioPort(&audioPort);
5246 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5247 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5248 return true;
5249 }
5250 }
5251 }
5252 }
5253 return false;
5254}
5255
Carter Hsu325a8eb2022-01-19 19:56:51 +08005256bool AudioPolicyManager::isUltrasoundSupported()
5257{
5258 bool hasUltrasoundOutput = false;
5259 bool hasUltrasoundInput = false;
5260 for (const auto& hwModule : mHwModules) {
5261 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5262 if (!hasUltrasoundOutput) {
5263 for (const auto &outProfile : outputProfiles) {
5264 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5265 hasUltrasoundOutput = true;
5266 break;
5267 }
5268 }
5269 }
5270
5271 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5272 if (!hasUltrasoundInput) {
5273 for (const auto &inputProfile : inputProfiles) {
5274 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5275 hasUltrasoundInput = true;
5276 break;
5277 }
5278 }
5279 }
5280
5281 if (hasUltrasoundOutput && hasUltrasoundInput)
5282 return true;
5283 }
5284 return false;
5285}
5286
Eric Laurent8340e672019-11-06 11:01:08 -08005287bool AudioPolicyManager::isCallScreenModeSupported()
5288{
5289 return getConfig().isCallScreenModeSupported();
5290}
5291
5292
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005293status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005294{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005295 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005296 if (!sourceDesc->isConnected()) {
5297 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5298 return NO_ERROR;
5299 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5301 if (swOutput != 0) {
5302 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005303 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005305 }
jiabinbce0c1d2020-10-05 11:20:18 -07005306 if (releaseOutput(sourceDesc->portId())) {
5307 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5308 // no need to release audio patch here but just return NO_ERROR.
5309 return NO_ERROR;
5310 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005311 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005312 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005313 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005314 // close Hwoutput and remove from mHwOutputs
5315 } else {
5316 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5317 }
5318 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005319 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005320 sourceDesc->disconnect();
5321 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005322}
5323
François Gaffiec005e562018-11-06 15:04:49 +01005324sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5325 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005326{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005327 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005328 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005329 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005330 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005331 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5332 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005333 source = sourceDesc;
5334 break;
5335 }
5336 }
5337 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005338}
5339
Eric Laurent39095982021-08-24 18:29:27 +02005340/* static */
5341bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5342 switch (channels) {
5343 case AUDIO_CHANNEL_OUT_5POINT1:
5344 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5345 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5346 case AUDIO_CHANNEL_OUT_7POINT1:
5347 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5348 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5349 return true;
5350 default:
5351 return false;
5352 }
5353}
5354
Eric Laurentb4f42a92022-01-17 17:37:31 +01005355bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005356 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005357 const AudioDeviceTypeAddrVector &devices,
5358 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005359{
5360 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5361 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005362 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005363 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005364 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5365 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5366 return false;
5367 }
5368 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5369 return false;
5370 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005371 }
5372
5373 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005374 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5375 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005376 // to the specified devices must exist.
5377 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005378 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005379 if (profile == nullptr) {
5380 return false;
5381 }
5382
5383 // The caller can have the audio config criteria ignored by either passing a null ptr or
5384 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005385 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005386 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005387 // If the spatializer output is already opened, only channel masks included in the
5388 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005389
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005390 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005391 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005392 return false;
5393 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005394 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5395 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005396 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005397 != config->channel_mask) {
5398 return false;
5399 }
5400 }
5401 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005402 return true;
5403}
5404
5405void AudioPolicyManager::checkVirtualizerClientRoutes() {
5406 std::set<audio_stream_type_t> streamsToInvalidate;
5407 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005408 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5409 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005410 audio_attributes_t attr = client->attributes();
5411 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5412 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5413 audio_config_base_t clientConfig = client->config();
5414 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005415 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005416 && canBeSpatializedInt(&attr, &config,
5417 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005418 streamsToInvalidate.insert(client->stream());
5419 }
5420 }
5421 }
5422
5423 for (audio_stream_type_t stream : streamsToInvalidate) {
5424 mpClientInterface->invalidateStream(stream);
5425 }
5426}
5427
Eric Laurente191d1b2022-04-15 11:59:25 +02005428
5429bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5430 const sp<SwAudioOutputDescriptor>& outputDesc) {
5431 if (outputDesc->isDuplicated()) {
5432 return false;
5433 }
5434 DeviceVector devices = outputDesc->supportedDevices();
5435 for (size_t i = 0; i < mOutputs.size(); i++) {
5436 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5437 if (desc == outputDesc || desc->isDuplicated()) {
5438 continue;
5439 }
5440 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5441 if (!sharedDevices.isEmpty()
5442 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5443 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5444 return false;
5445 }
5446 }
5447 return true;
5448}
5449
5450
Eric Laurentfa0f6742021-08-17 18:39:44 +02005451status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005452 const audio_attributes_t *attr,
5453 audio_io_handle_t *output) {
5454 *output = AUDIO_IO_HANDLE_NONE;
5455
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005456 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5457 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5458 audio_config_t *configPtr = nullptr;
5459 audio_config_t config;
5460 if (mixerConfig != nullptr) {
5461 config = audio_config_initializer(mixerConfig);
5462 configPtr = &config;
5463 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005464 if (!canBeSpatializedInt(
5465 attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005466 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005467 return BAD_VALUE;
5468 }
5469
5470 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005471 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005472 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005473 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005474 return BAD_VALUE;
5475 }
5476
Eric Laurente191d1b2022-04-15 11:59:25 +02005477 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005478 for (size_t i = 0; i < mOutputs.size(); i++) {
5479 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005480 if (!desc->isDuplicated()
5481 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5482 spatializerOutputs.push_back(desc);
5483 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005484 }
5485 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005486 mSpatializerOutput.clear();
5487 bool outputsChanged = false;
5488 for (const auto& desc : spatializerOutputs) {
5489 if (desc->mProfile == profile
5490 && (configPtr == nullptr
5491 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5492 mSpatializerOutput = desc;
5493 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5494 } else {
5495 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5496 " and devices %s", __func__, desc->mIoHandle,
5497 configPtr != nullptr ? configPtr->channel_mask : 0,
5498 devices.toString().c_str());
5499 closeOutput(desc->mIoHandle);
5500 outputsChanged = true;
5501 }
Eric Laurent39095982021-08-24 18:29:27 +02005502 }
5503
Eric Laurente191d1b2022-04-15 11:59:25 +02005504 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005505 sp<SwAudioOutputDescriptor> desc =
5506 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005507 if (desc != nullptr) {
5508 mSpatializerOutput = desc;
5509 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005510 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005511 }
5512
5513 checkVirtualizerClientRoutes();
5514
Eric Laurente191d1b2022-04-15 11:59:25 +02005515 if (outputsChanged) {
5516 mPreviousOutputs = mOutputs;
5517 mpClientInterface->onAudioPortListUpdate();
5518 }
5519
5520 if (mSpatializerOutput == nullptr) {
5521 ALOGV("%s could not open spatializer output with requested config", __func__);
5522 return BAD_VALUE;
5523 }
Eric Laurent39095982021-08-24 18:29:27 +02005524 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005525 ALOGV("%s returning new spatializer output %d", __func__, *output);
5526 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005527}
5528
Eric Laurentfa0f6742021-08-17 18:39:44 +02005529status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5530 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005531 return INVALID_OPERATION;
5532 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005533 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005534 return BAD_VALUE;
5535 }
Eric Laurent39095982021-08-24 18:29:27 +02005536
Eric Laurente191d1b2022-04-15 11:59:25 +02005537 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5538 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5539 closeOutput(mSpatializerOutput->mIoHandle);
5540 //from now on mSpatializerOutput is null
5541 checkVirtualizerClientRoutes();
5542 }
Eric Laurent39095982021-08-24 18:29:27 +02005543
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005544 return NO_ERROR;
5545}
5546
Eric Laurente552edb2014-03-10 17:42:56 -07005547// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005548// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005549// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005550uint32_t AudioPolicyManager::nextAudioPortGeneration()
5551{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005552 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005553}
5554
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005555static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005556 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5557 !audioPolicyXmlConfigFile.empty()) {
5558 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5559 if (ret == NO_ERROR) {
5560 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005561 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005562 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005563 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005564 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005565}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005566
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005567AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5568 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005569 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005570 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005571 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005572 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005573 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005574 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005575 mAudioPortGeneration(1),
5576 mBeaconMuteRefCount(0),
5577 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005578 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005579 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005580 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005581 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005582{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005583}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005584
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005585AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5586 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5587{
5588 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005589}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005590
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005591void AudioPolicyManager::loadConfig() {
5592 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005593 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005594 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005595 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005596}
5597
5598status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005599 {
5600 auto engLib = EngineLibrary::load(
5601 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5602 if (!engLib) {
5603 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5604 return NO_INIT;
5605 }
5606 mEngine = engLib->createEngine();
5607 if (mEngine == nullptr) {
5608 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5609 return NO_INIT;
5610 }
François Gaffie2110e042015-03-24 08:41:51 +01005611 }
5612 mEngine->setObserver(this);
5613 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005614 if (status != NO_ERROR) {
5615 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5616 return status;
5617 }
François Gaffie2110e042015-03-24 08:41:51 +01005618
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005619 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005620 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5621 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5622
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005623 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005624 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005625 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005626
Eric Laurent3a4311c2014-03-17 12:00:47 -07005627 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005628 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5629 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5630 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005631 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005632 }
jiabin9ff780e2018-03-19 18:19:52 -07005633 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005634 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005635 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005636 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005637 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005638 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005639 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005640 }
5641 }
5642 }
Eric Laurente552edb2014-03-10 17:42:56 -07005643
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005644 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005645
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005646 // Silence ALOGV statements
5647 property_set("log.tag." LOG_TAG, "D");
5648
Eric Laurente552edb2014-03-10 17:42:56 -07005649 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005650 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005651}
5652
Eric Laurente0720872014-03-11 09:30:41 -07005653AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005654{
Eric Laurente552edb2014-03-10 17:42:56 -07005655 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005656 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005657 }
5658 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005659 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005660 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005661 mAvailableOutputDevices.clear();
5662 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005663 mOutputs.clear();
5664 mInputs.clear();
5665 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005666 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005667 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005668}
5669
Eric Laurente0720872014-03-11 09:30:41 -07005670status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005671{
Eric Laurent87ffa392015-05-22 10:32:38 -07005672 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005673}
5674
Eric Laurente552edb2014-03-10 17:42:56 -07005675// ---
5676
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005677void AudioPolicyManager::onNewAudioModulesAvailable()
5678{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005679 DeviceVector newDevices;
5680 onNewAudioModulesAvailableInt(&newDevices);
5681 if (!newDevices.empty()) {
5682 nextAudioPortGeneration();
5683 mpClientInterface->onAudioPortListUpdate();
5684 }
5685}
5686
5687void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5688{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005689 for (const auto& hwModule : mHwModulesAll) {
5690 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5691 continue;
5692 }
5693 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5694 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5695 ALOGW("could not open HW module %s", hwModule->getName());
5696 continue;
5697 }
5698 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005699 // open all output streams needed to access attached devices.
5700 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005701 // This also validates mAvailableOutputDevices list
5702 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5703 if (!outProfile->canOpenNewIo()) {
5704 ALOGE("Invalid Output profile max open count %u for profile %s",
5705 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5706 continue;
5707 }
5708 if (!outProfile->hasSupportedDevices()) {
5709 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5710 continue;
5711 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005712 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5713 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005714 mTtsOutputAvailable = true;
5715 }
5716
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005717 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5718 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5719 sp<DeviceDescriptor> supportedDevice = 0;
5720 if (supportedDevices.contains(mDefaultOutputDevice)) {
5721 supportedDevice = mDefaultOutputDevice;
5722 } else {
5723 // choose first device present in profile's SupportedDevices also part of
5724 // mAvailableOutputDevices.
5725 if (availProfileDevices.isEmpty()) {
5726 continue;
5727 }
5728 supportedDevice = availProfileDevices.itemAt(0);
5729 }
5730 if (!mOutputDevicesAll.contains(supportedDevice)) {
5731 continue;
5732 }
5733 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5734 mpClientInterface);
5735 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005736 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5737 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005738 AUDIO_STREAM_DEFAULT,
5739 AUDIO_OUTPUT_FLAG_NONE, &output);
5740 if (status != NO_ERROR) {
5741 ALOGW("Cannot open output stream for devices %s on hw module %s",
5742 supportedDevice->toString().c_str(), hwModule->getName());
5743 continue;
5744 }
5745 for (const auto &device : availProfileDevices) {
5746 // give a valid ID to an attached device once confirmed it is reachable
5747 if (!device->isAttached()) {
5748 device->attach(hwModule);
5749 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005750 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005751 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005752 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5753 }
5754 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005755 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005756 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5757 mPrimaryOutput = outputDesc;
5758 }
Eric Laurent39095982021-08-24 18:29:27 +02005759 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005760 outputDesc->close();
5761 } else {
5762 addOutput(output, outputDesc);
5763 setOutputDevices(outputDesc,
5764 DeviceVector(supportedDevice),
5765 true,
5766 0,
5767 NULL);
5768 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005769 }
5770 // open input streams needed to access attached devices to validate
5771 // mAvailableInputDevices list
5772 for (const auto& inProfile : hwModule->getInputProfiles()) {
5773 if (!inProfile->canOpenNewIo()) {
5774 ALOGE("Invalid Input profile max open count %u for profile %s",
5775 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5776 continue;
5777 }
5778 if (!inProfile->hasSupportedDevices()) {
5779 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5780 continue;
5781 }
5782 // chose first device present in profile's SupportedDevices also part of
5783 // available input devices
5784 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5785 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5786 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005787 ALOGV("%s: Input device list is empty! for profile %s",
5788 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005789 continue;
5790 }
5791 sp<AudioInputDescriptor> inputDesc =
5792 new AudioInputDescriptor(inProfile, mpClientInterface);
5793
5794 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5795 status_t status = inputDesc->open(nullptr,
5796 availProfileDevices.itemAt(0),
5797 AUDIO_SOURCE_MIC,
5798 AUDIO_INPUT_FLAG_NONE,
5799 &input);
5800 if (status != NO_ERROR) {
5801 ALOGW("Cannot open input stream for device %s on hw module %s",
5802 availProfileDevices.toString().c_str(),
5803 hwModule->getName());
5804 continue;
5805 }
5806 for (const auto &device : availProfileDevices) {
5807 // give a valid ID to an attached device once confirmed it is reachable
5808 if (!device->isAttached()) {
5809 device->attach(hwModule);
5810 device->importAudioPortAndPickAudioProfile(inProfile, true);
5811 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005812 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005813 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5814 }
5815 }
5816 inputDesc->close();
5817 }
5818 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005819
5820 // Check if spatializer outputs can be closed until used.
5821 // mOutputs vector never contains duplicated outputs at this point.
5822 std::vector<audio_io_handle_t> outputsClosed;
5823 for (size_t i = 0; i < mOutputs.size(); i++) {
5824 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5825 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5826 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5827 outputsClosed.push_back(desc->mIoHandle);
5828 desc->close();
5829 }
5830 }
5831 for (auto output : outputsClosed) {
5832 removeOutput(output);
5833 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005834}
5835
Eric Laurent98e38192018-02-15 18:31:53 -08005836void AudioPolicyManager::addOutput(audio_io_handle_t output,
5837 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005838{
Eric Laurent1c333e22014-05-20 10:48:17 -07005839 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005840 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005841 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005842 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005843 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005844}
5845
François Gaffie53615e22015-03-19 09:24:12 +01005846void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5847{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005848 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5849 ALOGV("%s: removing primary output", __func__);
5850 mPrimaryOutput = nullptr;
5851 }
François Gaffie53615e22015-03-19 09:24:12 +01005852 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005853 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005854}
5855
Eric Laurent98e38192018-02-15 18:31:53 -08005856void AudioPolicyManager::addInput(audio_io_handle_t input,
5857 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005858{
Eric Laurent1c333e22014-05-20 10:48:17 -07005859 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005860 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005861}
Eric Laurente552edb2014-03-10 17:42:56 -07005862
François Gaffie11d30102018-11-02 16:09:09 +01005863status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005864 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005865 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005866{
François Gaffie11d30102018-11-02 16:09:09 +01005867 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005868 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005869 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005870
François Gaffie11d30102018-11-02 16:09:09 +01005871 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005872 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005873 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005874 }
Eric Laurente552edb2014-03-10 17:42:56 -07005875
Eric Laurent3b73df72014-03-11 09:06:29 -07005876 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005877 // first call getAudioPort to get the supported attributes from the HAL
5878 struct audio_port_v7 port = {};
5879 device->toAudioPort(&port);
5880 status_t status = mpClientInterface->getAudioPort(&port);
5881 if (status == NO_ERROR) {
5882 device->importAudioPort(port);
5883 }
5884
5885 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005886 for (size_t i = 0; i < mOutputs.size(); i++) {
5887 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005888 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005889 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005890 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5891 mOutputs.keyAt(i), device->toString().c_str());
5892 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005893 }
5894 }
5895 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005896 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005897 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005898 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5899 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005900 if (profile->supportsDevice(device)) {
5901 profiles.add(profile);
5902 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5903 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005904 }
5905 }
5906 }
5907
Eric Laurent7b279bb2015-12-14 10:18:23 -08005908 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005909
Eric Laurente552edb2014-03-10 17:42:56 -07005910 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005911 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005912 return BAD_VALUE;
5913 }
5914
5915 // open outputs for matching profiles if needed. Direct outputs are also opened to
5916 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5917 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005918 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005919
5920 // nothing to do if one output is already opened for this profile
5921 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005922 for (j = 0; j < outputs.size(); j++) {
5923 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005924 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005925 // matching profile: save the sample rates, format and channel masks supported
5926 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005927 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005928 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005929 }
Eric Laurente552edb2014-03-10 17:42:56 -07005930 break;
5931 }
5932 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005933 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005934 continue;
5935 }
5936
Eric Laurent3974e3b2017-12-07 17:58:43 -08005937 if (!profile->canOpenNewIo()) {
5938 ALOGW("Max Output number %u already opened for this profile %s",
5939 profile->maxOpenCount, profile->getTagName().c_str());
5940 continue;
5941 }
5942
Eric Laurent83efe1c2017-07-09 16:51:08 -07005943 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005944 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005945 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5946 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005947 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005948 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005949 profiles.removeAt(profile_index);
5950 profile_index--;
5951 } else {
5952 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005953 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005954 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005955 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5956 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005957 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005958 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005959
François Gaffie11d30102018-11-02 16:09:09 +01005960 if (device_distinguishes_on_address(deviceType)) {
5961 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5962 device->toString().c_str());
5963 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5964 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005965 }
Eric Laurente552edb2014-03-10 17:42:56 -07005966 ALOGV("checkOutputsForDevice(): adding output %d", output);
5967 }
5968 }
5969
5970 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005971 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005972 return BAD_VALUE;
5973 }
Eric Laurentd4692962014-05-05 18:13:44 -07005974 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005975 // check if one opened output is not needed any more after disconnecting one device
5976 for (size_t i = 0; i < mOutputs.size(); i++) {
5977 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005978 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005979 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005980 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005981 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005982 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005983 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005984 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5985 mOutputs.keyAt(i));
5986 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005987 }
Eric Laurente552edb2014-03-10 17:42:56 -07005988 }
5989 }
Eric Laurentd4692962014-05-05 18:13:44 -07005990 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005991 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005992 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5993 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005994 if (!profile->supportsDevice(device)) {
5995 continue;
5996 }
5997 ALOGV("checkOutputsForDevice(): "
5998 "clearing direct output profile %zu on module %s",
5999 j, hwModule->getName());
6000 profile->clearAudioProfiles();
6001 if (!profile->hasDynamicAudioProfile()) {
6002 continue;
6003 }
6004 // When a device is disconnected, if there is an IOProfile that contains dynamic
6005 // profiles and supports the disconnected device, call getAudioPort to repopulate
6006 // the capabilities of the devices that is supported by the IOProfile.
6007 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6008 if (supportedDevice == device ||
6009 !mAvailableOutputDevices.contains(supportedDevice)) {
6010 continue;
6011 }
6012 struct audio_port_v7 port;
6013 supportedDevice->toAudioPort(&port);
6014 status_t status = mpClientInterface->getAudioPort(&port);
6015 if (status == NO_ERROR) {
6016 supportedDevice->importAudioPort(port);
6017 }
Eric Laurente552edb2014-03-10 17:42:56 -07006018 }
6019 }
6020 }
6021 }
6022 return NO_ERROR;
6023}
6024
François Gaffie11d30102018-11-02 16:09:09 +01006025status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006026 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006027{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006028 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006029
François Gaffie11d30102018-11-02 16:09:09 +01006030 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006031 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006032 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006033 }
6034
Eric Laurentd4692962014-05-05 18:13:44 -07006035 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006036 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006037 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006038 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006039 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006040 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006041 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006042 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006043
François Gaffie11d30102018-11-02 16:09:09 +01006044 if (profile->supportsDevice(device)) {
6045 profiles.add(profile);
6046 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6047 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006048 }
6049 }
6050 }
6051
Eric Laurent0dd51852019-04-19 18:18:58 -07006052 if (profiles.isEmpty()) {
6053 ALOGW("%s: No input profile available for device %s",
6054 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006055 return BAD_VALUE;
6056 }
6057
6058 // open inputs for matching profiles if needed. Direct inputs are also opened to
6059 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6060 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6061
Eric Laurent1c333e22014-05-20 10:48:17 -07006062 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006063
Eric Laurentd4692962014-05-05 18:13:44 -07006064 // nothing to do if one input is already opened for this profile
6065 size_t input_index;
6066 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6067 desc = mInputs.valueAt(input_index);
6068 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006069 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006070 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006071 }
Eric Laurentd4692962014-05-05 18:13:44 -07006072 break;
6073 }
6074 }
6075 if (input_index != mInputs.size()) {
6076 continue;
6077 }
6078
Eric Laurent3974e3b2017-12-07 17:58:43 -08006079 if (!profile->canOpenNewIo()) {
6080 ALOGW("Max Input number %u already opened for this profile %s",
6081 profile->maxOpenCount, profile->getTagName().c_str());
6082 continue;
6083 }
6084
Eric Laurentfe231122017-11-17 17:48:06 -08006085 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006086 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006087 status_t status = desc->open(nullptr,
6088 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006089 AUDIO_SOURCE_MIC,
6090 AUDIO_INPUT_FLAG_NONE,
6091 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006092
Eric Laurentcf2c0212014-07-25 16:20:43 -07006093 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006094 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006095 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006096 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006097 mpClientInterface->setParameters(input, String8(param));
6098 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006099 }
François Gaffie11d30102018-11-02 16:09:09 +01006100 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006101 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006102 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006103 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006104 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006105 }
6106
Eric Laurent0dd51852019-04-19 18:18:58 -07006107 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006108 addInput(input, desc);
6109 }
6110 } // endif input != 0
6111
Eric Laurentcf2c0212014-07-25 16:20:43 -07006112 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006113 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006114 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006115 profiles.removeAt(profile_index);
6116 profile_index--;
6117 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006118 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006119 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006120 }
Eric Laurentd4692962014-05-05 18:13:44 -07006121 ALOGV("checkInputsForDevice(): adding input %d", input);
6122 }
6123 } // end scan profiles
6124
6125 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006126 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006127 return BAD_VALUE;
6128 }
6129 } else {
6130 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006131 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006132 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006133 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006134 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006135 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006136 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006137 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006138 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6139 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006140 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006141 }
6142 }
6143 }
6144 } // end disconnect
6145
6146 return NO_ERROR;
6147}
6148
6149
Eric Laurente0720872014-03-11 09:30:41 -07006150void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006151{
6152 ALOGV("closeOutput(%d)", output);
6153
François Gaffie1c878552018-11-22 16:53:21 +01006154 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6155 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006156 ALOGW("closeOutput() unknown output %d", output);
6157 return;
6158 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006159 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006160 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006161
Eric Laurente552edb2014-03-10 17:42:56 -07006162 // look for duplicated outputs connected to the output being removed.
6163 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006164 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6165 if (dupOutput->isDuplicated() &&
6166 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6167 sp<SwAudioOutputDescriptor> remainingOutput =
6168 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006169 // As all active tracks on duplicated output will be deleted,
6170 // and as they were also referenced on the other output, the reference
6171 // count for their stream type must be adjusted accordingly on
6172 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006173 const bool wasActive = remainingOutput->isActive();
6174 // Note: no-op on the closing output where all clients has already been set inactive
6175 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006176 // stop() will be a no op if the output is still active but is needed in case all
6177 // active streams refcounts where cleared above
6178 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006179 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006180 }
Eric Laurente552edb2014-03-10 17:42:56 -07006181 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6182 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6183
6184 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006185 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006186 }
6187 }
6188
Eric Laurent05b90f82014-08-27 15:32:29 -07006189 nextAudioPortGeneration();
6190
François Gaffie1c878552018-11-22 16:53:21 +01006191 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006192 if (index >= 0) {
6193 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006194 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6195 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006196 mAudioPatches.removeItemsAt(index);
6197 mpClientInterface->onAudioPatchListUpdate();
6198 }
6199
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006200 if (closingOutputWasActive) {
6201 closingOutput->stop();
6202 }
François Gaffie1c878552018-11-22 16:53:21 +01006203 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006204
François Gaffie53615e22015-03-19 09:24:12 +01006205 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006206 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006207 if (closingOutput == mSpatializerOutput) {
6208 mSpatializerOutput.clear();
6209 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006210
6211 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6212 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006213 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006214 bool directOutputOpen = false;
6215 for (size_t i = 0; i < mOutputs.size(); i++) {
6216 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6217 directOutputOpen = true;
6218 break;
6219 }
6220 }
6221 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006222 ALOGV("no direct outputs open, reset MSD patches");
6223 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6224 // how output devices for patching are resolved. Avoid by caching and reusing the
6225 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6226 // devices to patch to. This may be complicated by the fact that devices may become
6227 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006228 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006229 }
6230 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006231}
6232
6233void AudioPolicyManager::closeInput(audio_io_handle_t input)
6234{
6235 ALOGV("closeInput(%d)", input);
6236
6237 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6238 if (inputDesc == NULL) {
6239 ALOGW("closeInput() unknown input %d", input);
6240 return;
6241 }
6242
Eric Laurent6a94d692014-05-20 11:18:06 -07006243 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006244
François Gaffie11d30102018-11-02 16:09:09 +01006245 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006246 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006247 if (index >= 0) {
6248 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006249 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6250 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006251 mAudioPatches.removeItemsAt(index);
6252 mpClientInterface->onAudioPatchListUpdate();
6253 }
6254
Eric Laurentfe231122017-11-17 17:48:06 -08006255 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006256 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006257
François Gaffie11d30102018-11-02 16:09:09 +01006258 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6259 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006260 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006261 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006262 }
Eric Laurente552edb2014-03-10 17:42:56 -07006263}
6264
François Gaffie11d30102018-11-02 16:09:09 +01006265SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6266 const DeviceVector &devices,
6267 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006268{
6269 SortedVector<audio_io_handle_t> outputs;
6270
François Gaffie11d30102018-11-02 16:09:09 +01006271 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006272 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006273 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006274 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006275 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006276 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006277 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006278 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006279 outputs.add(openOutputs.keyAt(i));
6280 }
6281 }
6282 return outputs;
6283}
6284
Mikhail Naganov37977152018-07-11 15:54:44 -07006285void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6286{
6287 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6288 // output is suspended before any tracks are moved to it
6289 checkA2dpSuspend();
6290 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006291 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006292 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006293 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006294 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006295 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6296 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6297 // configuration changes will ultimately be rerouted correctly. We can still avoid
6298 // unnecessary rerouting by caching and reusing the arguments to
6299 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6300 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006301 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006302 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006303 // an event that changed routing likely occurred, inform upper layers
6304 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006305}
6306
François Gaffiec005e562018-11-06 15:04:49 +01006307bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6308 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006309{
François Gaffiec005e562018-11-06 15:04:49 +01006310 return mEngine->getProductStrategyForAttributes(lAttr) ==
6311 mEngine->getProductStrategyForAttributes(rAttr);
6312}
6313
Francois Gaffieff1eb522020-05-06 18:37:04 +02006314void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6315{
6316 for (size_t i = 0; i < mAudioSources.size(); i++) {
6317 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6318 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006319 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006320 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006321 connectAudioSource(sourceDesc);
6322 }
6323 }
6324}
6325
6326void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6327{
6328 for (size_t i = 0; i < mAudioSources.size(); i++) {
6329 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6330 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6331 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6332 disconnectAudioSource(sourceDesc);
6333 }
6334 }
6335}
6336
François Gaffiec005e562018-11-06 15:04:49 +01006337void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6338{
6339 auto psId = mEngine->getProductStrategyForAttributes(attr);
6340
6341 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6342 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006343
François Gaffie11d30102018-11-02 16:09:09 +01006344 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6345 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006346
Eric Laurentc209fe42020-06-05 18:11:23 -07006347 uint32_t maxLatency = 0;
6348 bool invalidate = false;
6349 // take into account dynamic audio policies related changes: if a client is now associated
6350 // to a different policy mix than at creation time, invalidate corresponding stream
6351 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6352 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6353 if (desc->isDuplicated()) {
6354 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006355 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006356 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6357 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6358 continue;
6359 }
6360 sp<AudioPolicyMix> primaryMix;
6361 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6362 client->flags(), primaryMix, nullptr);
6363 if (status != OK) {
6364 continue;
6365 }
yucliuf4de36d2020-09-14 14:57:56 -07006366 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006367 invalidate = true;
6368 if (desc->isStrategyActive(psId)) {
6369 maxLatency = desc->latency();
6370 }
6371 break;
6372 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006373 }
6374 }
6375
Eric Laurentc209fe42020-06-05 18:11:23 -07006376 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006377 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6378 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006379 for (audio_io_handle_t srcOut : srcOutputs) {
6380 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006381 if (desc == nullptr) continue;
6382
6383 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006384 maxLatency = desc->latency();
6385 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006386
6387 if (invalidate) continue;
6388
6389 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006390 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006391 // a client on a non direct outputs has necessarily a linear PCM format
6392 // so we can call selectOutput() safely
6393 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6394 client->flags(),
6395 client->config().format,
6396 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006397 client->config().sample_rate,
6398 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006399 if (newOutput != srcOut) {
6400 invalidate = true;
6401 break;
6402 }
6403 } else {
6404 sp<IOProfile> profile = getProfileForOutput(newDevices,
6405 client->config().sample_rate,
6406 client->config().format,
6407 client->config().channel_mask,
6408 client->flags(),
6409 true /* directOnly */);
6410 if (profile != desc->mProfile) {
6411 invalidate = true;
6412 break;
6413 }
6414 }
6415 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006416 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006417
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006418 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006419 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006420 std::to_string(srcOutputs[0]).c_str(),
6421 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006422 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006423 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006424 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006425 if (desc == nullptr) continue;
6426
6427 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006428 setStrategyMute(psId, true, desc);
6429 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006430 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006431 }
François Gaffiec005e562018-11-06 15:04:49 +01006432 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006433 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006434 connectAudioSource(source);
6435 }
Eric Laurente552edb2014-03-10 17:42:56 -07006436 }
6437
François Gaffiec005e562018-11-06 15:04:49 +01006438 // Move effects associated to this stream from previous output to new output
6439 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006440 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006441 }
François Gaffiec005e562018-11-06 15:04:49 +01006442 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006443 if (invalidate) {
6444 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6445 mpClientInterface->invalidateStream(stream);
6446 }
jiabin49256852022-03-09 11:21:35 -08006447 for (audio_io_handle_t srcOut : srcOutputs) {
6448 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6449 if (desc == nullptr) continue;
6450
6451 desc->setTracksInvalidatedStatusByStrategy(psId);
6452 }
Eric Laurente552edb2014-03-10 17:42:56 -07006453 }
6454 }
6455}
6456
Eric Laurente0720872014-03-11 09:30:41 -07006457void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006458{
François Gaffiec005e562018-11-06 15:04:49 +01006459 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6460 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6461 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006462 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006463 }
Eric Laurente552edb2014-03-10 17:42:56 -07006464}
6465
Kevin Rocard153f92d2018-12-18 18:33:28 -08006466void AudioPolicyManager::checkSecondaryOutputs() {
6467 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006468 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006469 for (size_t i = 0; i < mOutputs.size(); i++) {
6470 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6471 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006472 sp<AudioPolicyMix> primaryMix;
6473 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006474 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006475 client->flags(), primaryMix, &secondaryMixes);
6476 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6477 for (auto &secondaryMix : secondaryMixes) {
6478 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6479 if (outputDesc != nullptr &&
6480 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6481 secondaryDescs.push_back(outputDesc);
6482 }
6483 }
6484
jiabin10a03f12021-05-07 23:46:28 +00006485 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006486 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006487 } else if (!std::equal(
6488 client->getSecondaryOutputs().begin(),
6489 client->getSecondaryOutputs().end(),
6490 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006491 if (!audio_is_linear_pcm(client->config().format)) {
6492 // If the format is not PCM, the tracks should be invalidated to get correct
6493 // behavior when the secondary output is changed.
6494 streamsToInvalidate.insert(client->stream());
6495 } else {
6496 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6497 std::vector<audio_io_handle_t> secondaryOutputIds;
6498 for (const auto &secondaryDesc: secondaryDescs) {
6499 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6500 weakSecondaryDescs.push_back(secondaryDesc);
6501 }
6502 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6503 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006504 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006505 }
6506 }
6507 }
jiabin10a03f12021-05-07 23:46:28 +00006508 if (!trackSecondaryOutputs.empty()) {
6509 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6510 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006511 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006512 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006513 mpClientInterface->invalidateStream(stream);
6514 }
6515}
6516
Eric Laurent2517af32020-11-25 15:31:27 +01006517bool AudioPolicyManager::isScoRequestedForComm() const {
6518 AudioDeviceTypeAddrVector devices;
6519 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6520 for (const auto &device : devices) {
6521 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6522 return true;
6523 }
6524 }
6525 return false;
6526}
6527
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006528bool AudioPolicyManager::isHearingAidUsedForComm() const {
6529 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6530 true /*fromCache*/);
6531 for (const auto &device : devices) {
6532 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6533 return true;
6534 }
6535 }
6536 return false;
6537}
6538
6539
Eric Laurente0720872014-03-11 09:30:41 -07006540void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006541{
François Gaffie53615e22015-03-19 09:24:12 +01006542 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006543 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006544 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006545 return;
6546 }
6547
Eric Laurent3a4311c2014-03-17 12:00:47 -07006548 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006549 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6550 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006551 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006552
6553 // if suspended, restore A2DP output if:
6554 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006555 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006556 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006557 //
Eric Laurentf732e072016-08-03 19:30:28 -07006558 // if not suspended, suspend A2DP output if:
6559 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006560 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006561 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006562 //
6563 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006564 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006565 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006566 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006567 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006568
6569 mpClientInterface->restoreOutput(a2dpOutput);
6570 mA2dpSuspended = false;
6571 }
6572 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006573 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006574 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006575 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006576 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006577
6578 mpClientInterface->suspendOutput(a2dpOutput);
6579 mA2dpSuspended = true;
6580 }
6581 }
6582}
6583
François Gaffie11d30102018-11-02 16:09:09 +01006584DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6585 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006586{
François Gaffie11d30102018-11-02 16:09:09 +01006587 DeviceVector devices;
6588
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006589 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006590 if (index >= 0) {
6591 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006592 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006593 ALOGV("%s device %s forced by patch %d", __func__,
6594 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6595 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006596 }
6597 }
6598
Dean Wheatley514b4312020-06-17 21:45:00 +10006599 // Do not retrieve engine device for outputs through MSD
6600 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6601 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6602 return outputDesc->devices();
6603 }
6604
Eric Laurent97ac8712018-07-27 18:59:02 -07006605 // Honor explicit routing requests only if no client using default routing is active on this
6606 // input: a specific app can not force routing for other apps by setting a preferred device.
6607 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006608 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006609 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006610 if (device != nullptr) {
6611 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006612 }
6613
François Gaffiea807ef92018-11-05 10:44:33 +01006614 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6615 // of setForceUse / Default Bus device here
6616 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6617 if (device != nullptr) {
6618 return DeviceVector(device);
6619 }
6620
François Gaffiec005e562018-11-06 15:04:49 +01006621 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6622 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6623 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306624 auto hasStreamActive = [&](auto stream) {
6625 return hasStream(streams, stream) && isStreamActive(stream, 0);
6626 };
Eric Laurent484e9272018-06-07 17:29:23 -07006627
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306628 auto doGetOutputDevicesForVoice = [&]() {
6629 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006630 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306631 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006632 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6633 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306634 };
6635
6636 // With low-latency playing on speaker, music on WFD, when the first low-latency
6637 // output is stopped, getNewOutputDevices checks for a product strategy
6638 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006639 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306640 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6641 // stream is associated to the output descriptor.
6642 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6643 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6644 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6645 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006646 // Retrieval of devices for voice DL is done on primary output profile, cannot
6647 // check the route (would force modifying configuration file for this profile)
6648 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6649 break;
6650 }
Eric Laurente552edb2014-03-10 17:42:56 -07006651 }
François Gaffiec005e562018-11-06 15:04:49 +01006652 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006653 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006654}
6655
François Gaffie11d30102018-11-02 16:09:09 +01006656sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6657 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006658{
François Gaffie11d30102018-11-02 16:09:09 +01006659 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006660
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006661 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006662 if (index >= 0) {
6663 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006664 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006665 ALOGV("getNewInputDevice() device %s forced by patch %d",
6666 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6667 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006668 }
6669 }
6670
Eric Laurent97ac8712018-07-27 18:59:02 -07006671 // Honor explicit routing requests only if no client using default routing is active on this
6672 // input: a specific app can not force routing for other apps by setting a preferred device.
6673 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006674 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6675 if (device != nullptr) {
6676 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006677 }
6678
Eric Laurentdc95a252018-04-12 12:46:56 -07006679 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006680 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006681 audio_attributes_t attributes;
6682 uid_t uid;
6683 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6684 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006685 attributes = topClient->attributes();
6686 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006687 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006688 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6689 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006690 }
6691
Francois Gaffie716e1432019-01-14 16:58:59 +01006692 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6693 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006694 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006695 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006696 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006697 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006698
Eric Laurente552edb2014-03-10 17:42:56 -07006699 return device;
6700}
6701
Eric Laurent794fde22016-03-11 09:50:45 -08006702bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6703 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006704 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006705}
6706
Dorin Drimusf2196d82022-01-03 12:11:18 +01006707// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006708status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006709 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006710 if (devices == nullptr) {
6711 return BAD_VALUE;
6712 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006713
6714 // Devices are determined in the following precedence:
6715 //
6716 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6717 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6718 //
6719 // If no such dynamic policy then
6720 // 2) Devices containing an active client using setPreferredDevice
6721 // with same strategy as the attributes.
6722 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6723 //
6724 // If no corresponding active client with setPreferredDevice then
6725 // 3) Devices associated with the strategy determined by the attributes
6726 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6727 //
6728 // See related getOutputForAttrInt().
6729
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006730 // check dynamic policies but only for primary descriptors (secondary not used for audible
6731 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006732 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006733 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006734 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006735 if (status != OK) {
6736 return status;
6737 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006738
6739 DeviceVector curDevices;
6740 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6741 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6742 // as they are unaffected by device/stream volume
6743 // (per SwAudioOutputDescriptor::isFixedVolume()).
6744 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6745 ) {
6746 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6747 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6748 curDevices.add(deviceDesc);
6749 } else {
6750 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6751 // which selects setPreferredDevice if active. This means forVolume call
6752 // will take an active setPreferredDevice, if such exists.
6753
6754 curDevices = mEngine->getOutputDevicesForAttributes(
6755 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006756 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006757
6758 if (forVolume) {
6759 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6760 // for single volume control in AudioService (such relationship should exist if
6761 // SPEAKER_SAFE is present).
6762 //
6763 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6764 DeviceVector speakerSafeDevices =
6765 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6766 if (!speakerSafeDevices.isEmpty()) {
6767 curDevices.merge(
6768 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6769 curDevices.remove(speakerSafeDevices);
6770 }
6771 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006772 for (const auto& device : curDevices) {
6773 devices->push_back(device->getDeviceTypeAddr());
6774 }
6775 return NO_ERROR;
6776}
6777
Eric Laurente0720872014-03-11 09:30:41 -07006778void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006779 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006780 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006781 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006782 updateDevicesAndOutputs();
6783 break;
6784 default:
6785 break;
6786 }
6787}
6788
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006789uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006790
6791 // skip beacon mute management if a dedicated TTS output is available
6792 if (mTtsOutputAvailable) {
6793 return 0;
6794 }
6795
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006796 switch(event) {
6797 case STARTING_OUTPUT:
6798 mBeaconMuteRefCount++;
6799 break;
6800 case STOPPING_OUTPUT:
6801 if (mBeaconMuteRefCount > 0) {
6802 mBeaconMuteRefCount--;
6803 }
6804 break;
6805 case STARTING_BEACON:
6806 mBeaconPlayingRefCount++;
6807 break;
6808 case STOPPING_BEACON:
6809 if (mBeaconPlayingRefCount > 0) {
6810 mBeaconPlayingRefCount--;
6811 }
6812 break;
6813 }
6814
6815 if (mBeaconMuteRefCount > 0) {
6816 // any playback causes beacon to be muted
6817 return setBeaconMute(true);
6818 } else {
6819 // no other playback: unmute when beacon starts playing, mute when it stops
6820 return setBeaconMute(mBeaconPlayingRefCount == 0);
6821 }
6822}
6823
6824uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6825 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6826 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6827 // keep track of muted state to avoid repeating mute/unmute operations
6828 if (mBeaconMuted != mute) {
6829 // mute/unmute AUDIO_STREAM_TTS on all outputs
6830 ALOGV("\t muting %d", mute);
6831 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006832 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6833 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6834 ALOGV("\t no tts volume source available");
6835 return 0;
6836 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006837 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006838 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006839 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006840 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006841 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006842 maxLatency = latency;
6843 }
6844 }
6845 mBeaconMuted = mute;
6846 return maxLatency;
6847 }
6848 return 0;
6849}
6850
Eric Laurente0720872014-03-11 09:30:41 -07006851void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006852{
François Gaffiec005e562018-11-06 15:04:49 +01006853 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006854 mPreviousOutputs = mOutputs;
6855}
6856
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006857uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006858 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006859 uint32_t delayMs)
6860{
6861 // mute/unmute strategies using an incompatible device combination
6862 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6863 // if unmuting, unmute only after the specified delay
6864 if (outputDesc->isDuplicated()) {
6865 return 0;
6866 }
6867
6868 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006869 DeviceVector devices = outputDesc->devices();
6870 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006871
François Gaffiec005e562018-11-06 15:04:49 +01006872 auto productStrategies = mEngine->getOrderedProductStrategies();
6873 for (const auto &productStrategy : productStrategies) {
6874 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6875 DeviceVector curDevices =
6876 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6877 curDevices = curDevices.filter(outputDesc->supportedDevices());
6878 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006879 bool doMute = false;
6880
François Gaffiec005e562018-11-06 15:04:49 +01006881 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006882 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006883 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6884 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006885 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006886 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006887 }
Eric Laurent99401132014-05-07 19:48:15 -07006888 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006889 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006890 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006891 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006892 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006893 continue;
6894 }
François Gaffiec005e562018-11-06 15:04:49 +01006895 ALOGVV("%s() %s (curDevice %s)", __func__,
6896 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6897 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6898 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006899 if (mute) {
6900 // FIXME: should not need to double latency if volume could be applied
6901 // immediately by the audioflinger mixer. We must account for the delay
6902 // between now and the next time the audioflinger thread for this output
6903 // will process a buffer (which corresponds to one buffer size,
6904 // usually 1/2 or 1/4 of the latency).
6905 if (muteWaitMs < desc->latency() * 2) {
6906 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006907 }
6908 }
6909 }
6910 }
6911 }
6912 }
6913
Eric Laurent99401132014-05-07 19:48:15 -07006914 // temporary mute output if device selection changes to avoid volume bursts due to
6915 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006916 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006917 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006918
Eric Laurentdc462862016-07-19 12:29:53 -07006919 if (muteWaitMs < tempMuteWaitMs) {
6920 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006921 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006922
6923 // If recommended duration is defined, replace temporary mute duration to avoid
6924 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6925 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6926 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6927 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6928 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6929
François Gaffieaaac0fd2018-11-22 17:56:39 +01006930 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6931 // make sure that we do not start the temporary mute period too early in case of
6932 // delayed device change
6933 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6934 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006935 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006936 }
6937 }
6938
Eric Laurente552edb2014-03-10 17:42:56 -07006939 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6940 if (muteWaitMs > delayMs) {
6941 muteWaitMs -= delayMs;
6942 usleep(muteWaitMs * 1000);
6943 return muteWaitMs;
6944 }
6945 return 0;
6946}
6947
François Gaffie11d30102018-11-02 16:09:09 +01006948uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6949 const DeviceVector &devices,
6950 bool force,
6951 int delayMs,
6952 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006953 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006954{
François Gaffie11d30102018-11-02 16:09:09 +01006955 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006956 uint32_t muteWaitMs;
6957
6958 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006959 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6960 nullptr /* patchHandle */, requiresMuteCheck);
6961 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6962 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006963 return muteWaitMs;
6964 }
Eric Laurente552edb2014-03-10 17:42:56 -07006965
6966 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006967 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006968 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006969 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006970
François Gaffie11d30102018-11-02 16:09:09 +01006971 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6972
6973 if (!filteredDevices.isEmpty()) {
6974 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006975 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006976
6977 // if the outputs are not materially active, there is no need to mute.
6978 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006979 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006980 } else {
6981 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6982 muteWaitMs = 0;
6983 }
Eric Laurente552edb2014-03-10 17:42:56 -07006984
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006985 bool outputRouted = outputDesc->isRouted();
6986
Eric Laurent79ea9582020-06-11 18:49:24 -07006987 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6988 // output profile or if new device is not supported AND previous device(s) is(are) still
6989 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006990 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006991 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6992 // restore previous device after evaluating strategy mute state
6993 outputDesc->setDevices(prevDevices);
6994 return muteWaitMs;
6995 }
6996
Eric Laurente552edb2014-03-10 17:42:56 -07006997 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006998 // the requested device is AUDIO_DEVICE_NONE
6999 // OR the requested device is the same as current device
7000 // AND force is not specified
7001 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007002 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007003 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007004 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7005 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007006 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7007 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7008 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7009 }
Eric Laurente552edb2014-03-10 17:42:56 -07007010 return muteWaitMs;
7011 }
7012
François Gaffie11d30102018-11-02 16:09:09 +01007013 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007014
Eric Laurente552edb2014-03-10 17:42:56 -07007015 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007016 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007017 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007018 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007019 PatchBuilder patchBuilder;
7020 patchBuilder.addSource(outputDesc);
7021 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7022 for (const auto &filteredDevice : filteredDevices) {
7023 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007024 }
7025
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007026 // Add half reported latency to delayMs when muteWaitMs is null in order
7027 // to avoid disordered sequence of muting volume and changing devices.
7028 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7029 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007030 }
Eric Laurente552edb2014-03-10 17:42:56 -07007031
7032 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007033 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007034
7035 return muteWaitMs;
7036}
7037
Eric Laurentc75307b2015-03-17 15:29:32 -07007038status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007039 int delayMs,
7040 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007041{
Eric Laurent6a94d692014-05-20 11:18:06 -07007042 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007043 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7044 return INVALID_OPERATION;
7045 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007046 if (patchHandle) {
7047 index = mAudioPatches.indexOfKey(*patchHandle);
7048 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007049 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007050 }
7051 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007052 return INVALID_OPERATION;
7053 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007054 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007055 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007056 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007057 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007058 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007059 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007060 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007061 return status;
7062}
7063
7064status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007065 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007066 bool force,
7067 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007068{
7069 status_t status = NO_ERROR;
7070
Eric Laurent1f2f2232014-06-02 12:01:23 -07007071 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007072 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7073 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007074
François Gaffie11d30102018-11-02 16:09:09 +01007075 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007076 PatchBuilder patchBuilder;
7077 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007078 // AUDIO_SOURCE_HOTWORD is for internal use only:
7079 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007080 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7081 auto result = usecase;
7082 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7083 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7084 }
7085 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007086 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007087 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007088 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007089 }
7090 }
7091 return status;
7092}
7093
Eric Laurent6a94d692014-05-20 11:18:06 -07007094status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7095 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007096{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007097 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007098 ssize_t index;
7099 if (patchHandle) {
7100 index = mAudioPatches.indexOfKey(*patchHandle);
7101 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007102 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007103 }
7104 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007105 return INVALID_OPERATION;
7106 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007107 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007108 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007109 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007110 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007111 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007112 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007113 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007114 return status;
7115}
7116
François Gaffie11d30102018-11-02 16:09:09 +01007117sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007118 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007119 audio_format_t& format,
7120 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007121 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007122{
7123 // Choose an input profile based on the requested capture parameters: select the first available
7124 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007125 //
7126 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7127 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007128
Glenn Kasten730b9262018-03-29 15:01:26 -07007129 sp<IOProfile> firstInexact;
7130 uint32_t updatedSamplingRate = 0;
7131 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7132 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007133 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007134 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007135 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007136 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007137 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007138 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007139 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007140 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007141 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007142 &channelMask /*updatedChannelMask*/,
7143 // FIXME ugly cast
7144 (audio_output_flags_t) flags,
7145 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007146 return profile;
7147 }
François Gaffie11d30102018-11-02 16:09:09 +01007148 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007149 samplingRate,
7150 &updatedSamplingRate,
7151 format,
7152 &updatedFormat,
7153 channelMask,
7154 &updatedChannelMask,
7155 // FIXME ugly cast
7156 (audio_output_flags_t) flags,
7157 false /*exactMatchRequiredForInputFlags*/)) {
7158 firstInexact = profile;
7159 }
7160
Eric Laurente552edb2014-03-10 17:42:56 -07007161 }
7162 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007163 if (firstInexact != nullptr) {
7164 samplingRate = updatedSamplingRate;
7165 format = updatedFormat;
7166 channelMask = updatedChannelMask;
7167 return firstInexact;
7168 }
Eric Laurente552edb2014-03-10 17:42:56 -07007169 return NULL;
7170}
7171
François Gaffieaaac0fd2018-11-22 17:56:39 +01007172float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7173 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007174 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007175 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007176{
jiabin9a3361e2019-10-01 09:38:30 -07007177 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007178
7179 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7180 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7181 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7182 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007183 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7184 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7185 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7186 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7187 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007188
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007189 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007190 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7191 mOutputs.isActive(ringVolumeSrc, 0)) {
7192 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007193 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007194 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007195 }
7196
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007197 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007198 if ((volumeSource != callVolumeSrc && (isInCall() ||
7199 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007200 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007201 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7202 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007203 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7204 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7205 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007206 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007207 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007208 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007209 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007210 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007211 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007212 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7213 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7214 // programmatically muted.
7215 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7216 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7217 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007218 bool exemptFromCapping =
7219 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7220 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007221 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7222 volumeSource, volumeDb);
7223 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007224 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7225 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7226 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007227 }
7228 }
Eric Laurente552edb2014-03-10 17:42:56 -07007229 // if a headset is connected, apply the following rules to ring tones and notifications
7230 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007231 // - always attenuate notifications volume by 6dB
7232 // - attenuate ring tones volume by 6dB unless music is not playing and
7233 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007234 // - if music is playing, always limit the volume to current music volume,
7235 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007236 if (!Intersection(deviceTypes,
7237 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7238 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007239 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7240 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007241 ((volumeSource == alarmVolumeSrc ||
7242 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007243 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7244 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7245 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007246 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7247 curves.canBeMuted()) {
7248
Eric Laurente552edb2014-03-10 17:42:56 -07007249 // when the phone is ringing we must consider that music could have been paused just before
7250 // by the music application and behave as if music was active if the last music track was
7251 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007252 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007253 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007254 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007255 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007256 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7257 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007258 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007259 float musicVolDb = computeVolume(musicCurves,
7260 musicVolumeSrc,
7261 musicCurves.getVolumeIndex(musicDevice),
7262 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007263 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7264 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7265 if (volumeDb > minVolDb) {
7266 volumeDb = minVolDb;
7267 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007268 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007269 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7270 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7271 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007272 // on A2DP, also ensure notification volume is not too low compared to media when
7273 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007274 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007275 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007276 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7277 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007278 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7279 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007280 }
7281 }
jiabin9a3361e2019-10-01 09:38:30 -07007282 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007283 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007284 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007285 }
7286 }
7287
François Gaffie43c73442018-11-08 08:21:55 +01007288 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007289}
7290
Eric Laurent3839bc02018-07-10 18:33:34 -07007291int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007292 VolumeSource fromVolumeSource,
7293 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007294{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007295 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007296 return srcIndex;
7297 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007298 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7299 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007300 float minSrc = (float)srcCurves.getVolumeIndexMin();
7301 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7302 float minDst = (float)dstCurves.getVolumeIndexMin();
7303 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007304
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007305 // preserve mute request or correct range
7306 if (srcIndex < minSrc) {
7307 if (srcIndex == 0) {
7308 return 0;
7309 }
7310 srcIndex = minSrc;
7311 } else if (srcIndex > maxSrc) {
7312 srcIndex = maxSrc;
7313 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007314 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7315}
7316
François Gaffieaaac0fd2018-11-22 17:56:39 +01007317status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7318 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007319 int index,
7320 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007321 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007322 int delayMs,
7323 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007324{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007325 // do not change actual attributes volume if the attributes is muted
7326 if (outputDesc->isMuted(volumeSource)) {
7327 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7328 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007329 return NO_ERROR;
7330 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007331 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7332 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7333 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7334 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007335
Eric Laurent2517af32020-11-25 15:31:27 +01007336 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007337 bool isHAUsed = isHearingAidUsedForComm();
7338
Eric Laurente552edb2014-03-10 17:42:56 -07007339 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007340 // if sco and call follow same curves, bypass forceUseForComm
7341 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007342 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007343 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007344 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007345 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007346 // Do not return an error here as AudioService will always set both voice call
7347 // and bluetooth SCO volumes due to stream aliasing.
7348 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007349 }
jiabin9a3361e2019-10-01 09:38:30 -07007350 if (deviceTypes.empty()) {
7351 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007352 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007353
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007354 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7355 ALOGE("invalid volume index range");
7356 return BAD_VALUE;
7357 }
7358
jiabin9a3361e2019-10-01 09:38:30 -07007359 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7360 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007361 // Force VoIP volume to max for bluetooth SCO device except if muted
7362 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007363 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007364 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007365 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007366 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007367 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007368 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007369
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007370 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007371 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007372 // 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 +01007373 if (isVoiceVolSrc) {
7374 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007375 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007376 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007377 }
Eric Laurent18fba842016-03-31 14:41:26 -07007378 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007379 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7380 mLastVoiceVolume = voiceVolume;
7381 }
7382 }
Eric Laurente552edb2014-03-10 17:42:56 -07007383 return NO_ERROR;
7384}
7385
Eric Laurentc75307b2015-03-17 15:29:32 -07007386void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007387 const DeviceTypeSet& deviceTypes,
7388 int delayMs,
7389 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007390{
jiabincd510522020-01-22 09:40:55 -08007391 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007392 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7393 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7394 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007395 curves.getVolumeIndex(deviceTypes),
7396 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007397 }
7398}
7399
François Gaffiec005e562018-11-06 15:04:49 +01007400void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7401 bool on,
7402 const sp<AudioOutputDescriptor>& outputDesc,
7403 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007404 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007405{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007406 std::vector<VolumeSource> sourcesToMute;
7407 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7408 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7409 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007410 VolumeSource source = toVolumeSource(attributes, false);
7411 if ((source != VOLUME_SOURCE_NONE) &&
7412 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7413 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007414 sourcesToMute.push_back(source);
7415 }
Eric Laurente552edb2014-03-10 17:42:56 -07007416 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007417 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007418 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007419 }
7420
Eric Laurente552edb2014-03-10 17:42:56 -07007421}
7422
François Gaffieaaac0fd2018-11-22 17:56:39 +01007423void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7424 bool on,
7425 const sp<AudioOutputDescriptor>& outputDesc,
7426 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007427 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007428{
jiabin9a3361e2019-10-01 09:38:30 -07007429 if (deviceTypes.empty()) {
7430 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007431 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007432 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007433 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007434 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007435 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007436 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007437 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7438 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007439 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007440 }
7441 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007442 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7443 // ignored
7444 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007445 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007446 if (!outputDesc->isMuted(volumeSource)) {
7447 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007448 return;
7449 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007450 if (outputDesc->decMuteCount(volumeSource) == 0) {
7451 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007452 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007453 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007454 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007455 delayMs);
7456 }
7457 }
7458}
7459
François Gaffie53615e22015-03-19 09:24:12 +01007460bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7461{
François Gaffiec005e562018-11-06 15:04:49 +01007462 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007463 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7464 return true;
7465 }
7466
7467 // has known usage?
7468 switch (paa->usage) {
7469 case AUDIO_USAGE_UNKNOWN:
7470 case AUDIO_USAGE_MEDIA:
7471 case AUDIO_USAGE_VOICE_COMMUNICATION:
7472 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7473 case AUDIO_USAGE_ALARM:
7474 case AUDIO_USAGE_NOTIFICATION:
7475 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7476 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7477 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7478 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7479 case AUDIO_USAGE_NOTIFICATION_EVENT:
7480 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7481 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7482 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7483 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007484 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007485 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007486 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007487 case AUDIO_USAGE_EMERGENCY:
7488 case AUDIO_USAGE_SAFETY:
7489 case AUDIO_USAGE_VEHICLE_STATUS:
7490 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007491 break;
7492 default:
7493 return false;
7494 }
7495 return true;
7496}
7497
François Gaffie2110e042015-03-24 08:41:51 +01007498audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7499{
7500 return mEngine->getForceUse(usage);
7501}
7502
Eric Laurent96d1dda2022-03-14 17:14:19 +01007503bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007504 return isStateInCall(mEngine->getPhoneState());
7505}
7506
Eric Laurent96d1dda2022-03-14 17:14:19 +01007507bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007508 return is_state_in_call(state);
7509}
7510
Eric Laurent74b71512019-11-06 17:21:57 -08007511bool AudioPolicyManager::isCallAudioAccessible()
7512{
7513 audio_mode_t mode = mEngine->getPhoneState();
7514 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007515 || (mode == AUDIO_MODE_CALL_SCREEN)
7516 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007517}
7518
Eric Laurentd60560a2015-04-10 11:31:20 -07007519void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7520{
7521 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007522 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007523 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007524 sourceDesc->sinkDevice()->equals(deviceDesc))
7525 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007526 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007527 }
7528 }
7529
7530 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7531 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7532 bool release = false;
7533 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7534 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7535 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7536 source->ext.device.type == deviceDesc->type()) {
7537 release = true;
7538 }
7539 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007540 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007541 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7542 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7543 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007544 sink->ext.device.type == deviceDesc->type() &&
7545 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7546 || strncmp(sink->ext.device.address, address,
7547 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007548 release = true;
7549 }
7550 }
7551 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007552 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7553 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007554 }
7555 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007556
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007557 mInputs.clearSessionRoutesForDevice(deviceDesc);
7558
Francois Gaffie716e1432019-01-14 16:58:59 +01007559 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007560}
7561
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007562void AudioPolicyManager::modifySurroundFormats(
7563 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007564 std::unordered_set<audio_format_t> enforcedSurround(
7565 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007566 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7567 for (const auto& pair : mConfig.getSurroundFormats()) {
7568 allSurround.insert(pair.first);
7569 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7570 }
Phil Burk09bc4612016-02-24 15:58:15 -08007571
7572 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7573 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007574 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007575 // This is the resulting set of formats depending on the surround mode:
7576 // 'all surround' = allSurround
7577 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7578 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7579 // 'manual surround' = mManualSurroundFormats
7580 // AUTO: formats v 'enforced surround'
7581 // ALWAYS: formats v 'all surround' v 'enforced surround'
7582 // NEVER: formats ^ 'non-surround'
7583 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007584
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007585 std::unordered_set<audio_format_t> formatSet;
7586 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7587 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007588 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007589 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007590 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007591 formatSet.insert(*formatIter);
7592 }
7593 }
7594 } else {
7595 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7596 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007597 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007598
jiabin81772902018-04-02 17:52:27 -07007599 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007600 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007601 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7602 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7603 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007604 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007605 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7606 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7607 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007608 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007609 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007610 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007611 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007612 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007613 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007614}
7615
jiabin06e4bab2019-07-29 10:13:34 -07007616void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7617 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007618 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7619 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7620
7621 // If NEVER, then remove support for channelMasks > stereo.
7622 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007623 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7624 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007625 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007626 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007627 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007628 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007629 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007630 }
7631 }
jiabin81772902018-04-02 17:52:27 -07007632 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7633 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7634 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007635 bool supports5dot1 = false;
7636 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007637 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007638 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7639 supports5dot1 = true;
7640 break;
7641 }
7642 }
7643 // If not then add 5.1 support.
7644 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007645 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007646 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007647 }
Phil Burk09bc4612016-02-24 15:58:15 -08007648 }
7649}
7650
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007651void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007652 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007653 AudioProfileVector &profiles)
7654{
7655 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007656 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007657
François Gaffie112b0af2015-11-19 16:13:25 +01007658 // Format MUST be checked first to update the list of AudioProfile
7659 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007660 reply = mpClientInterface->getParameters(
7661 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007662 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007663 AudioParameter repliedParameters(reply);
7664 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007665 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007666 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7667 return;
7668 }
Phil Burk09bc4612016-02-24 15:58:15 -08007669 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007670 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007671 if (device == AUDIO_DEVICE_OUT_HDMI
7672 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007673 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007674 }
jiabin3e277cc2019-09-10 14:27:34 -07007675 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007676 }
François Gaffie112b0af2015-11-19 16:13:25 +01007677
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007678 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007679 ChannelMaskSet channelMasks;
7680 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007681 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007682 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007683
7684 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007685 reply = mpClientInterface->getParameters(
7686 ioHandle,
7687 requestedParameters.toString() + ";" +
7688 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007689 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007690 AudioParameter repliedParameters(reply);
7691 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007692 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007693 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007694 }
7695 }
7696 if (profiles.hasDynamicChannelsFor(format)) {
7697 reply = mpClientInterface->getParameters(ioHandle,
7698 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007699 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007700 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007701 AudioParameter repliedParameters(reply);
7702 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007703 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007704 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007705 if (device == AUDIO_DEVICE_OUT_HDMI
7706 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007707 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007708 }
François Gaffie112b0af2015-11-19 16:13:25 +01007709 }
7710 }
jiabin3e277cc2019-09-10 14:27:34 -07007711 addDynamicAudioProfileAndSort(
7712 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007713 }
7714}
Eric Laurentd60560a2015-04-10 11:31:20 -07007715
Mikhail Naganovdc769682018-05-04 15:34:08 -07007716status_t AudioPolicyManager::installPatch(const char *caller,
7717 audio_patch_handle_t *patchHandle,
7718 AudioIODescriptorInterface *ioDescriptor,
7719 const struct audio_patch *patch,
7720 int delayMs)
7721{
7722 ssize_t index = mAudioPatches.indexOfKey(
7723 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7724 *patchHandle : ioDescriptor->getPatchHandle());
7725 sp<AudioPatch> patchDesc;
7726 status_t status = installPatch(
7727 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7728 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007729 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007730 }
7731 return status;
7732}
7733
7734status_t AudioPolicyManager::installPatch(const char *caller,
7735 ssize_t index,
7736 audio_patch_handle_t *patchHandle,
7737 const struct audio_patch *patch,
7738 int delayMs,
7739 uid_t uid,
7740 sp<AudioPatch> *patchDescPtr)
7741{
7742 sp<AudioPatch> patchDesc;
7743 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7744 if (index >= 0) {
7745 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007746 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007747 }
7748
7749 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7750 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7751 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7752 if (status == NO_ERROR) {
7753 if (index < 0) {
7754 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007755 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007756 } else {
7757 patchDesc->mPatch = *patch;
7758 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007759 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007760 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007761 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007762 }
7763 nextAudioPortGeneration();
7764 mpClientInterface->onAudioPatchListUpdate();
7765 }
7766 if (patchDescPtr) *patchDescPtr = patchDesc;
7767 return status;
7768}
7769
jiabinbce0c1d2020-10-05 11:20:18 -07007770bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7771{
7772 const TrackClientVector activeClients = output->getActiveClients();
7773 if (activeClients.empty()) {
7774 return true;
7775 }
7776 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7777 if (index < 0) {
7778 ALOGE("%s, no audio patch found while there are active clients on output %d",
7779 __func__, output->getId());
7780 return false;
7781 }
7782 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7783 DeviceVector routedDevices;
7784 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7785 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7786 patchDesc->mPatch.sinks[i].id);
7787 if (device == nullptr) {
7788 ALOGE("%s, no audio device found with id(%d)",
7789 __func__, patchDesc->mPatch.sinks[i].id);
7790 return false;
7791 }
7792 routedDevices.add(device);
7793 }
7794 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007795 if (client->isInvalid()) {
7796 // No need to take care about invalidated clients.
7797 continue;
7798 }
jiabinbce0c1d2020-10-05 11:20:18 -07007799 sp<DeviceDescriptor> preferredDevice =
7800 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7801 if (mEngine->getOutputDevicesForAttributes(
7802 client->attributes(), preferredDevice, false) == routedDevices) {
7803 return false;
7804 }
7805 }
7806 return true;
7807}
7808
7809sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007810 const sp<IOProfile>& profile, const DeviceVector& devices,
7811 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007812{
7813 for (const auto& device : devices) {
7814 // TODO: This should be checking if the profile supports the device combo.
7815 if (!profile->supportsDevice(device)) {
7816 return nullptr;
7817 }
7818 }
7819 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7820 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007821 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007822 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7823 if (status != NO_ERROR) {
7824 return nullptr;
7825 }
7826
7827 // Here is where the out_set_parameters() for card & device gets called
7828 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7829 const audio_devices_t deviceType = device->type();
7830 const String8 &address = String8(device->address().c_str());
7831 if (!address.isEmpty()) {
7832 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7833 mpClientInterface->setParameters(output, String8(param));
7834 free(param);
7835 }
7836 updateAudioProfiles(device, output, profile->getAudioProfiles());
7837 if (!profile->hasValidAudioProfile()) {
7838 ALOGW("%s() missing param", __func__);
7839 desc->close();
7840 return nullptr;
7841 } else if (profile->hasDynamicAudioProfile()) {
7842 desc->close();
7843 output = AUDIO_IO_HANDLE_NONE;
7844 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7845 profile->pickAudioProfile(
7846 config.sample_rate, config.channel_mask, config.format);
7847 config.offload_info.sample_rate = config.sample_rate;
7848 config.offload_info.channel_mask = config.channel_mask;
7849 config.offload_info.format = config.format;
7850
Eric Laurentb4f42a92022-01-17 17:37:31 +01007851 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007852 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7853 if (status != NO_ERROR) {
7854 return nullptr;
7855 }
7856 }
7857
7858 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007859
jiabinbce0c1d2020-10-05 11:20:18 -07007860 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7861 sp<AudioPolicyMix> policyMix;
7862 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7863 policyMix->setOutput(desc);
7864 desc->mPolicyMix = policyMix;
7865 } else {
7866 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7867 address.string());
7868 }
7869
Eric Laurentb4f42a92022-01-17 17:37:31 +01007870 } else if (hasPrimaryOutput() && profile->getModule()
7871 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7872 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7873 // no duplicated output for:
7874 // - direct outputs
7875 // - outputs used by dynamic policy mixes
7876 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007877 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7878
7879 //TODO: configure audio effect output stage here
7880
7881 // open a duplicating output thread for the new output and the primary output
7882 sp<SwAudioOutputDescriptor> dupOutputDesc =
7883 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7884 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7885 if (status == NO_ERROR) {
7886 // add duplicated output descriptor
7887 addOutput(duplicatedOutput, dupOutputDesc);
7888 } else {
7889 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7890 mPrimaryOutput->mIoHandle, output);
7891 desc->close();
7892 removeOutput(output);
7893 nextAudioPortGeneration();
7894 return nullptr;
7895 }
7896 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007897 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7898 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7899 mPrimaryOutput = desc;
7900 }
jiabinbce0c1d2020-10-05 11:20:18 -07007901 return desc;
7902}
7903
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007904} // namespace android