blob: fb59211fcd6cd37b8b0e1d505f6dcba27ac66585 [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 Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100211 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Paul McLeane743a472015-01-28 11:07:31 -0800240 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100241 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100244 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100246 mOutputs.clearSessionRoutesForDevice(device);
247
François Gaffie11d30102018-11-02 16:09:09 +0100248 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100249
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800250 // Reset active device codec
251 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
252
Kriti Dangef6be8f2020-11-05 11:58:19 +0100253 // remove device from mReportedFormatsMap cache
254 mReportedFormatsMap.erase(device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200290 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200292 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent72aa32f2014-05-30 18:51:48 -0700356 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700357 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700358 } // end if is output device
359
Eric Laurente552edb2014-03-10 17:42:56 -0700360 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700361 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100362 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 switch (state)
364 {
365 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100368 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return INVALID_OPERATION;
370 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700371
372 if (mAvailableInputDevices.add(device) < 0) {
373 return NO_MEMORY;
374 }
375
François Gaffie44481e72016-04-20 07:49:57 +0200376 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
377 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100378 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 if (checkInputsForDevice(device, state) != NO_ERROR) {
381 mAvailableInputDevices.remove(device);
382
François Gaffie11d30102018-11-02 16:09:09 +0100383 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100384
385 mHwModules.cleanUpForDevice(device);
386
Eric Laurentd4692962014-05-05 18:13:44 -0700387 return INVALID_OPERATION;
388 }
389
Eric Laurentd4692962014-05-05 18:13:44 -0700390 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700391
392 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
François Gaffie11d30102018-11-02 16:09:09 +0100399 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
401 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100402 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700405
406 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100407
408 // remove device from mReportedFormatsMap cache
409 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 default:
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return BAD_VALUE;
415 }
416
Eric Laurent736a1022019-03-27 18:28:46 -0700417 // Propagate device availability to Engine
418 setEngineDeviceConnectionState(device, state);
419
Eric Laurent0dd51852019-04-19 18:18:58 -0700420 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700421 // As the input device list can impact the output device selection, update
422 // getDeviceForStrategy() cache
423 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700424
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100425 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200426 // Reconnect Audio Source
427 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
428 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
429 checkAudioSourceForAttributes(attributes);
430 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700431 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100432 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 }
434
Eric Laurentb52c1522014-05-20 11:27:36 -0700435 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700437 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700440 return BAD_VALUE;
441}
442
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100443status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
444 const char* device_name,
445 media::AudioPort* aidlPort) {
446 DeviceDescriptorBase devDescr(device, device_address);
447 devDescr.setName(device_name);
448 return devDescr.writeToParcelable(aidlPort);
449}
450
Eric Laurent736a1022019-03-27 18:28:46 -0700451void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
452 audio_policy_dev_state_t state) {
453
454 // the Engine does not have to know about remote submix devices used by dynamic audio policies
455 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
456 return;
457 }
458 mEngine->setDeviceConnectionState(device, state);
459}
460
461
Eric Laurente0720872014-03-11 09:30:41 -0700462audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100463 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700464{
Eric Laurent634b7142016-04-20 13:48:02 -0700465 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
467 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700468 (strlen(device_address) != 0)/*matchAddress*/);
469
470 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100471 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700472 device, device_address);
473 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
474 }
François Gaffie53615e22015-03-19 09:24:12 +0100475
Eric Laurent3a4311c2014-03-17 12:00:47 -0700476 DeviceVector *deviceVector;
477
Eric Laurente552edb2014-03-10 17:42:56 -0700478 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700479 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700480 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableInputDevices;
482 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100483 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700485 }
Eric Laurent634b7142016-04-20 13:48:02 -0700486
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800487 return (deviceVector->getDevice(
488 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700489 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800490}
491
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800492status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
493 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 const char *device_name,
495 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800496{
497 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700498 String8 reply;
499 AudioParameter param;
500 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
503 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800505 // connect/disconnect only 1 device at a time
506 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700509 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511 // Nothing to do: device is not connected
512 return NO_ERROR;
513 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700516 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 // configure codecs.
518 // Handle two specific cases by sending a set parameter to
519 // configure A2DP codecs. No need to toggle device state.
520 // Case 1: A2DP active device switches from primary to primary
521 // module
522 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200523 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700524 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
526 if (availablePrimaryOutputDevices().contains(devDesc) &&
527 (module != 0 && module->getHandle() == primaryHandle)) {
528 reply = mpClientInterface->getParameters(
529 AUDIO_IO_HANDLE_NONE,
530 String8(AudioParameter::keyReconfigA2dpSupported));
531 AudioParameter repliedParameters(reply);
532 repliedParameters.getInt(
533 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
534 if (isReconfigA2dpSupported) {
535 const String8 key(AudioParameter::keyReconfigA2dp);
536 param.add(key, String8("true"));
537 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
538 devDesc->setEncodedFormat(encodedFormat);
539 return NO_ERROR;
540 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700541 }
542 }
cnx421bd2dcc42020-07-11 14:58:44 +0800543 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
544 for (size_t i = 0; i < mOutputs.size(); i++) {
545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
546 // mute media strategies and delay device switch by the largest
547 // This avoid sending the music tail into the earpiece or headset.
548 setStrategyMute(musicStrategy, true, desc);
549 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
550 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
551 nullptr, true /*fromCache*/).types());
552 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800553 // Toggle the device state: UNAVAILABLE -> AVAILABLE
554 // This will force reading again the device configuration
555 status = setDeviceConnectionState(device,
556 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 device_address, device_name,
558 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800559 if (status != NO_ERROR) {
560 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
561 status);
562 return status;
563 }
564
565 status = setDeviceConnectionState(device,
566 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
570 status);
571 return status;
572 }
573
574 return NO_ERROR;
575}
576
Pattydd807582021-11-04 21:01:03 +0800577status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
578 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800579{
Pattydd807582021-11-04 21:01:03 +0800580 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800582 std::unordered_set<audio_format_t> formatSet;
583 sp<HwModule> primaryModule =
584 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700585 if (primaryModule == nullptr) {
586 ALOGE("%s() unable to get primary module", __func__);
587 return NO_INIT;
588 }
Pattydd807582021-11-04 21:01:03 +0800589
590 DeviceTypeSet audioDeviceSet;
591
592 switch(device) {
593 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
594 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
595 break;
596 case AUDIO_DEVICE_OUT_BLE_HEADSET:
597 audioDeviceSet = getAudioDeviceOutAllBleSet();
598 break;
599 default:
600 ALOGE("%s() device type 0x%08x not supported", __func__, device);
601 return BAD_VALUE;
602 }
603
jiabin9a3361e2019-10-01 09:38:30 -0700604 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800605 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800606 for (const auto& device : declaredDevices) {
607 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800608 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800609 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800610 return status;
611}
612
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
614{
615 DeviceVector rxSinkdevices{};
616 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
617 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
618 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
619 auto rxSinkDevice = rxSinkdevices.itemAt(0);
620 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
621 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
622 // retrieve Rx Source device descriptor
623 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
624 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
625
626 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
627 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
628 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
629 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
630 return DeviceVector(rxSinkDevice);
631 }
632 }
633 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
634 // the device returned is not necessarily reachable via this output
635 // (filter later by setOutputDevices())
636 return getNewOutputDevices(mPrimaryOutput, fromCache);
637}
638
639status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
640{
641 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
642 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
643 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
644 }
645 return INVALID_OPERATION;
646}
647
648status_t AudioPolicyManager::updateCallRoutingInternal(
649 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700650{
651 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100652 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700653 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700654 if(!hasPrimaryOutput() ||
655 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100656 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700657 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100659
Francois Gaffie716e1432019-01-14 16:58:59 +0100660 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100661 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100663
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100665 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200667 disconnectTelephonyAudioSource(mCallRxSourceClientPort);
668 disconnectTelephonyAudioSource(mCallTxSourceClientPort);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669
François Gaffie9eb18552018-11-05 10:33:26 +0100670 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700671 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100672 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700673 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100674 // retrieve Rx Source and Tx Sink device descriptors
675 sp<DeviceDescriptor> rxSourceDevice =
676 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
677 String8(),
678 AUDIO_FORMAT_DEFAULT);
679 sp<DeviceDescriptor> txSinkDevice =
680 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
681 String8(),
682 AUDIO_FORMAT_DEFAULT);
683
684 // RX and TX Telephony device are declared by Primary Audio HAL
685 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
686 (telephonyRxModule->getHalVersionMajor() >= 3)) {
687 if (rxSourceDevice == 0 || txSinkDevice == 0) {
688 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100689 ALOGE("%s() no telephony Tx and/or RX device", __func__);
690 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100691 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100692 // createAudioPatchInternal now supports both HW / SW bridging
693 createRxPatch = true;
694 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100695 } else {
696 // If the RX device is on the primary HW module, then use legacy routing method for
697 // voice calls via setOutputDevice() on primary output.
698 // Otherwise, create two audio patches for TX and RX path.
699 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
700 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700701 // If the TX device is also on the primary HW module, setOutputDevice() will take care
702 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100703 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
704 (txSinkDevice != 0);
705 }
706 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
707 // Otherwise, create two audio patches for TX and RX path.
708 if (!createRxPatch) {
709 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700710 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200711 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800712 // If the TX device is on the primary HW module but RX device is
713 // on other HW module, SinkMetaData of telephony input should handle it
714 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700715 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700716 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100717 // terminate active capture if on the same HW module as the call TX source device
718 // FIXME: would be better to refine to only inputs whose profile connects to the
719 // call TX device but this information is not in the audio patch and logic here must be
720 // symmetric to the one in startInput()
721 for (const auto& activeDesc : mInputs.getActiveInputs()) {
722 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
723 closeActiveClients(activeDesc);
724 }
725 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200726 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800727 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100728 if (waitMs != nullptr) {
729 *waitMs = muteWaitMs;
730 }
731 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800732}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733
Mikhail Naganov100f0122018-11-29 11:22:16 -0800734bool AudioPolicyManager::isDeviceOfModule(
735 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
736 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
737 if (module != 0) {
738 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
739 .indexOf(devDesc) != NAME_NOT_FOUND
740 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
741 .indexOf(devDesc) != NAME_NOT_FOUND;
742 }
743 return false;
744}
745
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200746void AudioPolicyManager::connectTelephonyRxAudioSource()
747{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200748 disconnectTelephonyAudioSource(mCallRxSourceClientPort);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200749 const struct audio_port_config source = {
750 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
751 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
752 };
753 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
754 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
755 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
756}
757
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200758void AudioPolicyManager::disconnectTelephonyAudioSource(audio_port_handle_t &portHandle)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200759{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200760 stopAudioSource(portHandle);
761 portHandle = AUDIO_PORT_HANDLE_NONE;
762}
763
764void AudioPolicyManager::connectTelephonyTxAudioSource(
765 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
766 uint32_t delayMs)
767{
768 disconnectTelephonyAudioSource(mCallTxSourceClientPort);
769 if (srcDevice == nullptr || sinkDevice == nullptr) {
770 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
771 return;
772 }
773 PatchBuilder patchBuilder;
774 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
775 ALOGV("%s between source %s and sink %s", __func__,
776 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
777 mCallTxSourceClientPort = PolicyAudioPort::getNextUniqueId();
778 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
779 struct audio_port_config source = {};
780 srcDevice->toAudioPortConfig(&source);
781 sp<SourceClientDescriptor> sourceDesc = new InternalSourceClientDescriptor(
782 mCallTxSourceClientPort, mUidCached, aa, source, srcDevice, sinkDevice,
783 mCommunnicationStrategy, toVolumeSource(aa));
784 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
785 status_t status = connectAudioSourceToSink(
786 sourceDesc, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached, delayMs);
787 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
788 if (status == NO_ERROR) {
789 mAudioSources.add(mCallTxSourceClientPort, sourceDesc);
790 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200791}
792
Eric Laurente0720872014-03-11 09:30:41 -0700793void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700794{
795 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100796 // store previous phone state for management of sonification strategy below
797 int oldState = mEngine->getPhoneState();
798
799 if (mEngine->setPhoneState(state) != NO_ERROR) {
800 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700801 return;
802 }
François Gaffie2110e042015-03-24 08:41:51 +0100803 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700804 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700805 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700806 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800807 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700808 }
809
François Gaffie2110e042015-03-24 08:41:51 +0100810 /**
811 * Switching to or from incall state or switching between telephony and VoIP lead to force
812 * routing command.
813 */
Eric Laurent74b71512019-11-06 17:21:57 -0800814 bool force = ((isStateInCall(oldState) != isStateInCall(state))
815 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700816
817 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700818 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700819
Eric Laurente552edb2014-03-10 17:42:56 -0700820 int delayMs = 0;
821 if (isStateInCall(state)) {
822 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100823 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
824 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700825 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700826 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 // mute media and sonification strategies and delay device switch by the largest
828 // latency of any output where either strategy is active.
829 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100830 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
831 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
832 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700833 (delayMs < (int)desc->latency()*2)) {
834 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700835 }
François Gaffiec005e562018-11-06 15:04:49 +0100836 setStrategyMute(musicStrategy, true, desc);
837 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
838 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
839 nullptr, true /*fromCache*/).types());
840 setStrategyMute(sonificationStrategy, true, desc);
841 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
842 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
843 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700844 }
845 }
846
Eric Laurent87ffa392015-05-22 10:32:38 -0700847 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700848 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100849 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700850 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100851 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
852 // force routing command to audio hardware when ending call
853 // even if no device change is needed
854 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
855 rxDevices = mPrimaryOutput->devices();
856 }
857 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200858 disconnectTelephonyAudioSource(mCallRxSourceClientPort);
859 disconnectTelephonyAudioSource(mCallTxSourceClientPort);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100860 }
François Gaffie11d30102018-11-02 16:09:09 +0100861 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700862 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700863 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700864
865 // reevaluate routing on all outputs in case tracks have been started during the call
866 for (size_t i = 0; i < mOutputs.size(); i++) {
867 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100868 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700869 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100870 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700871 }
872 }
873
Eric Laurente552edb2014-03-10 17:42:56 -0700874 if (isStateInCall(state)) {
875 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700876 // force reevaluating accessibility routing when call starts
877 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700878 }
879
880 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100881 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
882 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700883}
884
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700885audio_mode_t AudioPolicyManager::getPhoneState() {
886 return mEngine->getPhoneState();
887}
888
Eric Laurente0720872014-03-11 09:30:41 -0700889void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100890 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700891{
François Gaffie2110e042015-03-24 08:41:51 +0100892 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700893 if (config == mEngine->getForceUse(usage)) {
894 return;
895 }
Eric Laurente552edb2014-03-10 17:42:56 -0700896
François Gaffie2110e042015-03-24 08:41:51 +0100897 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
898 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
899 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700900 }
François Gaffie2110e042015-03-24 08:41:51 +0100901 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
902 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
903 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700904
905 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700906 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800907
Eric Laurent22fcda22019-05-17 16:28:47 -0700908 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
909 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
910 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
911 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
912 }
913
Eric Laurentdc462862016-07-19 12:29:53 -0700914 //FIXME: workaround for truncated touch sounds
915 // to be removed when the problem is handled by system UI
916 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700917 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
918 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
919 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700920
921 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100922 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700923}
924
Eric Laurente0720872014-03-11 09:30:41 -0700925void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700926{
927 ALOGV("setSystemProperty() property %s, value %s", property, value);
928}
929
Michael Chana94fbb22018-04-24 14:31:19 +1000930// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
931// search to profiles for direct outputs.
932sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100933 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000934 uint32_t samplingRate,
935 audio_format_t format,
936 audio_channel_mask_t channelMask,
937 audio_output_flags_t flags,
938 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700939{
Michael Chana94fbb22018-04-24 14:31:19 +1000940 if (directOnly) {
941 // only retain flags that will drive the direct output profile selection
942 // if explicitly requested
943 static const uint32_t kRelevantFlags =
944 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700945 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000946 flags =
947 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
948 }
Eric Laurent861a6282015-05-18 15:40:16 -0700949
950 sp<IOProfile> profile;
951
Mikhail Naganovd4120142017-12-06 15:49:22 -0800952 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800953 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100954 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700955 samplingRate, NULL /*updatedSamplingRate*/,
956 format, NULL /*updatedFormat*/,
957 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700958 flags)) {
959 continue;
960 }
961 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100962 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700963 continue;
964 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800965 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700966 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800967 continue;
968 }
Michael Chana94fbb22018-04-24 14:31:19 +1000969 if (!directOnly) return curProfile;
970 // when searching for direct outputs, if several profiles are compatible, give priority
971 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100972 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700973 continue;
974 }
975 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100976 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700977 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700978 }
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
980 }
Eric Laurent861a6282015-05-18 15:40:16 -0700981 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700982}
983
Eric Laurentfa0f6742021-08-17 18:39:44 +0200984sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200985 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200986{
987 for (const auto& hwModule : mHwModules) {
988 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200989 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200990 continue;
991 }
992 // reject profiles not corresponding to a device currently available
993 DeviceVector supportedDevices = curProfile->getSupportedDevices();
994 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
995 continue;
996 }
997 if (!devices.empty()) {
998 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
999 != devices.size()) {
1000 continue;
1001 }
1002 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001003 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1004 return curProfile;
1005 }
1006 }
1007 return nullptr;
1008}
1009
Eric Laurentf4e63452017-11-06 19:31:46 +00001010audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001011{
François Gaffiec005e562018-11-06 15:04:49 +01001012 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001013
1014 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1015 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1016 // format, flags, etc. This may result in some discrepancy for functions that utilize
1017 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1018 // and AudioSystem::getOutputSamplingRate().
1019
François Gaffie11d30102018-11-02 16:09:09 +01001020 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001021 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001022
François Gaffie11d30102018-11-02 16:09:09 +01001023 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1024 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001025 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001026}
1027
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001028status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1029 const audio_attributes_t *srcAttr,
1030 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001031{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001032 if (srcAttr != NULL) {
1033 if (!isValidAttributes(srcAttr)) {
1034 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1035 __func__,
1036 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1037 srcAttr->tags);
1038 return BAD_VALUE;
1039 }
1040 *dstAttr = *srcAttr;
1041 } else {
1042 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1043 ALOGE("%s: invalid stream type", __func__);
1044 return BAD_VALUE;
1045 }
François Gaffiec005e562018-11-06 15:04:49 +01001046 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001047 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001048
1049 // Only honor audibility enforced when required. The client will be
1050 // forced to reconnect if the forced usage changes.
1051 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001052 dstAttr->flags = static_cast<audio_flags_mask_t>(
1053 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001054 }
1055
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001056 return NO_ERROR;
1057}
1058
Kevin Rocard153f92d2018-12-18 18:33:28 -08001059status_t AudioPolicyManager::getOutputForAttrInt(
1060 audio_attributes_t *resultAttr,
1061 audio_io_handle_t *output,
1062 audio_session_t session,
1063 const audio_attributes_t *attr,
1064 audio_stream_type_t *stream,
1065 uid_t uid,
1066 const audio_config_t *config,
1067 audio_output_flags_t *flags,
1068 audio_port_handle_t *selectedDeviceId,
1069 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001070 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001071 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001072{
François Gaffiec005e562018-11-06 15:04:49 +01001073 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001074 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001075 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001076 const sp<DeviceDescriptor> requestedDevice =
1077 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1078
Eric Laurent8a1095a2019-11-08 14:44:16 -08001079 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001080 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1081 if (status != NO_ERROR) {
1082 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001083 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001084 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001085 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001086 }
François Gaffiec005e562018-11-06 15:04:49 +01001087 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001088
François Gaffiec005e562018-11-06 15:04:49 +01001089 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1090 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001091
Kevin Rocard153f92d2018-12-18 18:33:28 -08001092 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1093 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1094 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001095 sp<AudioPolicyMix> primaryMix;
1096 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001097 if (status != OK) {
1098 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001099 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001100
Kevin Rocard153f92d2018-12-18 18:33:28 -08001101 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001102 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001103
1104 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001105 if ((usePrimaryOutputFromPolicyMixes
1106 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001107 && !audio_is_linear_pcm(config->format)) {
1108 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001109 return BAD_VALUE;
1110 }
1111 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001112 sp<DeviceDescriptor> deviceDesc =
1113 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1114 primaryMix->mDeviceAddress,
1115 AUDIO_FORMAT_DEFAULT);
1116 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001117 if (deviceDesc != nullptr
1118 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001119 audio_io_handle_t newOutput;
1120 status = openDirectOutput(
1121 *stream, session, config,
1122 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1123 DeviceVector(deviceDesc), &newOutput);
1124 if (status != NO_ERROR) {
1125 policyDesc = nullptr;
1126 } else {
1127 policyDesc = mOutputs.valueFor(newOutput);
1128 primaryMix->setOutput(policyDesc);
1129 }
1130 }
1131 if (policyDesc != nullptr) {
1132 policyDesc->mPolicyMix = primaryMix;
1133 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001134 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001135
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001136 ALOGV("getOutputForAttr() returns output %d", *output);
1137 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1138 *outputType = API_OUT_MIX_PLAYBACK;
1139 } else {
1140 *outputType = API_OUTPUT_LEGACY;
1141 }
1142 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001143 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001144 }
François Gaffiec005e562018-11-06 15:04:49 +01001145 // Virtual sources must always be dynamicaly or explicitly routed
1146 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1147 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1148 return BAD_VALUE;
1149 }
1150 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1151 // in order to let the choice of the order to future vendor engine
1152 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001153
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001154 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001155 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001156 }
1157
Nadav Barb2f18162018-07-18 13:01:53 +03001158 // Set incall music only if device was explicitly set, and fallback to the device which is
1159 // chosen by the engine if not.
1160 // FIXME: provide a more generic approach which is not device specific and move this back
1161 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001162 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001163 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001164 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001165 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001166 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001167 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001168 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001169 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001170 }
1171 }
1172
François Gaffiec005e562018-11-06 15:04:49 +01001173 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1174 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1175 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001176
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001177 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001178 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001179 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001180 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001181 ALOGV("%s() Using MSD devices %s instead of devices %s",
1182 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001183 } else {
1184 *output = AUDIO_IO_HANDLE_NONE;
1185 }
1186 }
1187 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001188 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001189 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001190 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001191 if (*output == AUDIO_IO_HANDLE_NONE) {
1192 return INVALID_OPERATION;
1193 }
Paul McLeanaa981192015-03-21 09:55:15 -07001194
François Gaffiec005e562018-11-06 15:04:49 +01001195 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001196 for (auto &outputDevice : outputDevices) {
1197 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1198 *selectedDeviceId = outputDevice->getId();
1199 break;
1200 }
1201 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001202
Eric Laurent8a1095a2019-11-08 14:44:16 -08001203 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1204 *outputType = API_OUTPUT_TELEPHONY_TX;
1205 } else {
1206 *outputType = API_OUTPUT_LEGACY;
1207 }
1208
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001209 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1210
1211 return NO_ERROR;
1212}
1213
1214status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1215 audio_io_handle_t *output,
1216 audio_session_t session,
1217 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001218 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001219 const audio_config_t *config,
1220 audio_output_flags_t *flags,
1221 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001222 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001223 std::vector<audio_io_handle_t> *secondaryOutputs,
1224 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225{
1226 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1227 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1228 return INVALID_OPERATION;
1229 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001230 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001231 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001232 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001233 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001234 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001235 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001236 const sp<DeviceDescriptor> requestedDevice =
1237 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1238
1239 // Prevent from storing invalid requested device id in clients
1240 const audio_port_handle_t sanitizedRequestedPortId =
1241 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1242 *selectedDeviceId = sanitizedRequestedPortId;
1243
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001245 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001246 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001247 if (status != NO_ERROR) {
1248 return status;
1249 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001250 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001251 if (secondaryOutputs != nullptr) {
1252 for (auto &secondaryMix : secondaryMixes) {
1253 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1254 if (outputDesc != nullptr &&
1255 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1256 secondaryOutputs->push_back(outputDesc->mIoHandle);
1257 weakSecondaryOutputDescs.push_back(outputDesc);
1258 }
1259 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001260 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001261
Eric Laurent8fc147b2018-07-22 19:13:55 -07001262 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001263 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001264 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001265 };
jiabin4ef93452019-09-10 14:29:54 -07001266 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001267
Eric Laurentc209fe42020-06-05 18:11:23 -07001268 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001269 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001270 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001271 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001272 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001273 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001274 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001275 std::move(weakSecondaryOutputDescs),
1276 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001277 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001278
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001279 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1280 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001281
Eric Laurente83b55d2014-11-14 10:06:21 -08001282 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001283}
1284
Eric Laurentc529cf62020-04-17 18:19:10 -07001285status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1286 audio_session_t session,
1287 const audio_config_t *config,
1288 audio_output_flags_t flags,
1289 const DeviceVector &devices,
1290 audio_io_handle_t *output) {
1291
1292 *output = AUDIO_IO_HANDLE_NONE;
1293
1294 // skip direct output selection if the request can obviously be attached to a mixed output
1295 // and not explicitly requested
1296 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1297 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1298 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1299 return NAME_NOT_FOUND;
1300 }
1301
1302 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1303 // This prevents creating an offloaded track and tearing it down immediately after start
1304 // when audioflinger detects there is an active non offloadable effect.
1305 // FIXME: We should check the audio session here but we do not have it in this context.
1306 // This may prevent offloading in rare situations where effects are left active by apps
1307 // in the background.
1308 sp<IOProfile> profile;
1309 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1310 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1311 profile = getProfileForOutput(
1312 devices, config->sample_rate, config->format, config->channel_mask,
1313 flags, true /* directOnly */);
1314 }
1315
1316 if (profile == nullptr) {
1317 return NAME_NOT_FOUND;
1318 }
1319
1320 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1321 for (size_t i = 0; i < mOutputs.size(); i++) {
1322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1323 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1324 // reuse direct output if currently open by the same client
1325 // and configured with same parameters
1326 if ((config->sample_rate == desc->getSamplingRate()) &&
1327 (config->format == desc->getFormat()) &&
1328 (config->channel_mask == desc->getChannelMask()) &&
1329 (session == desc->mDirectClientSession)) {
1330 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001331 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001332 mOutputs.keyAt(i), session);
1333 *output = mOutputs.keyAt(i);
1334 return NO_ERROR;
1335 }
1336 }
1337 }
1338
1339 if (!profile->canOpenNewIo()) {
1340 return NAME_NOT_FOUND;
1341 }
1342
1343 sp<SwAudioOutputDescriptor> outputDesc =
1344 new SwAudioOutputDescriptor(profile, mpClientInterface);
1345
Michael Chan6fb34492020-12-08 15:44:49 +11001346 // An MSD patch may be using the only output stream that can service this request. Release
1347 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001348 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001349
Eric Laurentf1f22e72021-07-13 14:04:14 +02001350 status_t status =
1351 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001352
1353 // only accept an output with the requested parameters
1354 if (status != NO_ERROR ||
1355 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1356 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1357 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1358 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1359 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1360 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1361 config->channel_mask, outputDesc->getChannelMask());
1362 if (*output != AUDIO_IO_HANDLE_NONE) {
1363 outputDesc->close();
1364 }
1365 // fall back to mixer output if possible when the direct output could not be open
1366 if (audio_is_linear_pcm(config->format) &&
1367 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1368 return NAME_NOT_FOUND;
1369 }
1370 *output = AUDIO_IO_HANDLE_NONE;
1371 return BAD_VALUE;
1372 }
1373 outputDesc->mDirectOpenCount = 1;
1374 outputDesc->mDirectClientSession = session;
1375
1376 addOutput(*output, outputDesc);
1377 mPreviousOutputs = mOutputs;
1378 ALOGV("%s returns new direct output %d", __func__, *output);
1379 mpClientInterface->onAudioPortListUpdate();
1380 return NO_ERROR;
1381}
1382
François Gaffie11d30102018-11-02 16:09:09 +01001383audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1384 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001385 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001386 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001387 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001388 audio_output_flags_t *flags,
1389 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001390{
Andy Hungc88b0642018-04-27 15:42:35 -07001391 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001392
jiabine375d412019-02-26 12:54:53 -08001393 // Discard haptic channel mask when forcing muting haptic channels.
1394 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001395 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1396 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001397
Eric Laurente552edb2014-03-10 17:42:56 -07001398 // open a direct output if required by specified parameters
1399 //force direct flag if offload flag is set: offloading implies a direct output stream
1400 // and all common behaviors are driven by checking only the direct flag
1401 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001402 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1403 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001404 }
Nadav Bar766fb022018-01-07 12:18:03 +02001405 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1406 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001407 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001408
1409 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1410
Eric Laurente83b55d2014-11-14 10:06:21 -08001411 // only allow deep buffering for music stream type
1412 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001413 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001414 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001415 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001416 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1417 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001418 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001419 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001420 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001421 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001422 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001423 audio_is_linear_pcm(config->format) &&
1424 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001425 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001426 AUDIO_OUTPUT_FLAG_DIRECT);
1427 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001428 }
Eric Laurente552edb2014-03-10 17:42:56 -07001429
Carter Hsua3abb402021-10-26 11:11:20 +08001430 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1431 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1432 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1433 }
1434
Eric Laurentfa0f6742021-08-17 18:39:44 +02001435 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001436 && canBeSpatializedInt(attr, config,
1437 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001438 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001439 }
1440
Eric Laurentc529cf62020-04-17 18:19:10 -07001441 audio_config_t directConfig = *config;
1442 directConfig.channel_mask = channelMask;
1443 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1444 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001445 return output;
1446 }
1447
Eric Laurent14cbfca2016-03-17 09:42:16 -07001448 // A request for HW A/V sync cannot fallback to a mixed output because time
1449 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001450 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001451 return AUDIO_IO_HANDLE_NONE;
1452 }
1453
Eric Laurente552edb2014-03-10 17:42:56 -07001454 // ignoring channel mask due to downmix capability in mixer
1455
1456 // open a non direct output
1457
1458 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001459 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001460 // get which output is suitable for the specified stream. The actual
1461 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001462 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001463
Eric Laurent8838a382014-09-08 16:44:28 -07001464 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001465 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001466 output = selectOutput(
1467 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001468 }
François Gaffie11d30102018-11-02 16:09:09 +01001469 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001470 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001471 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001472
Eric Laurente552edb2014-03-10 17:42:56 -07001473 return output;
1474}
1475
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001476sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001477 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1478 mAvailableInputDevices);
1479 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1480}
1481
1482DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1483 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1484 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001485}
1486
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001487const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001488 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001489 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1490 if (msdModule != 0) {
1491 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1492 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1493 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1494 const struct audio_port_config *source = &patch->mPatch.sources[j];
1495 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1496 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001497 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001498 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001499 }
1500 }
1501 }
1502 return msdPatches;
1503}
1504
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001505bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1506 ssize_t index = mAudioPatches.indexOfKey(handle);
1507 if (index < 0) {
1508 return false;
1509 }
1510 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1511 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1512 if (msdModule == nullptr) {
1513 return false;
1514 }
1515 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1516 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1517 return true;
1518 }
1519 index = getMsdOutputPatches().indexOfKey(handle);
1520 if (index < 0) {
1521 return false;
1522 }
1523 return true;
1524}
1525
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001526status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1527 const InputProfileCollection &inputProfiles,
1528 const OutputProfileCollection &outputProfiles,
1529 const sp<DeviceDescriptor> &sourceDevice,
1530 const sp<DeviceDescriptor> &sinkDevice,
1531 AudioProfileVector& sourceProfiles,
1532 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001533 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001534 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001535 return NO_INIT;
1536 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001537 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001538 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001539 return NO_INIT;
1540 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001541 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001542 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1543 inProfile->supportsDevice(sourceDevice)) {
1544 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001545 }
1546 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001547 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001548 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001549 outProfile->supportsDevice(sinkDevice)) {
1550 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 }
1552 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001553 return NO_ERROR;
1554}
1555
1556status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1557 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1558 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1559{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001560 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001561 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1562 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1563 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001564 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001565 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1566 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001567 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568 }
1569 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1570 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1571 sinkConfig->format = bestSinkConfig.format;
1572 // For encoded streams force direct flag to prevent downstream mixing.
1573 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1574 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001575 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1576 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001577 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001578 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1579 // raw and IEC61937 framed streams.
1580 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1581 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1582 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001583 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1584 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1585 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1586 sourceConfig->format = bestSinkConfig.format;
1587 // Copy input stream directly without any processing (e.g. resampling).
1588 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1589 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1590 if (hwAvSync) {
1591 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1592 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1593 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1594 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1595 }
1596 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1597 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1598 sinkConfig->config_mask |= config_mask;
1599 sourceConfig->config_mask |= config_mask;
1600 return NO_ERROR;
1601}
1602
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001603PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1604 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001605{
1606 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001607 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1608 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1609 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1610 if (deviceModule == nullptr) {
1611 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1612 return patchBuilder;
1613 }
1614 const InputProfileCollection inputProfiles = msdIsSource ?
1615 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1616 const OutputProfileCollection outputProfiles = msdIsSource ?
1617 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1618
1619 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1620 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1621 device : getMsdAudioOutDevices().itemAt(0);
1622 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1623
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1625 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001626 AudioProfileVector sourceProfiles;
1627 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1629 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630 for (auto hwAvSync : { true, false }) {
1631 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1632 sourceProfiles, sinkProfiles) != NO_ERROR) {
1633 continue;
1634 }
1635 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1636 &sinkConfig) == NO_ERROR) {
1637 // Found a matching config. Re-create PatchBuilder with this config.
1638 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1639 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001640 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001641 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 " supporting PCM format conversion.", __func__);
1643 return patchBuilder;
1644}
1645
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001646status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001647 DeviceVector devices;
1648 if (outputDevices != nullptr && outputDevices->size() > 0) {
1649 devices.add(*outputDevices);
1650 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001651 // Use media strategy for unspecified output device. This should only
1652 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1653 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001654 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001655 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001656 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001657 }
Michael Chan6fb34492020-12-08 15:44:49 +11001658 std::vector<PatchBuilder> patchesToCreate;
1659 for (auto i = 0u; i < devices.size(); ++i) {
1660 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001661 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001662 }
1663 // Retain only the MSD patches associated with outputDevices request.
1664 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001665 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001666 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1667 auto retainedPatch = false;
1668 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1669 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1670 patchesToRemove.removeItemsAt(i);
1671 retainedPatch = true;
1672 break;
1673 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001674 }
Michael Chan6fb34492020-12-08 15:44:49 +11001675 if (retainedPatch) {
1676 it = patchesToCreate.erase(it);
1677 continue;
1678 }
1679 ++it;
1680 }
1681 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1682 return NO_ERROR;
1683 }
1684 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1685 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001686 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001687 }
Michael Chan6fb34492020-12-08 15:44:49 +11001688 status_t status = NO_ERROR;
1689 for (const auto &p : patchesToCreate) {
1690 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1691 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1692 char message[256];
1693 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1694 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1695 currStatus == NO_ERROR ? "Success" : "Error",
1696 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1697 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1698 if (currStatus == NO_ERROR) {
1699 ALOGD("%s", message);
1700 } else {
1701 ALOGE("%s", message);
1702 if (status == NO_ERROR) {
1703 status = currStatus;
1704 }
1705 }
1706 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 return status;
1708}
1709
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1711 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001712 for (size_t i = 0; i < msdPatches.size(); i++) {
1713 const auto& patch = msdPatches[i];
1714 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1715 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1716 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1717 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1718 releaseAudioPatch(patch->getHandle(), mUidCached);
1719 break;
1720 }
1721 }
1722 }
1723}
1724
Dorin Drimus94d94412022-02-02 09:05:02 +01001725bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1726 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1727 AudioPatchCollection msdPatches = getMsdOutputPatches();
1728 for (size_t i = 0; i < msdPatches.size(); i++) {
1729 const auto& patch = msdPatches[i];
1730 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1731 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1732 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1733 const auto& foundDevice = devicesToCheck.getDevice(
1734 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1735 if (foundDevice != nullptr) {
1736 devicesToCheck.remove(foundDevice);
1737 if (devicesToCheck.isEmpty()) {
1738 return true;
1739 }
1740 }
1741 }
1742 }
1743 }
1744 return false;
1745}
1746
Eric Laurente0720872014-03-11 09:30:41 -07001747audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001748 audio_output_flags_t flags,
1749 audio_format_t format,
1750 audio_channel_mask_t channelMask,
1751 uint32_t samplingRate,
1752 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001753{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001754 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1755 "%s called with format %#x", __func__, format);
1756
jiabinebb6af42020-06-09 17:31:17 -07001757 // Return the output that haptic-generating attached to when 1) session id is specified,
1758 // 2) haptic-generating effect exists for given session id and 3) the output that
1759 // haptic-generating effect attached to is in given outputs.
1760 if (sessionId != AUDIO_SESSION_NONE) {
1761 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1762 sessionId, FX_IID_HAPTICGENERATOR);
1763 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1764 return hapticGeneratingOutput;
1765 }
1766 }
1767
Eric Laurent16c66dd2019-05-01 17:54:10 -07001768 // Flags disqualifying an output: the match must happen before calling selectOutput()
1769 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1770 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1771
1772 // Flags expressing a functional request: must be honored in priority over
1773 // other criteria
1774 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1775 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001776 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1777 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001778 // Flags expressing a performance request: have lower priority than serving
1779 // requested sampling rate or channel mask
1780 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1781 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1782 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1783
1784 const audio_output_flags_t functionalFlags =
1785 (audio_output_flags_t)(flags & kFunctionalFlags);
1786 const audio_output_flags_t performanceFlags =
1787 (audio_output_flags_t)(flags & kPerformanceFlags);
1788
1789 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1790
Eric Laurente552edb2014-03-10 17:42:56 -07001791 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001792 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001793 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001794 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001795 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001796 // with tiebreak preferring the minimum number of extra functional flags
1797 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001798 // 3: the output supporting the exact channel mask
1799 // 4: the output with a higher channel count than requested
1800 // 5: the output with a higher sampling rate than requested
1801 // 6: the output with the highest number of requested performance flags
1802 // 7: the output with the bit depth the closest to the requested one
1803 // 8: the primary output
1804 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001805
Eric Laurent16c66dd2019-05-01 17:54:10 -07001806 // matching criteria values in priority order for best matching output so far
1807 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001808
Eric Laurent16c66dd2019-05-01 17:54:10 -07001809 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1810 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1811 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001812
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001813 for (audio_io_handle_t output : outputs) {
1814 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001815 // matching criteria values in priority order for current output
1816 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001817
Eric Laurent16c66dd2019-05-01 17:54:10 -07001818 if (outputDesc->isDuplicated()) {
1819 continue;
1820 }
1821 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1822 continue;
1823 }
Eric Laurent8838a382014-09-08 16:44:28 -07001824
Eric Laurent16c66dd2019-05-01 17:54:10 -07001825 // If haptic channel is specified, use the haptic output if present.
1826 // When using haptic output, same audio format and sample rate are required.
1827 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001828 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001829 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1830 continue;
1831 }
1832 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001833 && format == outputDesc->getFormat()
1834 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001835 currentMatchCriteria[0] = outputHapticChannelCount;
1836 }
1837
1838 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001839 const int matchingFunctionalFlags =
1840 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1841 const int totalFunctionalFlags =
1842 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1843 // Prefer matching functional flags, but subtract unnecessary functional flags.
1844 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001845
1846 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001847 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1848 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001849 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1850 channelCount <= outputChannelCount) {
1851 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001852 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1853 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001854 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001855 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001856 currentMatchCriteria[3] = outputChannelCount;
1857 }
1858
1859 // sampling rate match
1860 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001861 samplingRate <= outputDesc->getSamplingRate()) {
1862 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001863 }
1864
1865 // performance flags match
1866 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1867
1868 // format match
1869 if (format != AUDIO_FORMAT_INVALID) {
1870 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001871 PolicyAudioPort::kFormatDistanceMax -
1872 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001873 }
1874
1875 // primary output match
1876 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1877
1878 // compare match criteria by priority then value
1879 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1880 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1881 bestMatchCriteria = currentMatchCriteria;
1882 bestOutput = output;
1883
1884 std::stringstream result;
1885 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1886 std::ostream_iterator<int>(result, " "));
1887 ALOGV("%s new bestOutput %d criteria %s",
1888 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001889 }
1890 }
1891
Eric Laurent16c66dd2019-05-01 17:54:10 -07001892 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001893}
1894
Eric Laurent8fc147b2018-07-22 19:13:55 -07001895status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001896{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001897 ALOGV("%s portId %d", __FUNCTION__, portId);
1898
1899 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1900 if (outputDesc == 0) {
1901 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001902 return BAD_VALUE;
1903 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001904 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001905
Eric Laurent8fc147b2018-07-22 19:13:55 -07001906 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001907 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001908
Eric Laurent733ce942017-12-07 12:18:25 -08001909 status_t status = outputDesc->start();
1910 if (status != NO_ERROR) {
1911 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001912 }
1913
Eric Laurent97ac8712018-07-27 18:59:02 -07001914 uint32_t delayMs;
1915 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001916
1917 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001918 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001919 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001920 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001921 if (delayMs != 0) {
1922 usleep(delayMs * 1000);
1923 }
1924
1925 return status;
1926}
1927
Eric Laurent97ac8712018-07-27 18:59:02 -07001928status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1929 const sp<TrackClientDescriptor>& client,
1930 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001931{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001932 // cannot start playback of STREAM_TTS if any other output is being used
1933 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001934
1935 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001936 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001937 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001938 auto clientStrategy = client->strategy();
1939 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001940 if (stream == AUDIO_STREAM_TTS) {
1941 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001942 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001943 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001944 return INVALID_OPERATION;
1945 } else {
1946 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1947 }
1948 } else {
1949 // some playback other than beacon starts
1950 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1951 }
1952
Eric Laurent77305a62016-07-25 16:39:22 -07001953 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001954 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001955 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001956
François Gaffie11d30102018-11-02 16:09:09 +01001957 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001958 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001959 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001960 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001961 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001962 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001963 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001964 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001965 } else {
1966 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001967 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001968 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1969 AUDIO_FORMAT_DEFAULT);
1970 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1971 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001972 }
1973
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001974 // requiresMuteCheck is false when we can bypass mute strategy.
1975 // It covers a common case when there is no materially active audio
1976 // and muting would result in unnecessary delay and dropped audio.
1977 const uint32_t outputLatencyMs = outputDesc->latency();
1978 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1979
Eric Laurente552edb2014-03-10 17:42:56 -07001980 // increment usage count for this stream on the requested output:
1981 // NOTE that the usage count is the same for duplicated output and hardware output which is
1982 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001983 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001984
1985 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001986 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1987 client->isPreferredDeviceForExclusiveUse()) {
1988 // Preferred device may be exclusive, use only if no other active clients on this output
1989 devices = DeviceVector(
1990 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1991 } else {
1992 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1993 }
François Gaffie11d30102018-11-02 16:09:09 +01001994 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001995 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001996 }
1997 }
Eric Laurente552edb2014-03-10 17:42:56 -07001998
François Gaffiec005e562018-11-06 15:04:49 +01001999 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002000 selectOutputForMusicEffects();
2001 }
2002
François Gaffie1c878552018-11-22 16:53:21 +01002003 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002004 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002005 if (devices.isEmpty()) {
2006 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002007 }
François Gaffiec005e562018-11-06 15:04:49 +01002008 bool shouldWait =
2009 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2010 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2011 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002012 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002013 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002014 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002015 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002016 // An output has a shared device if
2017 // - managed by the same hw module
2018 // - supports the currently selected device
2019 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002020 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002021
Eric Laurent77305a62016-07-25 16:39:22 -07002022 // force a device change if any other output is:
2023 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002024 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002025 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002026 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002027 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002028 // change the device currently selected by the other output.
2029 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002030 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002031 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002032 force = true;
2033 }
2034 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002035 // a notification so that audio focus effect can propagate, or that a mute/unmute
2036 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002037 const uint32_t latencyMs = desc->latency();
2038 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2039
2040 if (shouldWait && isActive && (waitMs < latencyMs)) {
2041 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002042 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002043
2044 // Require mute check if another output is on a shared device
2045 // and currently active to have proper drain and avoid pops.
2046 // Note restoring AudioTracks onto this output needs to invoke
2047 // a volume ramp if there is no mute.
2048 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002049 }
2050 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002051
2052 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002053 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002054
Eric Laurente552edb2014-03-10 17:42:56 -07002055 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002056 auto &curves = getVolumeCurves(client->attributes());
2057 checkAndSetVolume(curves, client->volumeSource(),
2058 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002059 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002060 outputDesc->devices().types(), 0 /*delay*/,
2061 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002062
2063 // update the outputs if starting an output with a stream that can affect notification
2064 // routing
2065 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002066
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002067 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002068 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002069 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2070 }
Eric Laurentdc462862016-07-19 12:29:53 -07002071
2072 if (waitMs > muteWaitMs) {
2073 *delayMs = waitMs - muteWaitMs;
2074 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002075
2076 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2077 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2078 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2079 // change occurs after the MixerThread starts and causes a stream volume
2080 // glitch.
2081 //
2082 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
Eric Laurentdc462862016-07-19 12:29:53 -07002084
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002085 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002086 mEngine->getForceUse(
2087 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002088 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002089 }
2090
Eric Laurent97ac8712018-07-27 18:59:02 -07002091 // Automatically enable the remote submix input when output is started on a re routing mix
2092 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002093 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2094 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002095 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2096 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2097 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002098 "remote-submix",
2099 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002100 }
2101
Eric Laurente552edb2014-03-10 17:42:56 -07002102 return NO_ERROR;
2103}
2104
Eric Laurent8fc147b2018-07-22 19:13:55 -07002105status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002106{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002107 ALOGV("%s portId %d", __FUNCTION__, portId);
2108
2109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2110 if (outputDesc == 0) {
2111 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002112 return BAD_VALUE;
2113 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002114 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002115
Eric Laurent97ac8712018-07-27 18:59:02 -07002116 ALOGV("stopOutput() output %d, stream %d, session %d",
2117 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002118
Eric Laurent97ac8712018-07-27 18:59:02 -07002119 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002120
Eric Laurent733ce942017-12-07 12:18:25 -08002121 if (status == NO_ERROR ) {
2122 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002123 }
2124 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002125}
2126
Eric Laurent97ac8712018-07-27 18:59:02 -07002127status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2128 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002129{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002130 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002131 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002132 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002133
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002134 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2135
François Gaffie1c878552018-11-22 16:53:21 +01002136 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2137 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002138 // Automatically disable the remote submix input when output is stopped on a
2139 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002140 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002141 if (isSingleDeviceType(
2142 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002143 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002144 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002145 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2146 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002147 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002148 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002149 }
2150 }
2151 bool forceDeviceUpdate = false;
2152 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002153 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002154 forceDeviceUpdate = true;
2155 }
2156
Eric Laurente552edb2014-03-10 17:42:56 -07002157 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002158 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002159
Eric Laurente552edb2014-03-10 17:42:56 -07002160 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002161 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002162 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002163 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002164
2165 // If the routing does not change, if an output is routed on a device using HwGain
2166 // (aka setAudioPortConfig) and there are still active clients following different
2167 // volume group(s), force reapply volume
2168 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2169 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2170
Eric Laurente552edb2014-03-10 17:42:56 -07002171 // delay the device switch by twice the latency because stopOutput() is executed when
2172 // the track stop() command is received and at that time the audio track buffer can
2173 // still contain data that needs to be drained. The latency only covers the audio HAL
2174 // and kernel buffers. Also the latency does not always include additional delay in the
2175 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002176 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2177 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002178
2179 // force restoring the device selection on other active outputs if it differs from the
2180 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002181 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002182 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002183 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002184 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002185 desc->isActive() &&
2186 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002187 (newDevices != desc->devices())) {
2188 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2189 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002190
François Gaffie11d30102018-11-02 16:09:09 +01002191 setOutputDevices(desc, newDevices2, force, delayMs);
2192
Eric Laurent57de36c2016-09-28 16:59:11 -07002193 // re-apply device specific volume if not done by setOutputDevice()
2194 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002195 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002196 }
Eric Laurente552edb2014-03-10 17:42:56 -07002197 }
2198 }
2199 // update the outputs if stopping one with a stream that can affect notification routing
2200 handleNotificationRoutingForStream(stream);
2201 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002202
2203 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2204 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002205 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002206 }
2207
François Gaffiec005e562018-11-06 15:04:49 +01002208 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002209 selectOutputForMusicEffects();
2210 }
Eric Laurente552edb2014-03-10 17:42:56 -07002211 return NO_ERROR;
2212 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002213 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002214 return INVALID_OPERATION;
2215 }
2216}
2217
jiabinbce0c1d2020-10-05 11:20:18 -07002218bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002219{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002220 ALOGV("%s portId %d", __FUNCTION__, portId);
2221
2222 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2223 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002224 // If an output descriptor is closed due to a device routing change,
2225 // then there are race conditions with releaseOutput from tracks
2226 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2227 // destroyed shortly thereafter.
2228 //
2229 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002230 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002231 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002232 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002233
2234 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302236 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2237 if (outputDesc->isClientActive(client)) {
2238 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2239 stopOutput(portId);
2240 }
2241
Eric Laurent8fc147b2018-07-22 19:13:55 -07002242 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2243 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002244 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002245 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002246 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002247 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002248 if (--outputDesc->mDirectOpenCount == 0) {
2249 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002250 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002251 }
2252 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302253
Andy Hung39efb7a2018-09-26 15:39:28 -07002254 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002255 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2256 // The output is pending reopened to query dynamic profiles and
2257 // there is no active clients
2258 closeOutput(outputDesc->mIoHandle);
2259 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2260 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2261 if (newOutputDesc == nullptr) {
2262 ALOGE("%s failed to open output", __func__);
2263 }
2264 return true;
2265 }
2266 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002267}
2268
Eric Laurentcaf7f482014-11-25 17:50:47 -08002269status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2270 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002271 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002272 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002273 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002274 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002275 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002276 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002277 input_type_t *inputType,
2278 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002279{
François Gaffiec005e562018-11-06 15:04:49 +01002280 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002281 "flags %#x attributes=%s requested device ID %d",
2282 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2283 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002284
Eric Laurentad2e7b92017-09-14 20:06:42 -07002285 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002286 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002287 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002288 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002289 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002290 sp<AudioInputDescriptor> inputDesc;
2291 sp<RecordClientDescriptor> clientDesc;
2292 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002293 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002294 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002295
2296 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2297 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2298 return INVALID_OPERATION;
2299 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002300
Francois Gaffie716e1432019-01-14 16:58:59 +01002301 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2302 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002303 }
2304
Paul McLean466dc8e2015-04-17 13:15:36 -06002305 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002306 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002307 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002308
Eric Laurentad2e7b92017-09-14 20:06:42 -07002309 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2310 // possible
2311 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2312 *input != AUDIO_IO_HANDLE_NONE) {
2313 ssize_t index = mInputs.indexOfKey(*input);
2314 if (index < 0) {
2315 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2316 status = BAD_VALUE;
2317 goto error;
2318 }
2319 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002320 RecordClientVector clients = inputDesc->getClientsForSession(session);
2321 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002322 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2323 status = BAD_VALUE;
2324 goto error;
2325 }
2326 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2327 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002328 // corresponds to a new client and is only permitted from the same UID.
2329 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002330 if (clients.size() > 1) {
2331 for (const auto& client : clients) {
2332 // The client map is ordered by key values (portId) and portIds are allocated
2333 // incrementaly. So the first client in this list is the one opened by audio flinger
2334 // when the mmap stream is created and should be ignored as it does not correspond
2335 // to an actual client
2336 if (client == *clients.cbegin()) {
2337 continue;
2338 }
2339 if (uid != client->uid() && !client->isSilenced()) {
2340 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2341 uid, client->portId(), client->uid());
2342 status = INVALID_OPERATION;
2343 goto error;
2344 }
Eric Laurent331679c2018-04-16 17:03:16 -07002345 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002346 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002347 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002348 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002349
Eric Laurentfecbceb2021-02-09 14:46:43 +01002350 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002351 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002352 }
2353
2354 *input = AUDIO_IO_HANDLE_NONE;
2355 *inputType = API_INPUT_INVALID;
2356
Francois Gaffie716e1432019-01-14 16:58:59 +01002357 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002358
Francois Gaffie716e1432019-01-14 16:58:59 +01002359 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2360 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2361 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002362 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002363 ALOGW("%s could not find input mix for attr %s",
2364 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002365 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002366 }
jiabinc1de2df2019-05-07 14:26:40 -07002367 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2368 String8(attr->tags + strlen("addr=")),
2369 AUDIO_FORMAT_DEFAULT);
2370 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002371 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002372 __func__, attributes.source, attributes.tags);
2373 status = BAD_VALUE;
2374 goto error;
2375 }
2376
Kevin Rocard25f9b052019-02-27 15:08:54 -08002377 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2378 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2379 } else {
2380 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2381 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002382 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002383 if (explicitRoutingDevice != nullptr) {
2384 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002385 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002386 // Prevent from storing invalid requested device id in clients
2387 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002388 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002389 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2390 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002391 }
François Gaffie11d30102018-11-02 16:09:09 +01002392 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002393 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002394 status = BAD_VALUE;
2395 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002396 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002397 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2398 *inputType = API_INPUT_MIX_CAPTURE;
2399 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002400 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2401 // there is an external policy, but this input is attached to a mix of recorders,
2402 // meaning it receives audio injected into the framework, so the recorder doesn't
2403 // know about it and is therefore considered "legacy"
2404 *inputType = API_INPUT_LEGACY;
2405 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002406 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002407 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002408 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002409 } else {
2410 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002411 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002412
Eric Laurent599c7582015-12-07 18:05:55 -08002413 }
2414
François Gaffiec005e562018-11-06 15:04:49 +01002415 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002416 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002417 status = INVALID_OPERATION;
2418 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002419 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002420
Eric Laurent8f42ea12018-08-08 09:08:25 -07002421exit:
2422
François Gaffiec005e562018-11-06 15:04:49 +01002423 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2424 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002425
Francois Gaffie716e1432019-01-14 16:58:59 +01002426 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002427 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002428 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002429
Mikhail Naganov2996f672019-04-18 12:29:59 -07002430 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002431 requestedDeviceId, attributes.source, flags,
2432 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002433 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002434 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002435
2436 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2437 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002438
Eric Laurent599c7582015-12-07 18:05:55 -08002439 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002440
2441error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002442 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002443}
2444
2445
François Gaffie11d30102018-11-02 16:09:09 +01002446audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002447 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002448 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002449 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002450 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002451 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002452{
2453 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002454 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002455 bool isSoundTrigger = false;
2456
François Gaffiec005e562018-11-06 15:04:49 +01002457 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002458 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2459 if (index >= 0) {
2460 input = mSoundTriggerSessions.valueFor(session);
2461 isSoundTrigger = true;
2462 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2463 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2464 } else {
2465 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002466 }
François Gaffiec005e562018-11-06 15:04:49 +01002467 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002468 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002469 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002470 }
2471
Carter Hsua3abb402021-10-26 11:11:20 +08002472 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2473 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2474 }
2475
Andy Hungf129b032015-04-07 13:45:50 -07002476 // find a compatible input profile (not necessarily identical in parameters)
2477 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002478 // sampling rate and flags may be updated by getInputProfile
2479 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2480 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002481 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002482 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002483 audio_input_flags_t profileFlags = flags;
2484 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002485 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002486 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002487 profileFlags);
2488 if (profile != 0) {
2489 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002490 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2491 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002492 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002493 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2494 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002495 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002496 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002497 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002498 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002499 }
Eric Laurente552edb2014-03-10 17:42:56 -07002500 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002501 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002502 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002503 if (samplingRate == 0) {
2504 samplingRate = profileSamplingRate;
2505 }
Eric Laurente552edb2014-03-10 17:42:56 -07002506
Eric Laurent322b4d22015-04-03 15:57:54 -07002507 if (profile->getModuleHandle() == 0) {
2508 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002509 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002510 }
2511
Eric Laurentec376dc2021-04-08 20:41:22 +02002512 // Reuse an already opened input if a client with the same session ID already exists
2513 // on that input
2514 for (size_t i = 0; i < mInputs.size(); i++) {
2515 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2516 if (desc->mProfile != profile) {
2517 continue;
2518 }
2519 RecordClientVector clients = desc->clientsList();
2520 for (const auto &client : clients) {
2521 if (session == client->session()) {
2522 return desc->mIoHandle;
2523 }
2524 }
2525 }
2526
Eric Laurent3974e3b2017-12-07 17:58:43 -08002527 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002528 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002529 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002530 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002531 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002532 continue;
2533 }
2534 // if sound trigger, reuse input if used by other sound trigger on same session
2535 // else
2536 // reuse input if active client app is not in IDLE state
2537 //
2538 RecordClientVector clients = desc->clientsList();
2539 bool doClose = false;
2540 for (const auto& client : clients) {
2541 if (isSoundTrigger != client->isSoundTrigger()) {
2542 continue;
2543 }
2544 if (client->isSoundTrigger()) {
2545 if (session == client->session()) {
2546 return desc->mIoHandle;
2547 }
2548 continue;
2549 }
2550 if (client->active() && client->appState() != APP_STATE_IDLE) {
2551 return desc->mIoHandle;
2552 }
2553 doClose = true;
2554 }
2555 if (doClose) {
2556 closeInput(desc->mIoHandle);
2557 } else {
2558 i++;
2559 }
2560 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002561 }
2562
Eric Laurentfe231122017-11-17 17:48:06 -08002563 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002564
Eric Laurentfe231122017-11-17 17:48:06 -08002565 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2566 lConfig.sample_rate = profileSamplingRate;
2567 lConfig.channel_mask = profileChannelMask;
2568 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002569
François Gaffie11d30102018-11-02 16:09:09 +01002570 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002571
2572 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002573 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002574 (profileSamplingRate != lConfig.sample_rate) ||
2575 !audio_formats_match(profileFormat, lConfig.format) ||
2576 (profileChannelMask != lConfig.channel_mask)) {
2577 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002578 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002579 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002580 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002581 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002582 }
Eric Laurent599c7582015-12-07 18:05:55 -08002583 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002584 }
2585
Eric Laurentc722f302014-12-10 11:21:49 -08002586 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002587
Eric Laurent599c7582015-12-07 18:05:55 -08002588 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002589 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002590
Eric Laurent599c7582015-12-07 18:05:55 -08002591 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002592}
2593
Eric Laurent4eb58f12018-12-07 16:41:02 -08002594status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002595{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002596 ALOGV("%s portId %d", __FUNCTION__, portId);
2597
2598 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2599 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002600 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002601 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002602 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002603 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002604 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 if (client->active()) {
2606 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2607 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002608 }
2609
Eric Laurent8f42ea12018-08-08 09:08:25 -07002610 audio_session_t session = client->session();
2611
Eric Laurent4eb58f12018-12-07 16:41:02 -08002612 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002613
Eric Laurent4eb58f12018-12-07 16:41:02 -08002614 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002615
Eric Laurent4eb58f12018-12-07 16:41:02 -08002616 status_t status = inputDesc->start();
2617 if (status != NO_ERROR) {
2618 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002619 }
Eric Laurente552edb2014-03-10 17:42:56 -07002620
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002621 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002622 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002623 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002624
Eric Laurent8f42ea12018-08-08 09:08:25 -07002625 // indicate active capture to sound trigger service if starting capture from a mic on
2626 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002627 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002628 if (device != nullptr) {
2629 status = setInputDevice(input, device, true /* force */);
2630 } else {
2631 ALOGW("%s no new input device can be found for descriptor %d",
2632 __FUNCTION__, inputDesc->getId());
2633 status = BAD_VALUE;
2634 }
Eric Laurente552edb2014-03-10 17:42:56 -07002635
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002636 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002637 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002638 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002639 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002640 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2641 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002642 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002643 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002644
François Gaffie11d30102018-11-02 16:09:09 +01002645 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2646 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002647 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002648 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002649 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002650
Eric Laurent8f42ea12018-08-08 09:08:25 -07002651 // automatically enable the remote submix output when input is started if not
2652 // used by a policy mix of type MIX_TYPE_RECORDERS
2653 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002654 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002655 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002656 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002658 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2659 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002660 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002661 if (address != "") {
2662 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2663 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002664 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002665 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002666 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002667 } else if (status != NO_ERROR) {
2668 // Restore client activity state.
2669 inputDesc->setClientActive(client, false);
2670 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002671 }
2672
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002673 ALOGV("%s input %d source = %d status = %d exit",
2674 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002675
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002676 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002677}
2678
Eric Laurent8fc147b2018-07-22 19:13:55 -07002679status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002680{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002681 ALOGV("%s portId %d", __FUNCTION__, portId);
2682
2683 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2684 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002685 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002686 return BAD_VALUE;
2687 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002688 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002689 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002690 if (!client->active()) {
2691 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002692 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002693 }
Carter Hsue6139d52021-07-08 10:30:20 +08002694 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002695 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002696
Eric Laurent8f42ea12018-08-08 09:08:25 -07002697 inputDesc->stop();
2698 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002699 auto current_source = inputDesc->source();
2700 setInputDevice(input, getNewInputDevice(inputDesc),
2701 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002702 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002703 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002704 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002705 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002706 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2707 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002708 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002709 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002710
2711 // automatically disable the remote submix output when input is stopped if not
2712 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002713 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002714 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002715 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002717 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2718 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002719 }
2720 if (address != "") {
2721 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2722 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002723 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002724 }
2725 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002726 resetInputDevice(input);
2727
2728 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2729 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002730 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2731 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002732 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002733 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002734 }
2735 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002736 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002737 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002738}
2739
Eric Laurent8fc147b2018-07-22 19:13:55 -07002740void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002741{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002742 ALOGV("%s portId %d", __FUNCTION__, portId);
2743
2744 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2745 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002746 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002747 return;
2748 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002749 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002750 audio_io_handle_t input = inputDesc->mIoHandle;
2751
Eric Laurent8f42ea12018-08-08 09:08:25 -07002752 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002753
Andy Hung39efb7a2018-09-26 15:39:28 -07002754 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002755
Andy Hung39efb7a2018-09-26 15:39:28 -07002756 if (inputDesc->getClientCount() > 0) {
2757 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002758 return;
2759 }
2760
Eric Laurent05b90f82014-08-27 15:32:29 -07002761 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002762 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002764}
2765
Eric Laurent8f42ea12018-08-08 09:08:25 -07002766void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002767{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002769
2770 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002771 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002772 }
2773}
2774
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2776{
2777 stopInput(portId);
2778 releaseInput(portId);
2779}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002780
Eric Laurent0dd51852019-04-19 18:18:58 -07002781void AudioPolicyManager::checkCloseInputs() {
2782 // After connecting or disconnecting an input device, close input if:
2783 // - it has no client (was just opened to check profile) OR
2784 // - none of its supported devices are connected anymore OR
2785 // - one of its clients cannot be routed to one of its supported
2786 // devices anymore. Otherwise update device selection
2787 std::vector<audio_io_handle_t> inputsToClose;
2788 for (size_t i = 0; i < mInputs.size(); i++) {
2789 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2790 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002791 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002792 inputsToClose.push_back(mInputs.keyAt(i));
2793 } else {
2794 bool close = false;
2795 for (const auto& client : input->clientsList()) {
2796 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002797 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002798 if (!input->supportedDevices().contains(device)) {
2799 close = true;
2800 break;
2801 }
2802 }
2803 if (close) {
2804 inputsToClose.push_back(mInputs.keyAt(i));
2805 } else {
2806 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2807 }
2808 }
2809 }
2810
2811 for (const audio_io_handle_t handle : inputsToClose) {
2812 ALOGV("%s closing input %d", __func__, handle);
2813 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002814 }
Eric Laurentd4692962014-05-05 18:13:44 -07002815}
2816
François Gaffie251c7f02018-11-07 10:41:08 +01002817void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002818{
2819 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002820 if (indexMin < 0 || indexMax < 0) {
2821 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2822 return;
2823 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002824 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002825
2826 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002827 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2828 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002829 continue;
2830 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002831 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002832 }
Eric Laurente552edb2014-03-10 17:42:56 -07002833}
2834
Eric Laurente0720872014-03-11 09:30:41 -07002835status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002836 int index,
2837 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002838{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002839 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002840 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2841 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2842 return NO_ERROR;
2843 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002844 ALOGV("%s: stream %s attributes=%s", __func__,
2845 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002846 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002847}
2848
Eric Laurente0720872014-03-11 09:30:41 -07002849status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002850 int *index,
2851 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002852{
François Gaffiec005e562018-11-06 15:04:49 +01002853 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2854 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002855 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002856 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002857 deviceTypes = mEngine->getOutputDevicesForStream(
2858 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002859 }
jiabin9a3361e2019-10-01 09:38:30 -07002860 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002861}
2862
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002863status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002864 int index,
2865 audio_devices_t device)
2866{
2867 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002868 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2869 if (group == VOLUME_GROUP_NONE) {
2870 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002871 return BAD_VALUE;
2872 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002873 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002874 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002875 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002876 VolumeSource vs = toVolumeSource(group);
2877 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2878
2879 status = setVolumeCurveIndex(index, device, curves);
2880 if (status != NO_ERROR) {
2881 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2882 return status;
2883 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002884
jiabin9a3361e2019-10-01 09:38:30 -07002885 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002886 auto curCurvAttrs = curves.getAttributes();
2887 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2888 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002889 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002890 } else if (!curves.getStreamTypes().empty()) {
2891 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002892 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002893 } else {
2894 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2895 return BAD_VALUE;
2896 }
jiabin9a3361e2019-10-01 09:38:30 -07002897 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2898 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002899
François Gaffiecfe17322018-11-07 13:41:29 +01002900 // update volume on all outputs and streams matching the following:
2901 // - The requested stream (or a stream matching for volume control) is active on the output
2902 // - The device (or devices) selected by the engine for this stream includes
2903 // the requested device
2904 // - For non default requested device, currently selected device on the output is either the
2905 // requested device or one of the devices selected by the engine for this stream
2906 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2907 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002908 for (size_t i = 0; i < mOutputs.size(); i++) {
2909 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002910 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002911
jiabin9a3361e2019-10-01 09:38:30 -07002912 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2913 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002914 }
François Gaffieed91f582020-01-31 10:35:37 +01002915 if (!(desc->isActive(vs) || isInCall())) {
2916 continue;
2917 }
2918 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2919 curDevices.find(device) == curDevices.end()) {
2920 continue;
2921 }
2922 bool applyVolume = false;
2923 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2924 curSrcDevices.insert(device);
2925 applyVolume = (curSrcDevices.find(
2926 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2927 } else {
2928 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2929 }
2930 if (!applyVolume) {
2931 continue; // next output
2932 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002933 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2934 // If a higher priority strategy is active, and the output is routed to a device with a
2935 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002936 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002937 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002938 // If the volume source is active with higher priority source, ensure at least Sw Muted
2939 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002940 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2941 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2942 false /*preferredDevice*/);
2943 if (activeClients.empty()) {
2944 continue;
2945 }
2946 bool isPreempted = false;
2947 bool isHigherPriority = productStrategy < strategy;
2948 for (const auto &client : activeClients) {
2949 if (isHigherPriority && (client->volumeSource() != vs)) {
2950 ALOGV("%s: Strategy=%d (\nrequester:\n"
2951 " group %d, volumeGroup=%d attributes=%s)\n"
2952 " higher priority source active:\n"
2953 " volumeGroup=%d attributes=%s) \n"
2954 " on output %zu, bailing out", __func__, productStrategy,
2955 group, group, toString(attributes).c_str(),
2956 client->volumeSource(), toString(client->attributes()).c_str(), i);
2957 applyVolume = false;
2958 isPreempted = true;
2959 break;
2960 }
2961 // However, continue for loop to ensure no higher prio clients running on output
2962 if (client->volumeSource() == vs) {
2963 applyVolume = true;
2964 }
2965 }
2966 if (isPreempted || applyVolume) {
2967 break;
2968 }
2969 }
2970 if (!applyVolume) {
2971 continue; // next output
2972 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002973 }
François Gaffieed91f582020-01-31 10:35:37 +01002974 //FIXME: workaround for truncated touch sounds
2975 // delayed volume change for system stream to be removed when the problem is
2976 // handled by system UI
2977 status_t volStatus = checkAndSetVolume(
2978 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002979 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01002980 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2981 if (volStatus != NO_ERROR) {
2982 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002983 }
2984 }
François Gaffiecfe17322018-11-07 13:41:29 +01002985 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2986 return status;
2987}
2988
François Gaffieaaac0fd2018-11-22 17:56:39 +01002989status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002990 audio_devices_t device,
2991 IVolumeCurves &volumeCurves)
2992{
2993 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2994 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002995 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2996 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002997 (index > volumeCurves.getVolumeIndexMax())) {
2998 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2999 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3000 return BAD_VALUE;
3001 }
3002 if (!audio_is_output_device(device)) {
3003 return BAD_VALUE;
3004 }
3005
3006 // Force max volume if stream cannot be muted
3007 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3008
François Gaffieaaac0fd2018-11-22 17:56:39 +01003009 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003010 volumeCurves.addCurrentVolumeIndex(device, index);
3011 return NO_ERROR;
3012}
3013
3014status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3015 int &index,
3016 audio_devices_t device)
3017{
3018 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3019 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003020 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003021 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003022 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3023 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003024 }
jiabin9a3361e2019-10-01 09:38:30 -07003025 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003026}
3027
3028status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3029 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003030 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003031{
jiabin9a3361e2019-10-01 09:38:30 -07003032 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003033 return BAD_VALUE;
3034 }
jiabin9a3361e2019-10-01 09:38:30 -07003035 index = curves.getVolumeIndex(deviceTypes);
3036 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003037 return NO_ERROR;
3038}
3039
3040status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3041 int &index)
3042{
3043 index = getVolumeCurves(attr).getVolumeIndexMin();
3044 return NO_ERROR;
3045}
3046
3047status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3048 int &index)
3049{
3050 index = getVolumeCurves(attr).getVolumeIndexMax();
3051 return NO_ERROR;
3052}
3053
Eric Laurent36829f92017-04-07 19:04:42 -07003054audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003055{
3056 // select one output among several suitable for global effects.
3057 // The priority is as follows:
3058 // 1: An offloaded output. If the effect ends up not being offloadable,
3059 // AudioFlinger will invalidate the track and the offloaded output
3060 // will be closed causing the effect to be moved to a PCM output.
3061 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003062 // 3: The primary output
3063 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003064
François Gaffiec005e562018-11-06 15:04:49 +01003065 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3066 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003067 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003068
Eric Laurent36829f92017-04-07 19:04:42 -07003069 if (outputs.size() == 0) {
3070 return AUDIO_IO_HANDLE_NONE;
3071 }
Eric Laurente552edb2014-03-10 17:42:56 -07003072
Eric Laurent36829f92017-04-07 19:04:42 -07003073 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3074 bool activeOnly = true;
3075
3076 while (output == AUDIO_IO_HANDLE_NONE) {
3077 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3078 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3079 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3080
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003081 for (audio_io_handle_t output : outputs) {
3082 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003083 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003084 continue;
3085 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003086 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3087 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003088 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003089 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003090 }
3091 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003092 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003093 }
3094 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003095 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003096 }
3097 }
3098 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3099 output = outputOffloaded;
3100 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3101 output = outputDeepBuffer;
3102 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3103 output = outputPrimary;
3104 } else {
3105 output = outputs[0];
3106 }
3107 activeOnly = false;
3108 }
3109
3110 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003111 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003112 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3113 mMusicEffectOutput = output;
3114 }
3115
3116 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003117 return output;
3118}
3119
Eric Laurent36829f92017-04-07 19:04:42 -07003120audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3121{
3122 return selectOutputForMusicEffects();
3123}
3124
Eric Laurente0720872014-03-11 09:30:41 -07003125status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003126 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003127 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003128 int session,
3129 int id)
3130{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003131 if (session != AUDIO_SESSION_DEVICE) {
3132 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003133 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003134 index = mInputs.indexOfKey(io);
3135 if (index < 0) {
3136 ALOGW("registerEffect() unknown io %d", io);
3137 return INVALID_OPERATION;
3138 }
Eric Laurente552edb2014-03-10 17:42:56 -07003139 }
3140 }
François Gaffiec005e562018-11-06 15:04:49 +01003141 return mEffects.registerEffect(desc, io, session, id,
3142 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3143 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003144}
3145
Eric Laurentc241b0d2018-11-28 09:08:49 -08003146status_t AudioPolicyManager::unregisterEffect(int id)
3147{
3148 if (mEffects.getEffect(id) == nullptr) {
3149 return INVALID_OPERATION;
3150 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003151 if (mEffects.isEffectEnabled(id)) {
3152 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3153 setEffectEnabled(id, false);
3154 }
3155 return mEffects.unregisterEffect(id);
3156}
3157
3158status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3159{
3160 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3161 if (effect == nullptr) {
3162 return INVALID_OPERATION;
3163 }
3164
3165 status_t status = mEffects.setEffectEnabled(id, enabled);
3166 if (status == NO_ERROR) {
3167 mInputs.trackEffectEnabled(effect, enabled);
3168 }
3169 return status;
3170}
3171
Eric Laurent6c796322019-04-09 14:13:17 -07003172
3173status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3174{
3175 mEffects.moveEffects(ids, io);
3176 return NO_ERROR;
3177}
3178
Eric Laurentc75307b2015-03-17 15:29:32 -07003179bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3180{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003181 auto vs = toVolumeSource(stream, false);
3182 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003183}
3184
3185bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3186{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003187 auto vs = toVolumeSource(stream, false);
3188 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003189}
3190
Eric Laurente0720872014-03-11 09:30:41 -07003191bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003192{
3193 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003194 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003195 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003196 return true;
3197 }
3198 }
3199 return false;
3200}
3201
Eric Laurent275e8e92014-11-30 15:14:47 -08003202// Register a list of custom mixes with their attributes and format.
3203// When a mix is registered, corresponding input and output profiles are
3204// added to the remote submix hw module. The profile contains only the
3205// parameters (sampling rate, format...) specified by the mix.
3206// The corresponding input remote submix device is also connected.
3207//
3208// When a remote submix device is connected, the address is checked to select the
3209// appropriate profile and the corresponding input or output stream is opened.
3210//
3211// When capture starts, getInputForAttr() will:
3212// - 1 look for a mix matching the address passed in attribtutes tags if any
3213// - 2 if none found, getDeviceForInputSource() will:
3214// - 2.1 look for a mix matching the attributes source
3215// - 2.2 if none found, default to device selection by policy rules
3216// At this time, the corresponding output remote submix device is also connected
3217// and active playback use cases can be transferred to this mix if needed when reconnecting
3218// after AudioTracks are invalidated
3219//
3220// When playback starts, getOutputForAttr() will:
3221// - 1 look for a mix matching the address passed in attribtutes tags if any
3222// - 2 if none found, look for a mix matching the attributes usage
3223// - 3 if none found, default to device and output selection by policy rules.
3224
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003225status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003226{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003227 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3228 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003229 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003230 sp<HwModule> rSubmixModule;
3231 // examine each mix's route type
3232 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003233 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003234 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3235 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3236 ALOGE("Unsupported Policy Mix %zu of %zu: "
3237 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3238 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003239 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003240 break;
3241 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003242 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3243 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003244 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003245 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3246 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003247 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003248 rSubmixModule = mHwModules.getModuleFromName(
3249 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3250 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003251 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003252 i);
3253 res = INVALID_OPERATION;
3254 break;
3255 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003256 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003257
Eric Laurent97ac8712018-07-27 18:59:02 -07003258 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003259 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003260 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003261 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003262 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3263 } else {
3264 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3265 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003266 }
François Gaffie036e1e92015-03-19 10:16:24 +01003267
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003268 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003269 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003270 res = INVALID_OPERATION;
3271 break;
3272 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003273 audio_config_t outputConfig = mix.mFormat;
3274 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003275 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3276 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003277 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3278 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003279 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003280 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003281 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003282 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003283
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003284 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003285 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3286 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3287 ALOGE("Failed to set remote submix device available, type %u, address %s",
3288 mix.mDeviceType, address.string());
3289 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003290 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003291 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3292 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003293 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003294 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003295 i, mixes.size(), type, address.string());
3296
3297 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3298 mix.mDeviceType, mix.mDeviceAddress,
3299 String8(), AUDIO_FORMAT_DEFAULT);
3300 if (device == nullptr) {
3301 res = INVALID_OPERATION;
3302 break;
3303 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003304
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003305 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003306 // First try to find an already opened output supporting the device
3307 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003308 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003309
Eric Laurentc529cf62020-04-17 18:19:10 -07003310 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003311 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003312 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3313 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003314 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003315 } else {
3316 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003317 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003318 }
3319 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003320 // If no output found, try to find a direct output profile supporting the device
3321 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3322 sp<HwModule> module = mHwModules[i];
3323 for (size_t j = 0;
3324 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3325 j++) {
3326 sp<IOProfile> profile = module->getOutputProfiles()[j];
3327 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3328 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3329 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3330 address.string());
3331 res = INVALID_OPERATION;
3332 } else {
3333 foundOutput = true;
3334 }
3335 }
3336 }
3337 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003338 if (res != NO_ERROR) {
3339 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003340 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003341 res = INVALID_OPERATION;
3342 break;
3343 } else if (!foundOutput) {
3344 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003345 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003346 res = INVALID_OPERATION;
3347 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003348 } else {
3349 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003350 }
Eric Laurentc722f302014-12-10 11:21:49 -08003351 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003352 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003353 if (res != NO_ERROR) {
3354 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003355 } else if (checkOutputs) {
3356 checkForDeviceAndOutputChanges();
3357 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003358 }
3359 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003360}
3361
3362status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3363{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003364 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003365 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003366 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003367 sp<HwModule> rSubmixModule;
3368 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003369 for (const auto& mix : mixes) {
3370 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003371
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003372 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003373 rSubmixModule = mHwModules.getModuleFromName(
3374 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3375 if (rSubmixModule == 0) {
3376 res = INVALID_OPERATION;
3377 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003378 }
3379 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003380
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003381 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003382
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003383 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003384 res = INVALID_OPERATION;
3385 continue;
3386 }
3387
Kevin Rocard04ed0462019-05-02 17:53:24 -07003388 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3389 if (getDeviceConnectionState(device, address.string()) ==
3390 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3391 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3392 address.string(), "remote-submix",
3393 AUDIO_FORMAT_DEFAULT);
3394 if (res != OK) {
3395 ALOGE("Error making RemoteSubmix device unavailable for mix "
3396 "with type %d, address %s", device, address.string());
3397 }
3398 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003399 }
jiabin5740f082019-08-19 15:08:30 -07003400 rSubmixModule->removeOutputProfile(address.c_str());
3401 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003402
Kevin Rocard153f92d2018-12-18 18:33:28 -08003403 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003404 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003405 res = INVALID_OPERATION;
3406 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003407 } else {
3408 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003409 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003410 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003411 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003412 if (res == NO_ERROR && checkOutputs) {
3413 checkForDeviceAndOutputChanges();
3414 updateCallAndOutputRouting();
3415 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003416 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003417}
3418
Mikhail Naganov100f0122018-11-29 11:22:16 -08003419void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3420{
3421 size_t i = 0;
3422 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3423 for (const auto& fmt : mManualSurroundFormats) {
3424 if (i++ != 0) dst->append(", ");
3425 std::string sfmt;
3426 FormatConverter::toString(fmt, sfmt);
3427 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3428 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3429 }
3430}
3431
Eric Laurentc529cf62020-04-17 18:19:10 -07003432// Returns true if all devices types match the predicate and are supported by one HW module
3433bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003434 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003435 std::function<bool(audio_devices_t)> predicate,
3436 const char *context) {
3437 for (size_t i = 0; i < devices.size(); i++) {
3438 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003439 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003440 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003441 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003442 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003443 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003444 return false;
3445 }
3446 }
3447 return true;
3448}
3449
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003450status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003451 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003452 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003453 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3454 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003455 }
3456 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003457 if (res != NO_ERROR) {
3458 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3459 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003460 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003461
3462 checkForDeviceAndOutputChanges();
3463 updateCallAndOutputRouting();
3464
3465 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003466}
3467
3468status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3469 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003470 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3471 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003472 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003473 __FUNCTION__, uid);
3474 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003475 }
3476
Eric Laurentc529cf62020-04-17 18:19:10 -07003477 checkForDeviceAndOutputChanges();
3478 updateCallAndOutputRouting();
3479
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003480 return res;
3481}
3482
Eric Laurent2517af32020-11-25 15:31:27 +01003483
jiabin0a488932020-08-07 17:32:40 -07003484status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3485 device_role_t role,
3486 const AudioDeviceTypeAddrVector &devices) {
3487 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3488 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003489
Eric Laurentc529cf62020-04-17 18:19:10 -07003490 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003491 return BAD_VALUE;
3492 }
jiabin0a488932020-08-07 17:32:40 -07003493 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003494 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003495 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3496 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003497 return status;
3498 }
3499
3500 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003501
3502 bool forceVolumeReeval = false;
3503 // FIXME: workaround for truncated touch sounds
3504 // to be removed when the problem is handled by system UI
3505 uint32_t delayMs = 0;
3506 if (strategy == mCommunnicationStrategy) {
3507 forceVolumeReeval = true;
3508 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3509 updateInputRouting();
3510 }
3511 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003512
3513 return NO_ERROR;
3514}
3515
3516void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3517{
3518 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003519 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003520 // Only apply special touch sound delay once
3521 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003522 }
3523 for (size_t i = 0; i < mOutputs.size(); i++) {
3524 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3525 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3526 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3527 // As done in setDeviceConnectionState, we could also fix default device issue by
3528 // preventing the force re-routing in case of default dev that distinguishes on address.
3529 // Let's give back to engine full device choice decision however.
3530 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003531 // Only apply special touch sound delay once
3532 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003533 }
3534 if (forceVolumeReeval && !newDevices.isEmpty()) {
3535 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3536 }
3537 }
3538}
3539
Eric Laurent2517af32020-11-25 15:31:27 +01003540void AudioPolicyManager::updateInputRouting() {
3541 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303542 // Skip for hotword recording as the input device switch
3543 // is handled within sound trigger HAL
3544 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3545 continue;
3546 }
Eric Laurent2517af32020-11-25 15:31:27 +01003547 auto newDevice = getNewInputDevice(activeDesc);
3548 // Force new input selection if the new device can not be reached via current input
3549 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3550 setInputDevice(activeDesc->mIoHandle, newDevice);
3551 } else {
3552 closeInput(activeDesc->mIoHandle);
3553 }
3554 }
3555}
3556
jiabin0a488932020-08-07 17:32:40 -07003557status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3558 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003559{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003560 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003561
jiabin0a488932020-08-07 17:32:40 -07003562 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003563 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003564 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3565 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003566 return status;
3567 }
3568
3569 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003570
3571 bool forceVolumeReeval = false;
3572 // FIXME: workaround for truncated touch sounds
3573 // to be removed when the problem is handled by system UI
3574 uint32_t delayMs = 0;
3575 if (strategy == mCommunnicationStrategy) {
3576 forceVolumeReeval = true;
3577 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3578 updateInputRouting();
3579 }
3580 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003581
3582 return NO_ERROR;
3583}
3584
jiabin0a488932020-08-07 17:32:40 -07003585status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3586 device_role_t role,
3587 AudioDeviceTypeAddrVector &devices) {
3588 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003589}
3590
Jiabin Huang3b98d322020-09-03 17:54:16 +00003591status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3592 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3593 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3594 dumpAudioDeviceTypeAddrVector(devices).c_str());
3595
Mikhail Naganov55773032020-10-01 15:08:13 -07003596 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003597 return BAD_VALUE;
3598 }
3599 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3600 ALOGW_IF(status != NO_ERROR,
3601 "Engine could not set preferred devices %s for audio source %d role %d",
3602 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3603
3604 return status;
3605}
3606
3607status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3608 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3609 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3610 dumpAudioDeviceTypeAddrVector(devices).c_str());
3611
Mikhail Naganov55773032020-10-01 15:08:13 -07003612 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003613 return BAD_VALUE;
3614 }
3615 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3616 ALOGW_IF(status != NO_ERROR,
3617 "Engine could not add preferred devices %s for audio source %d role %d",
3618 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3619
Eric Laurent2517af32020-11-25 15:31:27 +01003620 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003621 return status;
3622}
3623
3624status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3625 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3626{
3627 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3628 dumpAudioDeviceTypeAddrVector(devices).c_str());
3629
Mikhail Naganov55773032020-10-01 15:08:13 -07003630 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003631 return BAD_VALUE;
3632 }
3633
3634 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3635 audioSource, role, devices);
3636 ALOGW_IF(status != NO_ERROR,
3637 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3638
Eric Laurent2517af32020-11-25 15:31:27 +01003639 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003640 return status;
3641}
3642
3643status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3644 device_role_t role) {
3645 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3646
3647 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3648 ALOGW_IF(status != NO_ERROR,
3649 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3650
Eric Laurent2517af32020-11-25 15:31:27 +01003651 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003652 return status;
3653}
3654
3655status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3656 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3657 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3658}
3659
Oscar Azucena90e77632019-11-27 17:12:28 -08003660status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003661 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003662 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003663 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3664 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003665 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003666 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3667 if (status != NO_ERROR) {
3668 ALOGE("%s() could not set device affinity for userId %d",
3669 __FUNCTION__, userId);
3670 return status;
3671 }
3672
3673 // reevaluate outputs for all devices
3674 checkForDeviceAndOutputChanges();
3675 updateCallAndOutputRouting();
3676
3677 return NO_ERROR;
3678}
3679
3680status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003681 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003682 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3683 if (status != NO_ERROR) {
3684 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3685 __FUNCTION__, userId);
3686 return status;
3687 }
3688
3689 // reevaluate outputs for all devices
3690 checkForDeviceAndOutputChanges();
3691 updateCallAndOutputRouting();
3692
3693 return NO_ERROR;
3694}
3695
Andy Hungc29d82b2018-10-05 12:23:17 -07003696void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003697{
Andy Hungc29d82b2018-10-05 12:23:17 -07003698 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003699 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003700 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003701 std::string stateLiteral;
3702 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003703 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003704 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3705 "communications", "media", "record", "dock", "system",
3706 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3707 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3708 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003709 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3710 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3711 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3712 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3713 dst->append(" (MANUAL: ");
3714 dumpManualSurroundFormats(dst);
3715 dst->append(")");
3716 }
3717 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003718 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003719 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3720 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003721 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003722 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003723
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003724 dst->append("\n");
3725 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3726 dst->append("\n");
3727 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003728 mHwModulesAll.dump(dst);
3729 mOutputs.dump(dst);
3730 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003731 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003732 mAudioPatches.dump(dst);
3733 mPolicyMixes.dump(dst);
3734 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003735
Kevin Rocardb99cc752019-03-21 20:52:24 -07003736 dst->appendFormat(" AllowedCapturePolicies:\n");
3737 for (auto& policy : mAllowedCapturePolicies) {
3738 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3739 }
3740
François Gaffiec005e562018-11-06 15:04:49 +01003741 dst->appendFormat("\nPolicy Engine dump:\n");
3742 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003743}
3744
3745status_t AudioPolicyManager::dump(int fd)
3746{
3747 String8 result;
3748 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003749 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003750 return NO_ERROR;
3751}
3752
Kevin Rocardb99cc752019-03-21 20:52:24 -07003753status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3754{
3755 mAllowedCapturePolicies[uid] = capturePolicy;
3756 return NO_ERROR;
3757}
3758
Eric Laurente552edb2014-03-10 17:42:56 -07003759// This function checks for the parameters which can be offloaded.
3760// This can be enhanced depending on the capability of the DSP and policy
3761// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003762audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003763{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003764 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003765 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003766 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003767 offloadInfo.format,
3768 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3769 offloadInfo.has_video);
3770
jiabin2b9d5a12021-12-10 01:06:29 +00003771 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003772 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003773 }
3774
3775 // See if there is a profile to support this.
3776 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003777 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003778 offloadInfo.sample_rate,
3779 offloadInfo.format,
3780 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003781 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3782 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003783 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3784 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3785 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003786 if (profile == nullptr) {
3787 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3788 }
3789 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3790 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3791 }
3792 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003793}
3794
Michael Chana94fbb22018-04-24 14:31:19 +10003795bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3796 const audio_attributes_t& attributes) {
3797 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003798 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003799 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3800 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003801 config.sample_rate,
3802 config.format,
3803 config.channel_mask,
3804 output_flags,
3805 true /* directOnly */);
3806 ALOGV("%s() profile %sfound with name: %s, "
3807 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3808 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003809 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003810 config.sample_rate, config.format, config.channel_mask, output_flags);
3811 return (profile != 0);
3812}
3813
jiabin2b9d5a12021-12-10 01:06:29 +00003814bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3815 bool durationIgnored) {
3816 if (mMasterMono) {
3817 return false; // no offloading if mono is set.
3818 }
3819
3820 // Check if offload has been disabled
3821 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3822 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3823 return false;
3824 }
3825
3826 // Check if stream type is music, then only allow offload as of now.
3827 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3828 {
3829 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3830 return false;
3831 }
3832
3833 //TODO: enable audio offloading with video when ready
3834 const bool allowOffloadWithVideo =
3835 property_get_bool("audio.offload.video", false /* default_value */);
3836 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3837 ALOGV("%s: has_video == true, returning false", __func__);
3838 return false;
3839 }
3840
3841 //If duration is less than minimum value defined in property, return false
3842 const int min_duration_secs = property_get_int32(
3843 "audio.offload.min.duration.secs", -1 /* default_value */);
3844 if (!durationIgnored) {
3845 if (min_duration_secs >= 0) {
3846 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3847 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3848 __func__, min_duration_secs);
3849 return false;
3850 }
3851 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3852 ALOGV("%s: Offload denied by duration < default min(=%u)",
3853 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3854 return false;
3855 }
3856 }
3857
3858 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3859 // creating an offloaded track and tearing it down immediately after start when audioflinger
3860 // detects there is an active non offloadable effect.
3861 // FIXME: We should check the audio session here but we do not have it in this context.
3862 // This may prevent offloading in rare situations where effects are left active by apps
3863 // in the background.
3864 if (mEffects.isNonOffloadableEffectEnabled()) {
3865 return false;
3866 }
3867
3868 return true;
3869}
3870
3871audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3872 const audio_config_t *config) {
3873 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3874 offloadInfo.format = config->format;
3875 offloadInfo.sample_rate = config->sample_rate;
3876 offloadInfo.channel_mask = config->channel_mask;
3877 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3878 offloadInfo.has_video = false;
3879 offloadInfo.is_streaming = false;
3880 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3881
3882 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3883 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3884 audio_flags_to_audio_output_flags(attr->flags, &flags);
3885 // only retain flags that will drive compressed offload or passthrough
3886 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3887 if (offloadPossible) {
3888 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3889 }
3890 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3891
jiabinc8f7dfc2022-01-06 18:42:08 +00003892 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003893 for (const auto& hwModule : mHwModules) {
3894 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003895 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003896 config->sample_rate, nullptr /*updatedSamplingRate*/,
3897 config->format, nullptr /*updatedFormat*/,
3898 config->channel_mask, nullptr /*updatedChannelMask*/,
3899 flags)) {
3900 continue;
3901 }
3902 // reject profiles not corresponding to a device currently available
3903 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3904 continue;
3905 }
3906 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3907 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003908 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003909 != AUDIO_DIRECT_NOT_SUPPORTED) {
3910 // Already reports offload gapless supported. No need to report offload support.
3911 continue;
3912 }
3913 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3914 != AUDIO_OUTPUT_FLAG_NONE) {
3915 // If offload gapless is reported, no need to report offload support.
3916 directMode = (audio_direct_mode_t) ((directMode &
3917 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3918 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3919 } else {
3920 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3921 }
3922 } else {
3923 directMode = (audio_direct_mode_t) (directMode |
3924 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3925 }
3926 }
3927 }
3928 return directMode;
3929}
3930
Dorin Drimusf2196d82022-01-03 12:11:18 +01003931status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3932 AudioProfileVector& audioProfilesVector) {
3933 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08003934 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01003935 if (status != OK) {
3936 return status;
3937 }
3938 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3939 if (devices.empty()) {
3940 return OK; // no output devices for the attributes
3941 }
3942
3943 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01003944 // the MSD module checks for different conditions
3945 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3946 continue;
3947 }
3948 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
3949 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01003950 continue;
3951 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003952 // allow only profiles that support all the available and routed devices
3953 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01003954 != devices.size()) {
3955 continue;
3956 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003957 audioProfilesVector.addAllValidProfiles(
3958 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01003959 }
3960 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003961
3962 // add the direct profiles from MSD if present and has audio patches to all the output(s)
3963 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
3964 if (msdModule != nullptr) {
3965 if (msdHasPatchesToAllDevices(devices)) {
3966 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
3967 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
3968 if (!outputProfile->asAudioPort()->isDirectOutput()) {
3969 continue;
3970 }
3971 audioProfilesVector.addAllValidProfiles(
3972 outputProfile->asAudioPort()->getAudioProfiles());
3973 }
3974 } else {
3975 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
3976 }
3977 }
3978
Dorin Drimusf2196d82022-01-03 12:11:18 +01003979 return NO_ERROR;
3980}
3981
Eric Laurent6a94d692014-05-20 11:18:06 -07003982status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3983 audio_port_type_t type,
3984 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003985 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003986 unsigned int *generation)
3987{
jiabin19cdba52020-11-24 11:28:58 -08003988 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3989 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003990 return BAD_VALUE;
3991 }
3992 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003993 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003994 *num_ports = 0;
3995 }
3996
3997 size_t portsWritten = 0;
3998 size_t portsMax = *num_ports;
3999 *num_ports = 0;
4000 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004001 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4002 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004003 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004004 for (const auto& dev : mAvailableOutputDevices) {
4005 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004006 continue;
4007 }
4008 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004009 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004010 }
4011 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004012 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004013 }
4014 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004015 for (const auto& dev : mAvailableInputDevices) {
4016 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004017 continue;
4018 }
4019 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004020 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004021 }
4022 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004023 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004024 }
4025 }
4026 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4027 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4028 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4029 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4030 }
4031 *num_ports += mInputs.size();
4032 }
4033 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004034 size_t numOutputs = 0;
4035 for (size_t i = 0; i < mOutputs.size(); i++) {
4036 if (!mOutputs[i]->isDuplicated()) {
4037 numOutputs++;
4038 if (portsWritten < portsMax) {
4039 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4040 }
4041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004042 }
Eric Laurent84c70242014-06-23 08:46:27 -07004043 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004044 }
4045 }
4046 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004047 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004048 return NO_ERROR;
4049}
4050
jiabin19cdba52020-11-24 11:28:58 -08004051status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004052{
Eric Laurent99fcae42018-05-17 16:59:18 -07004053 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4054 return BAD_VALUE;
4055 }
4056 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4057 if (dev != 0) {
4058 dev->toAudioPort(port);
4059 return NO_ERROR;
4060 }
4061 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4062 if (dev != 0) {
4063 dev->toAudioPort(port);
4064 return NO_ERROR;
4065 }
4066 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4067 if (out != 0) {
4068 out->toAudioPort(port);
4069 return NO_ERROR;
4070 }
4071 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4072 if (in != 0) {
4073 in->toAudioPort(port);
4074 return NO_ERROR;
4075 }
4076 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004077}
4078
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004079status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4080 audio_patch_handle_t *handle,
4081 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004082{
François Gaffieafd4cea2019-11-18 15:50:22 +01004083 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004084 if (handle == NULL || patch == NULL) {
4085 return BAD_VALUE;
4086 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004087 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004088 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004089 return BAD_VALUE;
4090 }
4091 // only one source per audio patch supported for now
4092 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004093 return INVALID_OPERATION;
4094 }
Eric Laurent874c42872014-08-08 15:13:39 -07004095 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004096 return INVALID_OPERATION;
4097 }
Eric Laurent874c42872014-08-08 15:13:39 -07004098 for (size_t i = 0; i < patch->num_sinks; i++) {
4099 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4100 return INVALID_OPERATION;
4101 }
4102 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004103
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004104 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4105 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4106 if (srcDevice == nullptr || sinkDevice == nullptr) {
4107 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4108 return BAD_VALUE;
4109 }
4110 ALOGV("%s between source %s and sink %s", __func__,
4111 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4112 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4113 // Default attributes, default volume priority, not to infer with non raw audio patches.
4114 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4115 const struct audio_port_config *source = &patch->sources[0];
4116 sp<SourceClientDescriptor> sourceDesc =
4117 new InternalSourceClientDescriptor(
4118 portId, uid, attributes, *source, srcDevice, sinkDevice,
4119 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4120
4121 status_t status =
4122 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4123
4124 if (status != NO_ERROR) {
4125 return INVALID_OPERATION;
4126 }
4127 mAudioSources.add(portId, sourceDesc);
4128 return NO_ERROR;
4129}
4130
4131status_t AudioPolicyManager::connectAudioSourceToSink(
4132 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4133 const struct audio_patch *patch,
4134 audio_patch_handle_t &handle,
4135 uid_t uid, uint32_t delayMs)
4136{
4137 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4138 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4139 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4140 return INVALID_OPERATION;
4141 }
4142 sourceDesc->connect(handle, sinkDevice);
4143 if (isMsdPatch(handle)) {
4144 return NO_ERROR;
4145 }
4146 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4147 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4148 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4149 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4150 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4151 goto FailurePatchAdded;
4152 }
4153 status = swOutput->start();
4154 if (status != NO_ERROR) {
4155 goto FailureSourceAdded;
4156 }
4157 swOutput->addClient(sourceDesc);
4158 status = startSource(swOutput, sourceDesc, &delayMs);
4159 if (status != NO_ERROR) {
4160 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4161 goto FailureSourceActive;
4162 }
4163 if (delayMs != 0) {
4164 usleep(delayMs * 1000);
4165 }
4166 return NO_ERROR;
4167
4168FailureSourceActive:
4169 swOutput->stop();
4170 releaseOutput(sourceDesc->portId());
4171FailureSourceAdded:
4172 sourceDesc->setSwOutput(nullptr);
4173FailurePatchAdded:
4174 releaseAudioPatchInternal(handle);
4175 return INVALID_OPERATION;
4176}
4177
4178status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4179 audio_patch_handle_t *handle,
4180 uid_t uid, uint32_t delayMs,
4181 const sp<SourceClientDescriptor>& sourceDesc)
4182{
4183 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 sp<AudioPatch> patchDesc;
4185 ssize_t index = mAudioPatches.indexOfKey(*handle);
4186
François Gaffieafd4cea2019-11-18 15:50:22 +01004187 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4188 patch->sources[0].role,
4189 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004190#if LOG_NDEBUG == 0
4191 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004192 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4193 patch->sinks[i].role,
4194 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004195 }
4196#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004197
4198 if (index >= 0) {
4199 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004200 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4201 __func__, mUidCached, patchDesc->getUid(), uid);
4202 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004203 return INVALID_OPERATION;
4204 }
4205 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004206 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004207 }
4208
4209 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004210 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004211 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004212 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004213 return BAD_VALUE;
4214 }
Eric Laurent84c70242014-06-23 08:46:27 -07004215 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4216 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004217 if (patchDesc != 0) {
4218 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004219 ALOGV("%s source id differs for patch current id %d new id %d",
4220 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004221 return BAD_VALUE;
4222 }
4223 }
Eric Laurent874c42872014-08-08 15:13:39 -07004224 DeviceVector devices;
4225 for (size_t i = 0; i < patch->num_sinks; i++) {
4226 // Only support mix to devices connection
4227 // TODO add support for mix to mix connection
4228 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004229 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004230 return INVALID_OPERATION;
4231 }
4232 sp<DeviceDescriptor> devDesc =
4233 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4234 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004235 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004236 return BAD_VALUE;
4237 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004238
François Gaffie11d30102018-11-02 16:09:09 +01004239 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004240 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004241 NULL, // updatedSamplingRate
4242 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004243 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004244 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004245 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004246 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004247 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004248 return INVALID_OPERATION;
4249 }
4250 devices.add(devDesc);
4251 }
4252 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004253 return INVALID_OPERATION;
4254 }
Eric Laurent874c42872014-08-08 15:13:39 -07004255
Eric Laurent6a94d692014-05-20 11:18:06 -07004256 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004257 ALOGV("%s setting device %s on output %d",
4258 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004259 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004260 index = mAudioPatches.indexOfKey(*handle);
4261 if (index >= 0) {
4262 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004263 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004264 }
4265 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004266 patchDesc->setUid(uid);
4267 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004268 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004269 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004270 return INVALID_OPERATION;
4271 }
4272 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4273 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4274 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004275 // only one sink supported when connecting an input device to a mix
4276 if (patch->num_sinks > 1) {
4277 return INVALID_OPERATION;
4278 }
François Gaffie53615e22015-03-19 09:24:12 +01004279 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004280 if (inputDesc == NULL) {
4281 return BAD_VALUE;
4282 }
4283 if (patchDesc != 0) {
4284 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4285 return BAD_VALUE;
4286 }
4287 }
François Gaffie11d30102018-11-02 16:09:09 +01004288 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004289 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004290 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004291 return BAD_VALUE;
4292 }
4293
François Gaffie11d30102018-11-02 16:09:09 +01004294 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004295 patch->sinks[0].sample_rate,
4296 NULL, /*updatedSampleRate*/
4297 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004298 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004299 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004300 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004301 // FIXME for the parameter type,
4302 // and the NONE
4303 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004304 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004305 return INVALID_OPERATION;
4306 }
4307 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004308 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004309 device->toString().c_str(), inputDesc->mIoHandle);
4310 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004311 index = mAudioPatches.indexOfKey(*handle);
4312 if (index >= 0) {
4313 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004314 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004315 }
4316 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004317 patchDesc->setUid(uid);
4318 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004319 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004320 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004321 return INVALID_OPERATION;
4322 }
4323 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4324 // device to device connection
4325 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004326 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004327 return BAD_VALUE;
4328 }
4329 }
François Gaffie11d30102018-11-02 16:09:09 +01004330 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004331 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004332 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004333 return BAD_VALUE;
4334 }
Eric Laurent874c42872014-08-08 15:13:39 -07004335
Eric Laurent6a94d692014-05-20 11:18:06 -07004336 //update source and sink with our own data as the data passed in the patch may
4337 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004338 PatchBuilder patchBuilder;
4339 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004340
4341 // if first sink is to MSD, establish single MSD patch
4342 if (getMsdAudioOutDevices().contains(
4343 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4344 ALOGV("%s patching to MSD", __FUNCTION__);
4345 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4346 goto installPatch;
4347 }
4348
François Gaffieafd4cea2019-11-18 15:50:22 +01004349 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4350 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004351
Eric Laurent874c42872014-08-08 15:13:39 -07004352 for (size_t i = 0; i < patch->num_sinks; i++) {
4353 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004354 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004355 return INVALID_OPERATION;
4356 }
François Gaffie11d30102018-11-02 16:09:09 +01004357 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004358 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004359 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004360 return BAD_VALUE;
4361 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004362 audio_port_config sinkPortConfig = {};
4363 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4364 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004365
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004366 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4367 // volume management purpose (tracking activity)
4368 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4369 // in config XML to reach the sink so that is can be declared as available.
4370 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4371 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004372 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004373 // take care of dynamic routing for SwOutput selection,
4374 audio_attributes_t attributes = sourceDesc->attributes();
4375 audio_stream_type_t stream = sourceDesc->stream();
4376 audio_attributes_t resultAttr;
4377 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4378 config.sample_rate = sourceDesc->config().sample_rate;
4379 config.channel_mask = sourceDesc->config().channel_mask;
4380 config.format = sourceDesc->config().format;
4381 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4382 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4383 bool isRequestedDeviceForExclusiveUse = false;
4384 output_type_t outputType;
4385 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4386 &stream, sourceDesc->uid(), &config, &flags,
4387 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4388 nullptr, &outputType);
4389 if (output == AUDIO_IO_HANDLE_NONE) {
4390 ALOGV("%s no output for device %s",
4391 __FUNCTION__, sinkDevice->toString().c_str());
4392 return INVALID_OPERATION;
4393 }
4394 outputDesc = mOutputs.valueFor(output);
4395 if (outputDesc->isDuplicated()) {
4396 ALOGE("%s output is duplicated", __func__);
4397 return INVALID_OPERATION;
4398 }
4399 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004400 } else {
4401 // Same for "raw patches" aka created from createAudioPatch API
4402 SortedVector<audio_io_handle_t> outputs =
4403 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4404 // if the sink device is reachable via an opened output stream, request to
4405 // go via this output stream by adding a second source to the patch
4406 // description
4407 output = selectOutput(outputs);
4408 if (output == AUDIO_IO_HANDLE_NONE) {
4409 ALOGE("%s no output available for internal patch sink", __func__);
4410 return INVALID_OPERATION;
4411 }
4412 outputDesc = mOutputs.valueFor(output);
4413 if (outputDesc->isDuplicated()) {
4414 ALOGV("%s output for device %s is duplicated",
4415 __func__, sinkDevice->toString().c_str());
4416 return INVALID_OPERATION;
4417 }
4418 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004419 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004420 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004421 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004422 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004423 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004424 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4425 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004426 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4427 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004428 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004429 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004430 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004431 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004432 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004433 return INVALID_OPERATION;
4434 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004435 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004436 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004437 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004438 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004439 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004440 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4441 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4442 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004443 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004444 }
Eric Laurent83b88082014-06-20 18:31:16 -07004445 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 }
4447 // TODO: check from routing capabilities in config file and other conflicting patches
4448
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004449installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 status_t status = installPatch(
4451 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004452 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004453 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 return INVALID_OPERATION;
4455 }
4456 } else {
4457 return BAD_VALUE;
4458 }
4459 } else {
4460 return BAD_VALUE;
4461 }
4462 return NO_ERROR;
4463}
4464
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004465status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004466{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004467 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004468 ssize_t index = mAudioPatches.indexOfKey(handle);
4469
4470 if (index < 0) {
4471 return BAD_VALUE;
4472 }
4473 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004474 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4475 __func__, mUidCached, patchDesc->getUid(), uid);
4476 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 return INVALID_OPERATION;
4478 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004479 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4480 for (size_t i = 0; i < mAudioSources.size(); i++) {
4481 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4482 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4483 portId = sourceDesc->portId();
4484 break;
4485 }
4486 }
4487 return portId != AUDIO_PORT_HANDLE_NONE ?
4488 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004489}
Eric Laurent6a94d692014-05-20 11:18:06 -07004490
François Gaffieafd4cea2019-11-18 15:50:22 +01004491status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004492 uint32_t delayMs,
4493 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004494{
4495 ALOGV("%s patch %d", __func__, handle);
4496 if (mAudioPatches.indexOfKey(handle) < 0) {
4497 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4498 return BAD_VALUE;
4499 }
4500 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004502 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004504 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004505 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004506 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004507 return BAD_VALUE;
4508 }
4509
François Gaffie11d30102018-11-02 16:09:09 +01004510 setOutputDevices(outputDesc,
4511 getNewOutputDevices(outputDesc, true /*fromCache*/),
4512 true,
4513 0,
4514 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004515 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4516 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004517 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004518 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004519 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004520 return BAD_VALUE;
4521 }
4522 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004523 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004524 true,
4525 NULL);
4526 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004527 status_t status =
4528 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4529 ALOGV("%s patch panel returned %d patchHandle %d",
4530 __func__, status, patchDesc->getAfHandle());
4531 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004532 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004533 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004534 // SW or HW Bridge
4535 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4536 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004537 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004538 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4539 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4540 outputDesc = sourceDesc->swOutput().promote();
4541 }
4542 if (outputDesc == nullptr) {
4543 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4544 // releaseOutput has already called closeOutput in case of direct output
4545 return NO_ERROR;
4546 }
4547 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4548 resetOutputDevice(outputDesc);
4549 } else {
4550 // Reuse patch handle if still valid / do not force rerouting if still routed
4551 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004552 setOutputDevices(outputDesc,
4553 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004554 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004555 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004556 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004557 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 } else {
4559 return BAD_VALUE;
4560 }
4561 } else {
4562 return BAD_VALUE;
4563 }
4564 return NO_ERROR;
4565}
4566
4567status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4568 struct audio_patch *patches,
4569 unsigned int *generation)
4570{
François Gaffie53615e22015-03-19 09:24:12 +01004571 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004572 return BAD_VALUE;
4573 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004574 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004575 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004576}
4577
Eric Laurente1715a42014-05-20 11:30:42 -07004578status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004579{
Eric Laurente1715a42014-05-20 11:30:42 -07004580 ALOGV("setAudioPortConfig()");
4581
4582 if (config == NULL) {
4583 return BAD_VALUE;
4584 }
4585 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4586 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004587 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4588 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004589 }
4590
Eric Laurenta121f902014-06-03 13:32:54 -07004591 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004592 if (config->type == AUDIO_PORT_TYPE_MIX) {
4593 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004594 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004595 if (outputDesc == NULL) {
4596 return BAD_VALUE;
4597 }
Eric Laurent84c70242014-06-23 08:46:27 -07004598 ALOG_ASSERT(!outputDesc->isDuplicated(),
4599 "setAudioPortConfig() called on duplicated output %d",
4600 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004601 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004602 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004603 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004604 if (inputDesc == NULL) {
4605 return BAD_VALUE;
4606 }
Eric Laurenta121f902014-06-03 13:32:54 -07004607 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004608 } else {
4609 return BAD_VALUE;
4610 }
4611 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4612 sp<DeviceDescriptor> deviceDesc;
4613 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4614 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4615 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4616 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4617 } else {
4618 return BAD_VALUE;
4619 }
4620 if (deviceDesc == NULL) {
4621 return BAD_VALUE;
4622 }
Eric Laurenta121f902014-06-03 13:32:54 -07004623 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004624 } else {
4625 return BAD_VALUE;
4626 }
4627
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004628 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004629 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4630 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004631 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004632 audioPortConfig->toAudioPortConfig(&newConfig, config);
4633 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004634 }
Eric Laurenta121f902014-06-03 13:32:54 -07004635 if (status != NO_ERROR) {
4636 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004637 }
Eric Laurente1715a42014-05-20 11:30:42 -07004638
4639 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004640}
4641
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004642void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4643{
Eric Laurentd60560a2015-04-10 11:31:20 -07004644 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004645 clearAudioPatches(uid);
4646 clearSessionRoutes(uid);
4647}
4648
Eric Laurent6a94d692014-05-20 11:18:06 -07004649void AudioPolicyManager::clearAudioPatches(uid_t uid)
4650{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004651 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004652 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004653 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004654 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004655 }
4656 }
4657}
4658
François Gaffiec005e562018-11-06 15:04:49 +01004659void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004660{
François Gaffiec005e562018-11-06 15:04:49 +01004661 // Take the first attributes following the product strategy as it is used to retrieve the routed
4662 // device. All attributes wihin a strategy follows the same "routing strategy"
4663 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4664 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004665 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004666 for (size_t j = 0; j < mOutputs.size(); j++) {
4667 if (mOutputs.keyAt(j) == ouptutToSkip) {
4668 continue;
4669 }
4670 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004671 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004672 continue;
4673 }
4674 // If the default device for this strategy is on another output mix,
4675 // invalidate all tracks in this strategy to force re connection.
4676 // Otherwise select new device on the output mix.
4677 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004678 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4679 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004680 }
4681 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004682 setOutputDevices(
4683 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004684 }
4685 }
4686}
4687
4688void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4689{
4690 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004691 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004692 for (size_t i = 0; i < mOutputs.size(); i++) {
4693 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004694 for (const auto& client : outputDesc->getClientIterable()) {
4695 if (client->hasPreferredDevice() && client->uid() == uid) {
4696 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004697 auto clientStrategy = client->strategy();
4698 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4699 end(affectedStrategies)) {
4700 continue;
4701 }
4702 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004703 }
4704 }
4705 }
4706 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004707 for (const auto& strategy : affectedStrategies) {
4708 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004709 }
4710
4711 // remove input routes associated with this uid
4712 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004713 for (size_t i = 0; i < mInputs.size(); i++) {
4714 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004715 for (const auto& client : inputDesc->getClientIterable()) {
4716 if (client->hasPreferredDevice() && client->uid() == uid) {
4717 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4718 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004719 }
4720 }
4721 }
4722 // reroute inputs if necessary
4723 SortedVector<audio_io_handle_t> inputsToClose;
4724 for (size_t i = 0; i < mInputs.size(); i++) {
4725 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004726 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004727 inputsToClose.add(inputDesc->mIoHandle);
4728 }
4729 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004730 for (const auto& input : inputsToClose) {
4731 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004732 }
4733}
4734
Eric Laurentd60560a2015-04-10 11:31:20 -07004735void AudioPolicyManager::clearAudioSources(uid_t uid)
4736{
4737 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004738 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4739 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004740 stopAudioSource(mAudioSources.keyAt(i));
4741 }
4742 }
4743}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004744
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004745status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4746 audio_io_handle_t *ioHandle,
4747 audio_devices_t *device)
4748{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004749 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4750 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004751 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004752 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004753
François Gaffiedf372692015-03-19 10:43:27 +01004754 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004755}
4756
Eric Laurentd60560a2015-04-10 11:31:20 -07004757status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004758 const audio_attributes_t *attributes,
4759 audio_port_handle_t *portId,
4760 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004761{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004762 ALOGV("%s", __FUNCTION__);
4763 *portId = AUDIO_PORT_HANDLE_NONE;
4764
4765 if (source == NULL || attributes == NULL || portId == NULL) {
4766 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4767 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004768 return BAD_VALUE;
4769 }
4770
Eric Laurentd60560a2015-04-10 11:31:20 -07004771 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4772 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004773 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4774 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004775 return INVALID_OPERATION;
4776 }
4777
François Gaffie11d30102018-11-02 16:09:09 +01004778 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004779 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004780 String8(source->ext.device.address),
4781 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004782 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004783 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004784 return BAD_VALUE;
4785 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004786
jiabin4ef93452019-09-10 14:29:54 -07004787 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004788
François Gaffieaaac0fd2018-11-22 17:56:39 +01004789 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004790 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004791 mEngine->getStreamTypeForAttributes(*attributes),
4792 mEngine->getProductStrategyForAttributes(*attributes),
4793 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004794
4795 status_t status = connectAudioSource(sourceDesc);
4796 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004797 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004798 }
4799 return status;
4800}
4801
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004802status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004803{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004804 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004805
4806 // make sure we only have one patch per source.
4807 disconnectAudioSource(sourceDesc);
4808
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004809 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004810 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4811 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4812 sourceDesc->srcDevice()->type(),
4813 String8(sourceDesc->srcDevice()->address().c_str()),
4814 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004815 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004816 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004817 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004818 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004819 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4820 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4821 return INVALID_OPERATION;
4822 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004823 PatchBuilder patchBuilder;
4824 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4825 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004826
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004827 return connectAudioSourceToSink(
4828 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004829}
4830
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004831status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004832{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004833 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4834 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004835 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004836 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004837 return BAD_VALUE;
4838 }
4839 status_t status = disconnectAudioSource(sourceDesc);
4840
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004841 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004842 return status;
4843}
4844
Andy Hung2ddee192015-12-18 17:34:44 -08004845status_t AudioPolicyManager::setMasterMono(bool mono)
4846{
4847 if (mMasterMono == mono) {
4848 return NO_ERROR;
4849 }
4850 mMasterMono = mono;
4851 // if enabling mono we close all offloaded devices, which will invalidate the
4852 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4853 // for recreating the new AudioTrack as non-offloaded PCM.
4854 //
4855 // If disabling mono, we leave all tracks as is: we don't know which clients
4856 // and tracks are able to be recreated as offloaded. The next "song" should
4857 // play back offloaded.
4858 if (mMasterMono) {
4859 Vector<audio_io_handle_t> offloaded;
4860 for (size_t i = 0; i < mOutputs.size(); ++i) {
4861 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4862 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4863 offloaded.push(desc->mIoHandle);
4864 }
4865 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004866 for (const auto& handle : offloaded) {
4867 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004868 }
4869 }
4870 // update master mono for all remaining outputs
4871 for (size_t i = 0; i < mOutputs.size(); ++i) {
4872 updateMono(mOutputs.keyAt(i));
4873 }
4874 return NO_ERROR;
4875}
4876
4877status_t AudioPolicyManager::getMasterMono(bool *mono)
4878{
4879 *mono = mMasterMono;
4880 return NO_ERROR;
4881}
4882
Eric Laurentac9cef52017-06-09 15:46:26 -07004883float AudioPolicyManager::getStreamVolumeDB(
4884 audio_stream_type_t stream, int index, audio_devices_t device)
4885{
jiabin9a3361e2019-10-01 09:38:30 -07004886 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004887}
4888
jiabin81772902018-04-02 17:52:27 -07004889status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4890 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004891 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004892{
Kriti Dang6537def2021-03-02 13:46:59 +01004893 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4894 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004895 return BAD_VALUE;
4896 }
Kriti Dang6537def2021-03-02 13:46:59 +01004897 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4898 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004899
4900 size_t formatsWritten = 0;
4901 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004902
Kriti Dang6537def2021-03-02 13:46:59 +01004903 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004904 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4905 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004906 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004907 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004908 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004909 bool formatEnabled = true;
4910 switch (forceUse) {
4911 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004912 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004913 break;
4914 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4915 formatEnabled = false;
4916 break;
4917 default: // AUTO or ALWAYS => true
4918 break;
jiabin81772902018-04-02 17:52:27 -07004919 }
4920 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4921 }
jiabin81772902018-04-02 17:52:27 -07004922 }
4923 return NO_ERROR;
4924}
4925
Kriti Dang6537def2021-03-02 13:46:59 +01004926status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4927 audio_format_t *surroundFormats) {
4928 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4929 return BAD_VALUE;
4930 }
4931 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4932 __func__, *numSurroundFormats, surroundFormats);
4933
4934 size_t formatsWritten = 0;
4935 size_t formatsMax = *numSurroundFormats;
4936 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4937
4938 // Return formats from all device profiles that have already been resolved by
4939 // checkOutputsForDevice().
4940 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4941 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4942 audio_devices_t deviceType = device->type();
4943 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4944 // returns formats reported by HDMI devices.
4945 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4946 continue;
4947 }
4948 // Formats reported by sink devices
4949 std::unordered_set<audio_format_t> formatset;
4950 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4951 formatset.insert(it->second.begin(), it->second.end());
4952 }
4953
4954 // Formats hard-coded in the in policy configuration file (if any).
4955 FormatVector encodedFormats = device->encodedFormats();
4956 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4957 // Filter the formats which are supported by the vendor hardware.
4958 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4959 if (mConfig.getSurroundFormats().count(*it) != 0) {
4960 formats.insert(*it);
4961 } else {
4962 for (const auto& pair : mConfig.getSurroundFormats()) {
4963 if (pair.second.count(*it) != 0) {
4964 formats.insert(pair.first);
4965 break;
4966 }
4967 }
4968 }
4969 }
4970 }
4971 *numSurroundFormats = formats.size();
4972 for (const auto& format: formats) {
4973 if (formatsWritten < formatsMax) {
4974 surroundFormats[formatsWritten++] = format;
4975 }
4976 }
4977 return NO_ERROR;
4978}
4979
jiabin81772902018-04-02 17:52:27 -07004980status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4981{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004982 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004983 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4984 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004985 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004986 return BAD_VALUE;
4987 }
4988
Mikhail Naganov100f0122018-11-29 11:22:16 -08004989 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4990 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004991 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004992 return INVALID_OPERATION;
4993 }
4994
Mikhail Naganov100f0122018-11-29 11:22:16 -08004995 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004996 return NO_ERROR;
4997 }
4998
Mikhail Naganov100f0122018-11-29 11:22:16 -08004999 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005000 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005001 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005002 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005003 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005004 }
5005 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005006 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005007 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005008 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005009 }
5010 }
5011
5012 sp<SwAudioOutputDescriptor> outputDesc;
5013 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005014 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5015 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005016 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5017 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005018 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005019 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005020 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5021 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5022 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005023 name.c_str(),
5024 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005025 if (status != NO_ERROR) {
5026 continue;
5027 }
5028 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5029 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5030 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005031 name.c_str(),
5032 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005033 profileUpdated |= (status == NO_ERROR);
5034 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005035 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005036 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005037 AUDIO_DEVICE_IN_HDMI);
5038 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5039 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005040 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005041 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005042 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5043 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5044 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005045 name.c_str(),
5046 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005047 if (status != NO_ERROR) {
5048 continue;
5049 }
5050 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5051 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5052 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005053 name.c_str(),
5054 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005055 profileUpdated |= (status == NO_ERROR);
5056 }
5057
jiabin81772902018-04-02 17:52:27 -07005058 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005059 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005060 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005061 }
5062
5063 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5064}
5065
Eric Laurent5ada82e2019-08-29 17:53:54 -07005066void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005067{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005068 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005069 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005070 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005071 }
5072}
5073
jiabin6012f912018-11-02 17:06:30 -07005074bool AudioPolicyManager::isHapticPlaybackSupported()
5075{
5076 for (const auto& hwModule : mHwModules) {
5077 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5078 for (const auto &outProfile : outputProfiles) {
5079 struct audio_port audioPort;
5080 outProfile->toAudioPort(&audioPort);
5081 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5082 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5083 return true;
5084 }
5085 }
5086 }
5087 }
5088 return false;
5089}
5090
Carter Hsu325a8eb2022-01-19 19:56:51 +08005091bool AudioPolicyManager::isUltrasoundSupported()
5092{
5093 bool hasUltrasoundOutput = false;
5094 bool hasUltrasoundInput = false;
5095 for (const auto& hwModule : mHwModules) {
5096 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5097 if (!hasUltrasoundOutput) {
5098 for (const auto &outProfile : outputProfiles) {
5099 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5100 hasUltrasoundOutput = true;
5101 break;
5102 }
5103 }
5104 }
5105
5106 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5107 if (!hasUltrasoundInput) {
5108 for (const auto &inputProfile : inputProfiles) {
5109 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5110 hasUltrasoundInput = true;
5111 break;
5112 }
5113 }
5114 }
5115
5116 if (hasUltrasoundOutput && hasUltrasoundInput)
5117 return true;
5118 }
5119 return false;
5120}
5121
Eric Laurent8340e672019-11-06 11:01:08 -08005122bool AudioPolicyManager::isCallScreenModeSupported()
5123{
5124 return getConfig().isCallScreenModeSupported();
5125}
5126
5127
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005128status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005129{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005130 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005131 if (!sourceDesc->isConnected()) {
5132 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5133 return NO_ERROR;
5134 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005135 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5136 if (swOutput != 0) {
5137 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005138 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005139 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005140 }
jiabinbce0c1d2020-10-05 11:20:18 -07005141 if (releaseOutput(sourceDesc->portId())) {
5142 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5143 // no need to release audio patch here but just return NO_ERROR.
5144 return NO_ERROR;
5145 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005146 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005147 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005148 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005149 // close Hwoutput and remove from mHwOutputs
5150 } else {
5151 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5152 }
5153 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005154 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005155 sourceDesc->disconnect();
5156 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005157}
5158
François Gaffiec005e562018-11-06 15:04:49 +01005159sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5160 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005161{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005162 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005163 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005164 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005165 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005166 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5167 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005168 source = sourceDesc;
5169 break;
5170 }
5171 }
5172 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005173}
5174
Eric Laurent39095982021-08-24 18:29:27 +02005175/* static */
5176bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5177 switch (channels) {
5178 case AUDIO_CHANNEL_OUT_5POINT1:
5179 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5180 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5181 case AUDIO_CHANNEL_OUT_7POINT1:
5182 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5183 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5184 return true;
5185 default:
5186 return false;
5187 }
5188}
5189
Eric Laurentb4f42a92022-01-17 17:37:31 +01005190bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005191 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005192 const AudioDeviceTypeAddrVector &devices,
5193 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005194{
5195 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5196 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005197 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005198 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005199 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5200 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5201 return false;
5202 }
5203 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5204 return false;
5205 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005206 }
5207
5208 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005209 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5210 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005211 // to the specified devices must exist.
5212 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005213 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005214 if (profile == nullptr) {
5215 return false;
5216 }
5217
5218 // The caller can have the audio config criteria ignored by either passing a null ptr or
5219 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005220 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005221 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005222 // If the spatializer output is already opened, only channel masks included in the
5223 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005224
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005225 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005226 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005227 return false;
5228 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005229 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5230 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005231 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005232 != config->channel_mask) {
5233 return false;
5234 }
5235 }
5236 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005237 return true;
5238}
5239
5240void AudioPolicyManager::checkVirtualizerClientRoutes() {
5241 std::set<audio_stream_type_t> streamsToInvalidate;
5242 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005243 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5244 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005245 audio_attributes_t attr = client->attributes();
5246 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5247 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5248 audio_config_base_t clientConfig = client->config();
5249 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005250 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005251 && canBeSpatializedInt(&attr, &config,
5252 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005253 streamsToInvalidate.insert(client->stream());
5254 }
5255 }
5256 }
5257
5258 for (audio_stream_type_t stream : streamsToInvalidate) {
5259 mpClientInterface->invalidateStream(stream);
5260 }
5261}
5262
Eric Laurentfa0f6742021-08-17 18:39:44 +02005263status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005264 const audio_attributes_t *attr,
5265 audio_io_handle_t *output) {
5266 *output = AUDIO_IO_HANDLE_NONE;
5267
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005268 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5269 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5270 audio_config_t *configPtr = nullptr;
5271 audio_config_t config;
5272 if (mixerConfig != nullptr) {
5273 config = audio_config_initializer(mixerConfig);
5274 configPtr = &config;
5275 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005276 if (!canBeSpatializedInt(
5277 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005278 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005279 return BAD_VALUE;
5280 }
5281
5282 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005283 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005284 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005285 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005286 return BAD_VALUE;
5287 }
5288
Eric Laurent39095982021-08-24 18:29:27 +02005289 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5290 && configPtr != nullptr
5291 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5292 *output = mSpatializerOutput->mIoHandle;
5293 ALOGV("%s returns current spatializer output %d", __func__, *output);
5294 return NO_ERROR;
5295 }
5296 mSpatializerOutput.clear();
5297 for (size_t i = 0; i < mOutputs.size(); i++) {
5298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5299 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005300 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005301 mSpatializerOutput = desc;
5302 break;
5303 }
5304 }
5305 if (mSpatializerOutput == nullptr) {
5306 ALOGW("%s no opened spatializer output for profile %s",
5307 __func__, profile->getName().c_str());
5308 return BAD_VALUE;
5309 }
5310
5311 if (configPtr != nullptr
5312 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5313 audio_config_base_t savedMixerConfig = {
5314 .sample_rate = mSpatializerOutput->getSamplingRate(),
5315 .format = mSpatializerOutput->getFormat(),
5316 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5317 };
5318 DeviceVector savedDevices = mSpatializerOutput->devices();
5319
Eric Laurentb4f42a92022-01-17 17:37:31 +01005320 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5321 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005322
Eric Laurentb4f42a92022-01-17 17:37:31 +01005323 closeOutput(mSpatializerOutput->mIoHandle);
5324 //from now on mSpatializerOutput is null
5325
5326 sp<SwAudioOutputDescriptor> desc =
5327 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5328 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005329 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005330 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5331 if (desc == nullptr) {
5332 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005333 } else {
5334 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005335 }
5336 mPreviousOutputs = mOutputs;
5337 mpClientInterface->onAudioPortListUpdate();
5338 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005339 ALOGW("%s could not open spatializer output with requested config", __func__);
5340 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005341 }
Eric Laurent39095982021-08-24 18:29:27 +02005342 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005343 mPreviousOutputs = mOutputs;
5344 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005345 }
5346
5347 checkVirtualizerClientRoutes();
5348
Eric Laurent39095982021-08-24 18:29:27 +02005349 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005350 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005351 return NO_ERROR;
5352}
5353
Eric Laurentfa0f6742021-08-17 18:39:44 +02005354status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5355 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005356 return INVALID_OPERATION;
5357 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005358 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005359 return BAD_VALUE;
5360 }
Eric Laurent39095982021-08-24 18:29:27 +02005361
Eric Laurentfa0f6742021-08-17 18:39:44 +02005362 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005363
5364 checkVirtualizerClientRoutes();
5365
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005366 return NO_ERROR;
5367}
5368
Eric Laurente552edb2014-03-10 17:42:56 -07005369// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005370// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005371// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005372uint32_t AudioPolicyManager::nextAudioPortGeneration()
5373{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005374 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005375}
5376
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005377static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005378 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5379 !audioPolicyXmlConfigFile.empty()) {
5380 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5381 if (ret == NO_ERROR) {
5382 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005383 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005384 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005385 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005386 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005387}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005388
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005389AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5390 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005391 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005392 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005393 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005394 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005395 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005396 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005397 mAudioPortGeneration(1),
5398 mBeaconMuteRefCount(0),
5399 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005400 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005401 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005402 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005403 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005404{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005405}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005406
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005407AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5408 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5409{
5410 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005411}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005412
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005413void AudioPolicyManager::loadConfig() {
5414 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005415 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005416 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005417 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005418}
5419
5420status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005421 {
5422 auto engLib = EngineLibrary::load(
5423 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5424 if (!engLib) {
5425 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5426 return NO_INIT;
5427 }
5428 mEngine = engLib->createEngine();
5429 if (mEngine == nullptr) {
5430 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5431 return NO_INIT;
5432 }
François Gaffie2110e042015-03-24 08:41:51 +01005433 }
5434 mEngine->setObserver(this);
5435 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005436 if (status != NO_ERROR) {
5437 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5438 return status;
5439 }
François Gaffie2110e042015-03-24 08:41:51 +01005440
Eric Laurent1d69c872021-01-11 18:53:01 +01005441 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5442 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5443
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005444 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005445 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005446 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005447
Eric Laurent3a4311c2014-03-17 12:00:47 -07005448 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005449 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5450 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5451 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005452 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005453 }
jiabin9ff780e2018-03-19 18:19:52 -07005454 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005455 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005456 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005457 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005458 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005459 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005460 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005461 }
5462 }
5463 }
Eric Laurente552edb2014-03-10 17:42:56 -07005464
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005465 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005466
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005467 // Silence ALOGV statements
5468 property_set("log.tag." LOG_TAG, "D");
5469
Eric Laurente552edb2014-03-10 17:42:56 -07005470 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005471 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005472}
5473
Eric Laurente0720872014-03-11 09:30:41 -07005474AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005475{
Eric Laurente552edb2014-03-10 17:42:56 -07005476 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005477 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005478 }
5479 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005480 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005481 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005482 mAvailableOutputDevices.clear();
5483 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005484 mOutputs.clear();
5485 mInputs.clear();
5486 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005487 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005488 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005489}
5490
Eric Laurente0720872014-03-11 09:30:41 -07005491status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005492{
Eric Laurent87ffa392015-05-22 10:32:38 -07005493 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005494}
5495
Eric Laurente552edb2014-03-10 17:42:56 -07005496// ---
5497
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005498void AudioPolicyManager::onNewAudioModulesAvailable()
5499{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005500 DeviceVector newDevices;
5501 onNewAudioModulesAvailableInt(&newDevices);
5502 if (!newDevices.empty()) {
5503 nextAudioPortGeneration();
5504 mpClientInterface->onAudioPortListUpdate();
5505 }
5506}
5507
5508void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5509{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005510 for (const auto& hwModule : mHwModulesAll) {
5511 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5512 continue;
5513 }
5514 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5515 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5516 ALOGW("could not open HW module %s", hwModule->getName());
5517 continue;
5518 }
5519 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005520 // open all output streams needed to access attached devices.
5521 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005522 // This also validates mAvailableOutputDevices list
5523 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5524 if (!outProfile->canOpenNewIo()) {
5525 ALOGE("Invalid Output profile max open count %u for profile %s",
5526 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5527 continue;
5528 }
5529 if (!outProfile->hasSupportedDevices()) {
5530 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5531 continue;
5532 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005533 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5534 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005535 mTtsOutputAvailable = true;
5536 }
5537
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005538 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5539 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5540 sp<DeviceDescriptor> supportedDevice = 0;
5541 if (supportedDevices.contains(mDefaultOutputDevice)) {
5542 supportedDevice = mDefaultOutputDevice;
5543 } else {
5544 // choose first device present in profile's SupportedDevices also part of
5545 // mAvailableOutputDevices.
5546 if (availProfileDevices.isEmpty()) {
5547 continue;
5548 }
5549 supportedDevice = availProfileDevices.itemAt(0);
5550 }
5551 if (!mOutputDevicesAll.contains(supportedDevice)) {
5552 continue;
5553 }
5554 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5555 mpClientInterface);
5556 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005557 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5558 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005559 AUDIO_STREAM_DEFAULT,
5560 AUDIO_OUTPUT_FLAG_NONE, &output);
5561 if (status != NO_ERROR) {
5562 ALOGW("Cannot open output stream for devices %s on hw module %s",
5563 supportedDevice->toString().c_str(), hwModule->getName());
5564 continue;
5565 }
5566 for (const auto &device : availProfileDevices) {
5567 // give a valid ID to an attached device once confirmed it is reachable
5568 if (!device->isAttached()) {
5569 device->attach(hwModule);
5570 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005571 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005572 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005573 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5574 }
5575 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005576 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005577 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5578 mPrimaryOutput = outputDesc;
5579 }
Eric Laurent39095982021-08-24 18:29:27 +02005580 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005581 outputDesc->close();
5582 } else {
5583 addOutput(output, outputDesc);
5584 setOutputDevices(outputDesc,
5585 DeviceVector(supportedDevice),
5586 true,
5587 0,
5588 NULL);
5589 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005590 }
5591 // open input streams needed to access attached devices to validate
5592 // mAvailableInputDevices list
5593 for (const auto& inProfile : hwModule->getInputProfiles()) {
5594 if (!inProfile->canOpenNewIo()) {
5595 ALOGE("Invalid Input profile max open count %u for profile %s",
5596 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5597 continue;
5598 }
5599 if (!inProfile->hasSupportedDevices()) {
5600 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5601 continue;
5602 }
5603 // chose first device present in profile's SupportedDevices also part of
5604 // available input devices
5605 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5606 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5607 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005608 ALOGV("%s: Input device list is empty! for profile %s",
5609 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005610 continue;
5611 }
5612 sp<AudioInputDescriptor> inputDesc =
5613 new AudioInputDescriptor(inProfile, mpClientInterface);
5614
5615 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5616 status_t status = inputDesc->open(nullptr,
5617 availProfileDevices.itemAt(0),
5618 AUDIO_SOURCE_MIC,
5619 AUDIO_INPUT_FLAG_NONE,
5620 &input);
5621 if (status != NO_ERROR) {
5622 ALOGW("Cannot open input stream for device %s on hw module %s",
5623 availProfileDevices.toString().c_str(),
5624 hwModule->getName());
5625 continue;
5626 }
5627 for (const auto &device : availProfileDevices) {
5628 // give a valid ID to an attached device once confirmed it is reachable
5629 if (!device->isAttached()) {
5630 device->attach(hwModule);
5631 device->importAudioPortAndPickAudioProfile(inProfile, true);
5632 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005633 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005634 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5635 }
5636 }
5637 inputDesc->close();
5638 }
5639 }
5640}
5641
Eric Laurent98e38192018-02-15 18:31:53 -08005642void AudioPolicyManager::addOutput(audio_io_handle_t output,
5643 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005644{
Eric Laurent1c333e22014-05-20 10:48:17 -07005645 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005646 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005647 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005648 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005649 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005650}
5651
François Gaffie53615e22015-03-19 09:24:12 +01005652void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5653{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005654 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5655 ALOGV("%s: removing primary output", __func__);
5656 mPrimaryOutput = nullptr;
5657 }
François Gaffie53615e22015-03-19 09:24:12 +01005658 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005659 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005660}
5661
Eric Laurent98e38192018-02-15 18:31:53 -08005662void AudioPolicyManager::addInput(audio_io_handle_t input,
5663 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005664{
Eric Laurent1c333e22014-05-20 10:48:17 -07005665 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005666 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005667}
Eric Laurente552edb2014-03-10 17:42:56 -07005668
François Gaffie11d30102018-11-02 16:09:09 +01005669status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005670 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005671 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005672{
François Gaffie11d30102018-11-02 16:09:09 +01005673 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005674 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005675 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005676
François Gaffie11d30102018-11-02 16:09:09 +01005677 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005678 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005679 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005680 }
Eric Laurente552edb2014-03-10 17:42:56 -07005681
Eric Laurent3b73df72014-03-11 09:06:29 -07005682 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005683 // first call getAudioPort to get the supported attributes from the HAL
5684 struct audio_port_v7 port = {};
5685 device->toAudioPort(&port);
5686 status_t status = mpClientInterface->getAudioPort(&port);
5687 if (status == NO_ERROR) {
5688 device->importAudioPort(port);
5689 }
5690
5691 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005692 for (size_t i = 0; i < mOutputs.size(); i++) {
5693 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005694 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005695 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005696 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5697 mOutputs.keyAt(i), device->toString().c_str());
5698 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005699 }
5700 }
5701 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005702 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005703 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005704 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5705 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005706 if (profile->supportsDevice(device)) {
5707 profiles.add(profile);
5708 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5709 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005710 }
5711 }
5712 }
5713
Eric Laurent7b279bb2015-12-14 10:18:23 -08005714 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005715
Eric Laurente552edb2014-03-10 17:42:56 -07005716 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005717 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005718 return BAD_VALUE;
5719 }
5720
5721 // open outputs for matching profiles if needed. Direct outputs are also opened to
5722 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5723 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005724 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005725
5726 // nothing to do if one output is already opened for this profile
5727 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005728 for (j = 0; j < outputs.size(); j++) {
5729 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005730 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005731 // matching profile: save the sample rates, format and channel masks supported
5732 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005733 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005734 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005735 }
Eric Laurente552edb2014-03-10 17:42:56 -07005736 break;
5737 }
5738 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005739 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005740 continue;
5741 }
5742
Eric Laurent3974e3b2017-12-07 17:58:43 -08005743 if (!profile->canOpenNewIo()) {
5744 ALOGW("Max Output number %u already opened for this profile %s",
5745 profile->maxOpenCount, profile->getTagName().c_str());
5746 continue;
5747 }
5748
Eric Laurent83efe1c2017-07-09 16:51:08 -07005749 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005750 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005751 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5752 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005753 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005754 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005755 profiles.removeAt(profile_index);
5756 profile_index--;
5757 } else {
5758 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005759 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005760 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005761 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5762 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005763 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005764 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005765
François Gaffie11d30102018-11-02 16:09:09 +01005766 if (device_distinguishes_on_address(deviceType)) {
5767 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5768 device->toString().c_str());
5769 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5770 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005771 }
Eric Laurente552edb2014-03-10 17:42:56 -07005772 ALOGV("checkOutputsForDevice(): adding output %d", output);
5773 }
5774 }
5775
5776 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005777 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005778 return BAD_VALUE;
5779 }
Eric Laurentd4692962014-05-05 18:13:44 -07005780 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005781 // check if one opened output is not needed any more after disconnecting one device
5782 for (size_t i = 0; i < mOutputs.size(); i++) {
5783 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005784 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005785 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005786 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005787 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005788 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005789 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005790 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5791 mOutputs.keyAt(i));
5792 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005793 }
Eric Laurente552edb2014-03-10 17:42:56 -07005794 }
5795 }
Eric Laurentd4692962014-05-05 18:13:44 -07005796 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005797 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005798 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5799 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005800 if (!profile->supportsDevice(device)) {
5801 continue;
5802 }
5803 ALOGV("checkOutputsForDevice(): "
5804 "clearing direct output profile %zu on module %s",
5805 j, hwModule->getName());
5806 profile->clearAudioProfiles();
5807 if (!profile->hasDynamicAudioProfile()) {
5808 continue;
5809 }
5810 // When a device is disconnected, if there is an IOProfile that contains dynamic
5811 // profiles and supports the disconnected device, call getAudioPort to repopulate
5812 // the capabilities of the devices that is supported by the IOProfile.
5813 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5814 if (supportedDevice == device ||
5815 !mAvailableOutputDevices.contains(supportedDevice)) {
5816 continue;
5817 }
5818 struct audio_port_v7 port;
5819 supportedDevice->toAudioPort(&port);
5820 status_t status = mpClientInterface->getAudioPort(&port);
5821 if (status == NO_ERROR) {
5822 supportedDevice->importAudioPort(port);
5823 }
Eric Laurente552edb2014-03-10 17:42:56 -07005824 }
5825 }
5826 }
5827 }
5828 return NO_ERROR;
5829}
5830
François Gaffie11d30102018-11-02 16:09:09 +01005831status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005832 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005833{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005834 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005835
François Gaffie11d30102018-11-02 16:09:09 +01005836 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005837 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005838 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005839 }
5840
Eric Laurentd4692962014-05-05 18:13:44 -07005841 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005842 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005843 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005844 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005845 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005846 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005847 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005848 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005849
François Gaffie11d30102018-11-02 16:09:09 +01005850 if (profile->supportsDevice(device)) {
5851 profiles.add(profile);
5852 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5853 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005854 }
5855 }
5856 }
5857
Eric Laurent0dd51852019-04-19 18:18:58 -07005858 if (profiles.isEmpty()) {
5859 ALOGW("%s: No input profile available for device %s",
5860 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005861 return BAD_VALUE;
5862 }
5863
5864 // open inputs for matching profiles if needed. Direct inputs are also opened to
5865 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5866 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5867
Eric Laurent1c333e22014-05-20 10:48:17 -07005868 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005869
Eric Laurentd4692962014-05-05 18:13:44 -07005870 // nothing to do if one input is already opened for this profile
5871 size_t input_index;
5872 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5873 desc = mInputs.valueAt(input_index);
5874 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005875 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005876 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005877 }
Eric Laurentd4692962014-05-05 18:13:44 -07005878 break;
5879 }
5880 }
5881 if (input_index != mInputs.size()) {
5882 continue;
5883 }
5884
Eric Laurent3974e3b2017-12-07 17:58:43 -08005885 if (!profile->canOpenNewIo()) {
5886 ALOGW("Max Input number %u already opened for this profile %s",
5887 profile->maxOpenCount, profile->getTagName().c_str());
5888 continue;
5889 }
5890
Eric Laurentfe231122017-11-17 17:48:06 -08005891 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005892 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005893 status_t status = desc->open(nullptr,
5894 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005895 AUDIO_SOURCE_MIC,
5896 AUDIO_INPUT_FLAG_NONE,
5897 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005898
Eric Laurentcf2c0212014-07-25 16:20:43 -07005899 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005900 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005901 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005902 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005903 mpClientInterface->setParameters(input, String8(param));
5904 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005905 }
François Gaffie11d30102018-11-02 16:09:09 +01005906 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005907 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005908 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005909 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005910 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005911 }
5912
Eric Laurent0dd51852019-04-19 18:18:58 -07005913 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005914 addInput(input, desc);
5915 }
5916 } // endif input != 0
5917
Eric Laurentcf2c0212014-07-25 16:20:43 -07005918 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005919 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005920 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005921 profiles.removeAt(profile_index);
5922 profile_index--;
5923 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005924 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005925 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005926 }
Eric Laurentd4692962014-05-05 18:13:44 -07005927 ALOGV("checkInputsForDevice(): adding input %d", input);
5928 }
5929 } // end scan profiles
5930
5931 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005932 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005933 return BAD_VALUE;
5934 }
5935 } else {
5936 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005937 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005938 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005939 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005940 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005941 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005942 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005943 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005944 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5945 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005946 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005947 }
5948 }
5949 }
5950 } // end disconnect
5951
5952 return NO_ERROR;
5953}
5954
5955
Eric Laurente0720872014-03-11 09:30:41 -07005956void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005957{
5958 ALOGV("closeOutput(%d)", output);
5959
François Gaffie1c878552018-11-22 16:53:21 +01005960 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5961 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005962 ALOGW("closeOutput() unknown output %d", output);
5963 return;
5964 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005965 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005966 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005967
Eric Laurente552edb2014-03-10 17:42:56 -07005968 // look for duplicated outputs connected to the output being removed.
5969 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005970 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5971 if (dupOutput->isDuplicated() &&
5972 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5973 sp<SwAudioOutputDescriptor> remainingOutput =
5974 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005975 // As all active tracks on duplicated output will be deleted,
5976 // and as they were also referenced on the other output, the reference
5977 // count for their stream type must be adjusted accordingly on
5978 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005979 const bool wasActive = remainingOutput->isActive();
5980 // Note: no-op on the closing output where all clients has already been set inactive
5981 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005982 // stop() will be a no op if the output is still active but is needed in case all
5983 // active streams refcounts where cleared above
5984 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005985 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005986 }
Eric Laurente552edb2014-03-10 17:42:56 -07005987 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5988 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5989
5990 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005991 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005992 }
5993 }
5994
Eric Laurent05b90f82014-08-27 15:32:29 -07005995 nextAudioPortGeneration();
5996
François Gaffie1c878552018-11-22 16:53:21 +01005997 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005998 if (index >= 0) {
5999 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006000 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6001 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006002 mAudioPatches.removeItemsAt(index);
6003 mpClientInterface->onAudioPatchListUpdate();
6004 }
6005
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006006 if (closingOutputWasActive) {
6007 closingOutput->stop();
6008 }
François Gaffie1c878552018-11-22 16:53:21 +01006009 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006010
François Gaffie53615e22015-03-19 09:24:12 +01006011 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006012 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006013 if (closingOutput == mSpatializerOutput) {
6014 mSpatializerOutput.clear();
6015 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006016
6017 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6018 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006019 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006020 bool directOutputOpen = false;
6021 for (size_t i = 0; i < mOutputs.size(); i++) {
6022 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6023 directOutputOpen = true;
6024 break;
6025 }
6026 }
6027 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006028 ALOGV("no direct outputs open, reset MSD patches");
6029 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6030 // how output devices for patching are resolved. Avoid by caching and reusing the
6031 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6032 // devices to patch to. This may be complicated by the fact that devices may become
6033 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006034 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006035 }
6036 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006037}
6038
6039void AudioPolicyManager::closeInput(audio_io_handle_t input)
6040{
6041 ALOGV("closeInput(%d)", input);
6042
6043 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6044 if (inputDesc == NULL) {
6045 ALOGW("closeInput() unknown input %d", input);
6046 return;
6047 }
6048
Eric Laurent6a94d692014-05-20 11:18:06 -07006049 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006050
François Gaffie11d30102018-11-02 16:09:09 +01006051 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006052 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006053 if (index >= 0) {
6054 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006055 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6056 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006057 mAudioPatches.removeItemsAt(index);
6058 mpClientInterface->onAudioPatchListUpdate();
6059 }
6060
Eric Laurentfe231122017-11-17 17:48:06 -08006061 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006062 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006063
François Gaffie11d30102018-11-02 16:09:09 +01006064 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6065 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006066 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006067 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006068 }
Eric Laurente552edb2014-03-10 17:42:56 -07006069}
6070
François Gaffie11d30102018-11-02 16:09:09 +01006071SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6072 const DeviceVector &devices,
6073 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006074{
6075 SortedVector<audio_io_handle_t> outputs;
6076
François Gaffie11d30102018-11-02 16:09:09 +01006077 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006078 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006079 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006080 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006081 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006082 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006083 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006084 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006085 outputs.add(openOutputs.keyAt(i));
6086 }
6087 }
6088 return outputs;
6089}
6090
Mikhail Naganov37977152018-07-11 15:54:44 -07006091void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6092{
6093 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6094 // output is suspended before any tracks are moved to it
6095 checkA2dpSuspend();
6096 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006097 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006098 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006099 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006100 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006101 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6102 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6103 // configuration changes will ultimately be rerouted correctly. We can still avoid
6104 // unnecessary rerouting by caching and reusing the arguments to
6105 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6106 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006107 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006108 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006109 // an event that changed routing likely occurred, inform upper layers
6110 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006111}
6112
François Gaffiec005e562018-11-06 15:04:49 +01006113bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6114 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006115{
François Gaffiec005e562018-11-06 15:04:49 +01006116 return mEngine->getProductStrategyForAttributes(lAttr) ==
6117 mEngine->getProductStrategyForAttributes(rAttr);
6118}
6119
Francois Gaffieff1eb522020-05-06 18:37:04 +02006120void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6121{
6122 for (size_t i = 0; i < mAudioSources.size(); i++) {
6123 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6124 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006125 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006126 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006127 connectAudioSource(sourceDesc);
6128 }
6129 }
6130}
6131
6132void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6133{
6134 for (size_t i = 0; i < mAudioSources.size(); i++) {
6135 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6136 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6137 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6138 disconnectAudioSource(sourceDesc);
6139 }
6140 }
6141}
6142
François Gaffiec005e562018-11-06 15:04:49 +01006143void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6144{
6145 auto psId = mEngine->getProductStrategyForAttributes(attr);
6146
6147 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6148 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006149
François Gaffie11d30102018-11-02 16:09:09 +01006150 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6151 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006152
Eric Laurentc209fe42020-06-05 18:11:23 -07006153 uint32_t maxLatency = 0;
6154 bool invalidate = false;
6155 // take into account dynamic audio policies related changes: if a client is now associated
6156 // to a different policy mix than at creation time, invalidate corresponding stream
6157 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6158 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6159 if (desc->isDuplicated()) {
6160 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006161 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006162 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6163 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6164 continue;
6165 }
6166 sp<AudioPolicyMix> primaryMix;
6167 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6168 client->flags(), primaryMix, nullptr);
6169 if (status != OK) {
6170 continue;
6171 }
yucliuf4de36d2020-09-14 14:57:56 -07006172 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006173 invalidate = true;
6174 if (desc->isStrategyActive(psId)) {
6175 maxLatency = desc->latency();
6176 }
6177 break;
6178 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006179 }
6180 }
6181
Eric Laurentc209fe42020-06-05 18:11:23 -07006182 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006183 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6184 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006185 for (audio_io_handle_t srcOut : srcOutputs) {
6186 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006187 if (desc == nullptr) continue;
6188
6189 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006190 maxLatency = desc->latency();
6191 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006192
6193 if (invalidate) continue;
6194
6195 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006196 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006197 // a client on a non direct outputs has necessarily a linear PCM format
6198 // so we can call selectOutput() safely
6199 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6200 client->flags(),
6201 client->config().format,
6202 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006203 client->config().sample_rate,
6204 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006205 if (newOutput != srcOut) {
6206 invalidate = true;
6207 break;
6208 }
6209 } else {
6210 sp<IOProfile> profile = getProfileForOutput(newDevices,
6211 client->config().sample_rate,
6212 client->config().format,
6213 client->config().channel_mask,
6214 client->flags(),
6215 true /* directOnly */);
6216 if (profile != desc->mProfile) {
6217 invalidate = true;
6218 break;
6219 }
6220 }
6221 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006222 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006223
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006224 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006225 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006226 std::to_string(srcOutputs[0]).c_str(),
6227 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006228 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006229 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006230 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006231 if (desc == nullptr) continue;
6232
6233 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006234 setStrategyMute(psId, true, desc);
6235 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006236 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006237 }
François Gaffiec005e562018-11-06 15:04:49 +01006238 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006239 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006240 connectAudioSource(source);
6241 }
Eric Laurente552edb2014-03-10 17:42:56 -07006242 }
6243
François Gaffiec005e562018-11-06 15:04:49 +01006244 // Move effects associated to this stream from previous output to new output
6245 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006246 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006247 }
François Gaffiec005e562018-11-06 15:04:49 +01006248 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006249 if (invalidate) {
6250 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6251 mpClientInterface->invalidateStream(stream);
6252 }
Eric Laurente552edb2014-03-10 17:42:56 -07006253 }
6254 }
6255}
6256
Eric Laurente0720872014-03-11 09:30:41 -07006257void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006258{
François Gaffiec005e562018-11-06 15:04:49 +01006259 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6260 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6261 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006262 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006263 }
Eric Laurente552edb2014-03-10 17:42:56 -07006264}
6265
Kevin Rocard153f92d2018-12-18 18:33:28 -08006266void AudioPolicyManager::checkSecondaryOutputs() {
6267 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006268 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006269 for (size_t i = 0; i < mOutputs.size(); i++) {
6270 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6271 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006272 sp<AudioPolicyMix> primaryMix;
6273 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006274 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006275 client->flags(), primaryMix, &secondaryMixes);
6276 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6277 for (auto &secondaryMix : secondaryMixes) {
6278 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6279 if (outputDesc != nullptr &&
6280 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6281 secondaryDescs.push_back(outputDesc);
6282 }
6283 }
6284
jiabin10a03f12021-05-07 23:46:28 +00006285 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006286 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006287 } else if (!std::equal(
6288 client->getSecondaryOutputs().begin(),
6289 client->getSecondaryOutputs().end(),
6290 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006291 if (!audio_is_linear_pcm(client->config().format)) {
6292 // If the format is not PCM, the tracks should be invalidated to get correct
6293 // behavior when the secondary output is changed.
6294 streamsToInvalidate.insert(client->stream());
6295 } else {
6296 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6297 std::vector<audio_io_handle_t> secondaryOutputIds;
6298 for (const auto &secondaryDesc: secondaryDescs) {
6299 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6300 weakSecondaryDescs.push_back(secondaryDesc);
6301 }
6302 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6303 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006304 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006305 }
6306 }
6307 }
jiabin10a03f12021-05-07 23:46:28 +00006308 if (!trackSecondaryOutputs.empty()) {
6309 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6310 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006311 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006312 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006313 mpClientInterface->invalidateStream(stream);
6314 }
6315}
6316
Eric Laurent2517af32020-11-25 15:31:27 +01006317bool AudioPolicyManager::isScoRequestedForComm() const {
6318 AudioDeviceTypeAddrVector devices;
6319 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6320 for (const auto &device : devices) {
6321 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6322 return true;
6323 }
6324 }
6325 return false;
6326}
6327
Eric Laurente0720872014-03-11 09:30:41 -07006328void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006329{
François Gaffie53615e22015-03-19 09:24:12 +01006330 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006331 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006332 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006333 return;
6334 }
6335
Eric Laurent3a4311c2014-03-17 12:00:47 -07006336 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006337 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6338 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006339 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006340
6341 // if suspended, restore A2DP output if:
6342 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006343 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006344 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006345 //
Eric Laurentf732e072016-08-03 19:30:28 -07006346 // if not suspended, suspend A2DP output if:
6347 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006348 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006349 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006350 //
6351 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006352 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006353 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006354 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006355 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006356
6357 mpClientInterface->restoreOutput(a2dpOutput);
6358 mA2dpSuspended = false;
6359 }
6360 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006361 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006362 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006363 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006364 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006365
6366 mpClientInterface->suspendOutput(a2dpOutput);
6367 mA2dpSuspended = true;
6368 }
6369 }
6370}
6371
François Gaffie11d30102018-11-02 16:09:09 +01006372DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6373 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006374{
François Gaffie11d30102018-11-02 16:09:09 +01006375 DeviceVector devices;
6376
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006377 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006378 if (index >= 0) {
6379 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006380 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006381 ALOGV("%s device %s forced by patch %d", __func__,
6382 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6383 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006384 }
6385 }
6386
Dean Wheatley514b4312020-06-17 21:45:00 +10006387 // Do not retrieve engine device for outputs through MSD
6388 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6389 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6390 return outputDesc->devices();
6391 }
6392
Eric Laurent97ac8712018-07-27 18:59:02 -07006393 // Honor explicit routing requests only if no client using default routing is active on this
6394 // input: a specific app can not force routing for other apps by setting a preferred device.
6395 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006396 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006397 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006398 if (device != nullptr) {
6399 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006400 }
6401
François Gaffiea807ef92018-11-05 10:44:33 +01006402 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6403 // of setForceUse / Default Bus device here
6404 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6405 if (device != nullptr) {
6406 return DeviceVector(device);
6407 }
6408
François Gaffiec005e562018-11-06 15:04:49 +01006409 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6410 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6411 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306412 auto hasStreamActive = [&](auto stream) {
6413 return hasStream(streams, stream) && isStreamActive(stream, 0);
6414 };
Eric Laurent484e9272018-06-07 17:29:23 -07006415
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306416 auto doGetOutputDevicesForVoice = [&]() {
6417 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006418 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306419 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006420 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6421 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306422 };
6423
6424 // With low-latency playing on speaker, music on WFD, when the first low-latency
6425 // output is stopped, getNewOutputDevices checks for a product strategy
6426 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006427 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306428 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6429 // stream is associated to the output descriptor.
6430 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6431 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6432 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6433 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006434 // Retrieval of devices for voice DL is done on primary output profile, cannot
6435 // check the route (would force modifying configuration file for this profile)
6436 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6437 break;
6438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439 }
François Gaffiec005e562018-11-06 15:04:49 +01006440 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006441 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006442}
6443
François Gaffie11d30102018-11-02 16:09:09 +01006444sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6445 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006446{
François Gaffie11d30102018-11-02 16:09:09 +01006447 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006448
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006449 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006450 if (index >= 0) {
6451 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006452 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006453 ALOGV("getNewInputDevice() device %s forced by patch %d",
6454 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6455 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006456 }
6457 }
6458
Eric Laurent97ac8712018-07-27 18:59:02 -07006459 // Honor explicit routing requests only if no client using default routing is active on this
6460 // input: a specific app can not force routing for other apps by setting a preferred device.
6461 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006462 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6463 if (device != nullptr) {
6464 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006465 }
6466
Eric Laurentdc95a252018-04-12 12:46:56 -07006467 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006468 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006469 audio_attributes_t attributes;
6470 uid_t uid;
6471 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6472 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006473 attributes = topClient->attributes();
6474 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006475 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006476 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6477 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006478 }
6479
Francois Gaffie716e1432019-01-14 16:58:59 +01006480 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6481 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006482 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006483 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006484 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006485 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006486
Eric Laurente552edb2014-03-10 17:42:56 -07006487 return device;
6488}
6489
Eric Laurent794fde22016-03-11 09:50:45 -08006490bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6491 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006492 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006493}
6494
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006495DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006496 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006497 // getOutputDevicesForStream's behavior for invalid streams.
6498 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6499 // device for music stream), but we want to return the empty set.
6500 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006501 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006502 }
François Gaffie11d30102018-11-02 16:09:09 +01006503 DeviceVector activeDevices;
6504 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006505 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6506 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006507 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006508 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006509 }
François Gaffiec005e562018-11-06 15:04:49 +01006510 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006511 devices.merge(curDevices);
6512 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006513 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006514 if (outputDesc->isActive(toVolumeSource(curStream, false))) {
François Gaffie11d30102018-11-02 16:09:09 +01006515 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006516 }
6517 }
Eric Laurente552edb2014-03-10 17:42:56 -07006518 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006519
Eric Laurentb0688d62018-08-14 15:49:18 -07006520 // Favor devices selected on active streams if any to report correct device in case of
6521 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006522 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006523 devices = activeDevices;
6524 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006525 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6526 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006527 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006528 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006529 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006530 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006531 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006532 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006533}
6534
Dorin Drimusf2196d82022-01-03 12:11:18 +01006535// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006536status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006537 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006538 if (devices == nullptr) {
6539 return BAD_VALUE;
6540 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006541
6542 // Devices are determined in the following precedence:
6543 //
6544 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6545 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6546 //
6547 // If no such dynamic policy then
6548 // 2) Devices containing an active client using setPreferredDevice
6549 // with same strategy as the attributes.
6550 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6551 //
6552 // If no corresponding active client with setPreferredDevice then
6553 // 3) Devices associated with the strategy determined by the attributes
6554 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6555 //
6556 // See related getOutputForAttrInt().
6557
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006558 // check dynamic policies but only for primary descriptors (secondary not used for audible
6559 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006560 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006561 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006562 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006563 if (status != OK) {
6564 return status;
6565 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006566
6567 DeviceVector curDevices;
6568 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6569 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6570 // as they are unaffected by device/stream volume
6571 // (per SwAudioOutputDescriptor::isFixedVolume()).
6572 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6573 ) {
6574 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6575 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6576 curDevices.add(deviceDesc);
6577 } else {
6578 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6579 // which selects setPreferredDevice if active. This means forVolume call
6580 // will take an active setPreferredDevice, if such exists.
6581
6582 curDevices = mEngine->getOutputDevicesForAttributes(
6583 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006584 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006585
6586 if (forVolume) {
6587 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6588 // for single volume control in AudioService (such relationship should exist if
6589 // SPEAKER_SAFE is present).
6590 //
6591 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6592 DeviceVector speakerSafeDevices =
6593 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6594 if (!speakerSafeDevices.isEmpty()) {
6595 curDevices.merge(
6596 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6597 curDevices.remove(speakerSafeDevices);
6598 }
6599 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006600 for (const auto& device : curDevices) {
6601 devices->push_back(device->getDeviceTypeAddr());
6602 }
6603 return NO_ERROR;
6604}
6605
Eric Laurente0720872014-03-11 09:30:41 -07006606void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006607 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006608 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006609 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006610 updateDevicesAndOutputs();
6611 break;
6612 default:
6613 break;
6614 }
6615}
6616
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006617uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006618
6619 // skip beacon mute management if a dedicated TTS output is available
6620 if (mTtsOutputAvailable) {
6621 return 0;
6622 }
6623
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006624 switch(event) {
6625 case STARTING_OUTPUT:
6626 mBeaconMuteRefCount++;
6627 break;
6628 case STOPPING_OUTPUT:
6629 if (mBeaconMuteRefCount > 0) {
6630 mBeaconMuteRefCount--;
6631 }
6632 break;
6633 case STARTING_BEACON:
6634 mBeaconPlayingRefCount++;
6635 break;
6636 case STOPPING_BEACON:
6637 if (mBeaconPlayingRefCount > 0) {
6638 mBeaconPlayingRefCount--;
6639 }
6640 break;
6641 }
6642
6643 if (mBeaconMuteRefCount > 0) {
6644 // any playback causes beacon to be muted
6645 return setBeaconMute(true);
6646 } else {
6647 // no other playback: unmute when beacon starts playing, mute when it stops
6648 return setBeaconMute(mBeaconPlayingRefCount == 0);
6649 }
6650}
6651
6652uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6653 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6654 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6655 // keep track of muted state to avoid repeating mute/unmute operations
6656 if (mBeaconMuted != mute) {
6657 // mute/unmute AUDIO_STREAM_TTS on all outputs
6658 ALOGV("\t muting %d", mute);
6659 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006660 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6661 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6662 ALOGV("\t no tts volume source available");
6663 return 0;
6664 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006665 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006666 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006667 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006668 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006669 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006670 maxLatency = latency;
6671 }
6672 }
6673 mBeaconMuted = mute;
6674 return maxLatency;
6675 }
6676 return 0;
6677}
6678
Eric Laurente0720872014-03-11 09:30:41 -07006679void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006680{
François Gaffiec005e562018-11-06 15:04:49 +01006681 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006682 mPreviousOutputs = mOutputs;
6683}
6684
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006685uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006686 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006687 uint32_t delayMs)
6688{
6689 // mute/unmute strategies using an incompatible device combination
6690 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6691 // if unmuting, unmute only after the specified delay
6692 if (outputDesc->isDuplicated()) {
6693 return 0;
6694 }
6695
6696 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006697 DeviceVector devices = outputDesc->devices();
6698 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006699
François Gaffiec005e562018-11-06 15:04:49 +01006700 auto productStrategies = mEngine->getOrderedProductStrategies();
6701 for (const auto &productStrategy : productStrategies) {
6702 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6703 DeviceVector curDevices =
6704 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6705 curDevices = curDevices.filter(outputDesc->supportedDevices());
6706 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006707 bool doMute = false;
6708
François Gaffiec005e562018-11-06 15:04:49 +01006709 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006710 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006711 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6712 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006713 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006714 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006715 }
Eric Laurent99401132014-05-07 19:48:15 -07006716 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006717 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006718 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006719 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006720 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006721 continue;
6722 }
François Gaffiec005e562018-11-06 15:04:49 +01006723 ALOGVV("%s() %s (curDevice %s)", __func__,
6724 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6725 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6726 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006727 if (mute) {
6728 // FIXME: should not need to double latency if volume could be applied
6729 // immediately by the audioflinger mixer. We must account for the delay
6730 // between now and the next time the audioflinger thread for this output
6731 // will process a buffer (which corresponds to one buffer size,
6732 // usually 1/2 or 1/4 of the latency).
6733 if (muteWaitMs < desc->latency() * 2) {
6734 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006735 }
6736 }
6737 }
6738 }
6739 }
6740 }
6741
Eric Laurent99401132014-05-07 19:48:15 -07006742 // temporary mute output if device selection changes to avoid volume bursts due to
6743 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006744 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006745 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006746
Eric Laurentdc462862016-07-19 12:29:53 -07006747 if (muteWaitMs < tempMuteWaitMs) {
6748 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006749 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006750
6751 // If recommended duration is defined, replace temporary mute duration to avoid
6752 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6753 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6754 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6755 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6756 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6757
François Gaffieaaac0fd2018-11-22 17:56:39 +01006758 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6759 // make sure that we do not start the temporary mute period too early in case of
6760 // delayed device change
6761 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6762 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006763 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006764 }
6765 }
6766
Eric Laurente552edb2014-03-10 17:42:56 -07006767 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6768 if (muteWaitMs > delayMs) {
6769 muteWaitMs -= delayMs;
6770 usleep(muteWaitMs * 1000);
6771 return muteWaitMs;
6772 }
6773 return 0;
6774}
6775
François Gaffie11d30102018-11-02 16:09:09 +01006776uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6777 const DeviceVector &devices,
6778 bool force,
6779 int delayMs,
6780 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006781 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006782{
François Gaffie11d30102018-11-02 16:09:09 +01006783 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006784 uint32_t muteWaitMs;
6785
6786 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006787 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6788 nullptr /* patchHandle */, requiresMuteCheck);
6789 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6790 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006791 return muteWaitMs;
6792 }
Eric Laurente552edb2014-03-10 17:42:56 -07006793
6794 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006795 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006796 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006797 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006798
François Gaffie11d30102018-11-02 16:09:09 +01006799 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6800
6801 if (!filteredDevices.isEmpty()) {
6802 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006803 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006804
6805 // if the outputs are not materially active, there is no need to mute.
6806 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006807 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006808 } else {
6809 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6810 muteWaitMs = 0;
6811 }
Eric Laurente552edb2014-03-10 17:42:56 -07006812
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006813 bool outputRouted = outputDesc->isRouted();
6814
Eric Laurent79ea9582020-06-11 18:49:24 -07006815 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6816 // output profile or if new device is not supported AND previous device(s) is(are) still
6817 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006818 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006819 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6820 // restore previous device after evaluating strategy mute state
6821 outputDesc->setDevices(prevDevices);
6822 return muteWaitMs;
6823 }
6824
Eric Laurente552edb2014-03-10 17:42:56 -07006825 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006826 // the requested device is AUDIO_DEVICE_NONE
6827 // OR the requested device is the same as current device
6828 // AND force is not specified
6829 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006830 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006831 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006832 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6833 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006834 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6835 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6836 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6837 }
Eric Laurente552edb2014-03-10 17:42:56 -07006838 return muteWaitMs;
6839 }
6840
François Gaffie11d30102018-11-02 16:09:09 +01006841 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006842
Eric Laurente552edb2014-03-10 17:42:56 -07006843 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006844 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006845 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006846 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006847 PatchBuilder patchBuilder;
6848 patchBuilder.addSource(outputDesc);
6849 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6850 for (const auto &filteredDevice : filteredDevices) {
6851 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006852 }
6853
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006854 // Add half reported latency to delayMs when muteWaitMs is null in order
6855 // to avoid disordered sequence of muting volume and changing devices.
6856 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6857 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006858 }
Eric Laurente552edb2014-03-10 17:42:56 -07006859
6860 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006861 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006862
6863 return muteWaitMs;
6864}
6865
Eric Laurentc75307b2015-03-17 15:29:32 -07006866status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006867 int delayMs,
6868 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006869{
Eric Laurent6a94d692014-05-20 11:18:06 -07006870 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006871 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6872 return INVALID_OPERATION;
6873 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006874 if (patchHandle) {
6875 index = mAudioPatches.indexOfKey(*patchHandle);
6876 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006877 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006878 }
6879 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006880 return INVALID_OPERATION;
6881 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006882 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006883 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006884 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006885 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006886 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006887 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006888 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006889 return status;
6890}
6891
6892status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006893 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006894 bool force,
6895 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006896{
6897 status_t status = NO_ERROR;
6898
Eric Laurent1f2f2232014-06-02 12:01:23 -07006899 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006900 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6901 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006902
François Gaffie11d30102018-11-02 16:09:09 +01006903 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006904 PatchBuilder patchBuilder;
6905 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006906 // AUDIO_SOURCE_HOTWORD is for internal use only:
6907 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006908 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6909 auto result = usecase;
6910 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6911 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6912 }
6913 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006914 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006915 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006916 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006917 }
6918 }
6919 return status;
6920}
6921
Eric Laurent6a94d692014-05-20 11:18:06 -07006922status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6923 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006924{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006925 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006926 ssize_t index;
6927 if (patchHandle) {
6928 index = mAudioPatches.indexOfKey(*patchHandle);
6929 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006930 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006931 }
6932 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006933 return INVALID_OPERATION;
6934 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006935 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006936 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006937 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006938 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006939 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006940 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006941 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006942 return status;
6943}
6944
François Gaffie11d30102018-11-02 16:09:09 +01006945sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006946 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006947 audio_format_t& format,
6948 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006949 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006950{
6951 // Choose an input profile based on the requested capture parameters: select the first available
6952 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006953 //
6954 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6955 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006956
Glenn Kasten730b9262018-03-29 15:01:26 -07006957 sp<IOProfile> firstInexact;
6958 uint32_t updatedSamplingRate = 0;
6959 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6960 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006961 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006962 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006963 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006964 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006965 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006966 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006967 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006968 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006969 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006970 &channelMask /*updatedChannelMask*/,
6971 // FIXME ugly cast
6972 (audio_output_flags_t) flags,
6973 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006974 return profile;
6975 }
François Gaffie11d30102018-11-02 16:09:09 +01006976 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006977 samplingRate,
6978 &updatedSamplingRate,
6979 format,
6980 &updatedFormat,
6981 channelMask,
6982 &updatedChannelMask,
6983 // FIXME ugly cast
6984 (audio_output_flags_t) flags,
6985 false /*exactMatchRequiredForInputFlags*/)) {
6986 firstInexact = profile;
6987 }
6988
Eric Laurente552edb2014-03-10 17:42:56 -07006989 }
6990 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006991 if (firstInexact != nullptr) {
6992 samplingRate = updatedSamplingRate;
6993 format = updatedFormat;
6994 channelMask = updatedChannelMask;
6995 return firstInexact;
6996 }
Eric Laurente552edb2014-03-10 17:42:56 -07006997 return NULL;
6998}
6999
François Gaffieaaac0fd2018-11-22 17:56:39 +01007000float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7001 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007002 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007003 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007004{
jiabin9a3361e2019-10-01 09:38:30 -07007005 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007006
7007 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7008 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7009 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7010 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007011 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7012 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7013 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7014 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7015 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007016
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007017 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007018 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7019 mOutputs.isActive(ringVolumeSrc, 0)) {
7020 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007021 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007022 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007023 }
7024
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007025 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007026 if ((volumeSource != callVolumeSrc && (isInCall() ||
7027 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007028 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007029 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7030 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007031 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7032 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7033 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007034 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007035 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007036 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007037 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007038 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007039 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007040 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7041 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7042 // programmatically muted.
7043 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7044 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7045 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007046 bool exemptFromCapping =
7047 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7048 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007049 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7050 volumeSource, volumeDb);
7051 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007052 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7053 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7054 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007055 }
7056 }
Eric Laurente552edb2014-03-10 17:42:56 -07007057 // if a headset is connected, apply the following rules to ring tones and notifications
7058 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007059 // - always attenuate notifications volume by 6dB
7060 // - attenuate ring tones volume by 6dB unless music is not playing and
7061 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007062 // - if music is playing, always limit the volume to current music volume,
7063 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007064 if (!Intersection(deviceTypes,
7065 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7066 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007067 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7068 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007069 ((volumeSource == alarmVolumeSrc ||
7070 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007071 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7072 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7073 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007074 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7075 curves.canBeMuted()) {
7076
Eric Laurente552edb2014-03-10 17:42:56 -07007077 // when the phone is ringing we must consider that music could have been paused just before
7078 // by the music application and behave as if music was active if the last music track was
7079 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007080 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007081 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007082 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007083 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007084 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7085 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007086 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007087 float musicVolDb = computeVolume(musicCurves,
7088 musicVolumeSrc,
7089 musicCurves.getVolumeIndex(musicDevice),
7090 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007091 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7092 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7093 if (volumeDb > minVolDb) {
7094 volumeDb = minVolDb;
7095 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007096 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007097 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7098 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7099 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007100 // on A2DP, also ensure notification volume is not too low compared to media when
7101 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007102 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007103 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007104 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7105 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007106 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7107 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007108 }
7109 }
jiabin9a3361e2019-10-01 09:38:30 -07007110 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007111 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007112 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007113 }
7114 }
7115
François Gaffie43c73442018-11-08 08:21:55 +01007116 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007117}
7118
Eric Laurent3839bc02018-07-10 18:33:34 -07007119int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007120 VolumeSource fromVolumeSource,
7121 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007122{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007123 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007124 return srcIndex;
7125 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007126 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7127 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007128 float minSrc = (float)srcCurves.getVolumeIndexMin();
7129 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7130 float minDst = (float)dstCurves.getVolumeIndexMin();
7131 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007132
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007133 // preserve mute request or correct range
7134 if (srcIndex < minSrc) {
7135 if (srcIndex == 0) {
7136 return 0;
7137 }
7138 srcIndex = minSrc;
7139 } else if (srcIndex > maxSrc) {
7140 srcIndex = maxSrc;
7141 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007142 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7143}
7144
François Gaffieaaac0fd2018-11-22 17:56:39 +01007145status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7146 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007147 int index,
7148 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007149 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007150 int delayMs,
7151 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007152{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007153 // do not change actual attributes volume if the attributes is muted
7154 if (outputDesc->isMuted(volumeSource)) {
7155 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7156 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007157 return NO_ERROR;
7158 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007159 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7160 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7161 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7162 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007163
Eric Laurent2517af32020-11-25 15:31:27 +01007164 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007165 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007166 // if sco and call follow same curves, bypass forceUseForComm
7167 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007168 ((isVoiceVolSrc && isScoRequested) ||
7169 (isBtScoVolSrc && !isScoRequested))) {
7170 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7171 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007172 // Do not return an error here as AudioService will always set both voice call
7173 // and bluetooth SCO volumes due to stream aliasing.
7174 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007175 }
jiabin9a3361e2019-10-01 09:38:30 -07007176 if (deviceTypes.empty()) {
7177 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007178 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007179
jiabin9a3361e2019-10-01 09:38:30 -07007180 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7181 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007182 // Force VoIP volume to max for bluetooth SCO device except if muted
7183 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007184 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007185 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007186 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007187 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007188 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007189 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007190
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007191 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007192 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007193 // 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 +01007194 if (isVoiceVolSrc) {
7195 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007196 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007197 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007198 }
Eric Laurent18fba842016-03-31 14:41:26 -07007199 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007200 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7201 mLastVoiceVolume = voiceVolume;
7202 }
7203 }
Eric Laurente552edb2014-03-10 17:42:56 -07007204 return NO_ERROR;
7205}
7206
Eric Laurentc75307b2015-03-17 15:29:32 -07007207void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007208 const DeviceTypeSet& deviceTypes,
7209 int delayMs,
7210 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007211{
jiabincd510522020-01-22 09:40:55 -08007212 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007213 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7214 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7215 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007216 curves.getVolumeIndex(deviceTypes),
7217 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007218 }
7219}
7220
François Gaffiec005e562018-11-06 15:04:49 +01007221void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7222 bool on,
7223 const sp<AudioOutputDescriptor>& outputDesc,
7224 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007225 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007226{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007227 std::vector<VolumeSource> sourcesToMute;
7228 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7229 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7230 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007231 VolumeSource source = toVolumeSource(attributes, false);
7232 if ((source != VOLUME_SOURCE_NONE) &&
7233 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7234 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007235 sourcesToMute.push_back(source);
7236 }
Eric Laurente552edb2014-03-10 17:42:56 -07007237 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007238 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007239 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007240 }
7241
Eric Laurente552edb2014-03-10 17:42:56 -07007242}
7243
François Gaffieaaac0fd2018-11-22 17:56:39 +01007244void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7245 bool on,
7246 const sp<AudioOutputDescriptor>& outputDesc,
7247 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007248 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007249{
jiabin9a3361e2019-10-01 09:38:30 -07007250 if (deviceTypes.empty()) {
7251 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007252 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007253 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007254 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007255 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007256 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007257 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007258 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7259 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007260 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007261 }
7262 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007263 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7264 // ignored
7265 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007266 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007267 if (!outputDesc->isMuted(volumeSource)) {
7268 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007269 return;
7270 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007271 if (outputDesc->decMuteCount(volumeSource) == 0) {
7272 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007273 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007274 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007275 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007276 delayMs);
7277 }
7278 }
7279}
7280
François Gaffie53615e22015-03-19 09:24:12 +01007281bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7282{
François Gaffiec005e562018-11-06 15:04:49 +01007283 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007284 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7285 return true;
7286 }
7287
7288 // has known usage?
7289 switch (paa->usage) {
7290 case AUDIO_USAGE_UNKNOWN:
7291 case AUDIO_USAGE_MEDIA:
7292 case AUDIO_USAGE_VOICE_COMMUNICATION:
7293 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7294 case AUDIO_USAGE_ALARM:
7295 case AUDIO_USAGE_NOTIFICATION:
7296 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7297 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7298 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7299 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7300 case AUDIO_USAGE_NOTIFICATION_EVENT:
7301 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7302 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7303 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7304 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007305 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007306 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007307 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007308 case AUDIO_USAGE_EMERGENCY:
7309 case AUDIO_USAGE_SAFETY:
7310 case AUDIO_USAGE_VEHICLE_STATUS:
7311 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007312 break;
7313 default:
7314 return false;
7315 }
7316 return true;
7317}
7318
François Gaffie2110e042015-03-24 08:41:51 +01007319audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7320{
7321 return mEngine->getForceUse(usage);
7322}
7323
7324bool AudioPolicyManager::isInCall()
7325{
7326 return isStateInCall(mEngine->getPhoneState());
7327}
7328
7329bool AudioPolicyManager::isStateInCall(int state)
7330{
7331 return is_state_in_call(state);
7332}
7333
Eric Laurent74b71512019-11-06 17:21:57 -08007334bool AudioPolicyManager::isCallAudioAccessible()
7335{
7336 audio_mode_t mode = mEngine->getPhoneState();
7337 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007338 || (mode == AUDIO_MODE_CALL_SCREEN)
7339 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007340}
7341
Eric Laurentd60560a2015-04-10 11:31:20 -07007342void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7343{
7344 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007345 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007346 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007347 sourceDesc->sinkDevice()->equals(deviceDesc))
7348 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007349 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007350 }
7351 }
7352
7353 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7354 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7355 bool release = false;
7356 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7357 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7358 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7359 source->ext.device.type == deviceDesc->type()) {
7360 release = true;
7361 }
7362 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007363 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007364 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7365 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7366 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007367 sink->ext.device.type == deviceDesc->type() &&
7368 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7369 || strncmp(sink->ext.device.address, address,
7370 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007371 release = true;
7372 }
7373 }
7374 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007375 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7376 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007377 }
7378 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007379
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007380 mInputs.clearSessionRoutesForDevice(deviceDesc);
7381
Francois Gaffie716e1432019-01-14 16:58:59 +01007382 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007383}
7384
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007385void AudioPolicyManager::modifySurroundFormats(
7386 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007387 std::unordered_set<audio_format_t> enforcedSurround(
7388 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007389 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7390 for (const auto& pair : mConfig.getSurroundFormats()) {
7391 allSurround.insert(pair.first);
7392 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7393 }
Phil Burk09bc4612016-02-24 15:58:15 -08007394
7395 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7396 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007397 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007398 // This is the resulting set of formats depending on the surround mode:
7399 // 'all surround' = allSurround
7400 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7401 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7402 // 'manual surround' = mManualSurroundFormats
7403 // AUTO: formats v 'enforced surround'
7404 // ALWAYS: formats v 'all surround' v 'enforced surround'
7405 // NEVER: formats ^ 'non-surround'
7406 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007407
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007408 std::unordered_set<audio_format_t> formatSet;
7409 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7410 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007411 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007412 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007413 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007414 formatSet.insert(*formatIter);
7415 }
7416 }
7417 } else {
7418 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7419 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007420 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007421
jiabin81772902018-04-02 17:52:27 -07007422 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007423 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007424 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7425 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7426 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007427 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007428 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7429 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7430 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007431 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007432 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007433 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007434 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007435 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007436 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007437}
7438
jiabin06e4bab2019-07-29 10:13:34 -07007439void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7440 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007441 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7442 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7443
7444 // If NEVER, then remove support for channelMasks > stereo.
7445 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007446 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7447 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007448 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007449 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007450 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007451 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007452 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007453 }
7454 }
jiabin81772902018-04-02 17:52:27 -07007455 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7456 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7457 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007458 bool supports5dot1 = false;
7459 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007460 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007461 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7462 supports5dot1 = true;
7463 break;
7464 }
7465 }
7466 // If not then add 5.1 support.
7467 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007468 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007469 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007470 }
Phil Burk09bc4612016-02-24 15:58:15 -08007471 }
7472}
7473
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007474void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007475 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007476 AudioProfileVector &profiles)
7477{
7478 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007479 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007480
François Gaffie112b0af2015-11-19 16:13:25 +01007481 // Format MUST be checked first to update the list of AudioProfile
7482 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007483 reply = mpClientInterface->getParameters(
7484 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007485 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007486 AudioParameter repliedParameters(reply);
7487 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007488 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007489 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7490 return;
7491 }
Phil Burk09bc4612016-02-24 15:58:15 -08007492 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007493 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007494 if (device == AUDIO_DEVICE_OUT_HDMI
7495 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007496 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007497 }
jiabin3e277cc2019-09-10 14:27:34 -07007498 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007499 }
François Gaffie112b0af2015-11-19 16:13:25 +01007500
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007501 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007502 ChannelMaskSet channelMasks;
7503 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007504 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007505 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007506
7507 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007508 reply = mpClientInterface->getParameters(
7509 ioHandle,
7510 requestedParameters.toString() + ";" +
7511 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007512 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007513 AudioParameter repliedParameters(reply);
7514 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007515 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007516 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007517 }
7518 }
7519 if (profiles.hasDynamicChannelsFor(format)) {
7520 reply = mpClientInterface->getParameters(ioHandle,
7521 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007522 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007523 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007524 AudioParameter repliedParameters(reply);
7525 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007526 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007527 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007528 if (device == AUDIO_DEVICE_OUT_HDMI
7529 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007530 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007531 }
François Gaffie112b0af2015-11-19 16:13:25 +01007532 }
7533 }
jiabin3e277cc2019-09-10 14:27:34 -07007534 addDynamicAudioProfileAndSort(
7535 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007536 }
7537}
Eric Laurentd60560a2015-04-10 11:31:20 -07007538
Mikhail Naganovdc769682018-05-04 15:34:08 -07007539status_t AudioPolicyManager::installPatch(const char *caller,
7540 audio_patch_handle_t *patchHandle,
7541 AudioIODescriptorInterface *ioDescriptor,
7542 const struct audio_patch *patch,
7543 int delayMs)
7544{
7545 ssize_t index = mAudioPatches.indexOfKey(
7546 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7547 *patchHandle : ioDescriptor->getPatchHandle());
7548 sp<AudioPatch> patchDesc;
7549 status_t status = installPatch(
7550 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7551 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007552 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007553 }
7554 return status;
7555}
7556
7557status_t AudioPolicyManager::installPatch(const char *caller,
7558 ssize_t index,
7559 audio_patch_handle_t *patchHandle,
7560 const struct audio_patch *patch,
7561 int delayMs,
7562 uid_t uid,
7563 sp<AudioPatch> *patchDescPtr)
7564{
7565 sp<AudioPatch> patchDesc;
7566 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7567 if (index >= 0) {
7568 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007569 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007570 }
7571
7572 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7573 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7574 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7575 if (status == NO_ERROR) {
7576 if (index < 0) {
7577 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007578 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007579 } else {
7580 patchDesc->mPatch = *patch;
7581 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007582 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007583 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007584 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007585 }
7586 nextAudioPortGeneration();
7587 mpClientInterface->onAudioPatchListUpdate();
7588 }
7589 if (patchDescPtr) *patchDescPtr = patchDesc;
7590 return status;
7591}
7592
jiabinbce0c1d2020-10-05 11:20:18 -07007593bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7594{
7595 const TrackClientVector activeClients = output->getActiveClients();
7596 if (activeClients.empty()) {
7597 return true;
7598 }
7599 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7600 if (index < 0) {
7601 ALOGE("%s, no audio patch found while there are active clients on output %d",
7602 __func__, output->getId());
7603 return false;
7604 }
7605 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7606 DeviceVector routedDevices;
7607 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7608 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7609 patchDesc->mPatch.sinks[i].id);
7610 if (device == nullptr) {
7611 ALOGE("%s, no audio device found with id(%d)",
7612 __func__, patchDesc->mPatch.sinks[i].id);
7613 return false;
7614 }
7615 routedDevices.add(device);
7616 }
7617 for (const auto& client : activeClients) {
7618 // TODO: b/175343099 only travel the valid client
7619 sp<DeviceDescriptor> preferredDevice =
7620 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7621 if (mEngine->getOutputDevicesForAttributes(
7622 client->attributes(), preferredDevice, false) == routedDevices) {
7623 return false;
7624 }
7625 }
7626 return true;
7627}
7628
7629sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007630 const sp<IOProfile>& profile, const DeviceVector& devices,
7631 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007632{
7633 for (const auto& device : devices) {
7634 // TODO: This should be checking if the profile supports the device combo.
7635 if (!profile->supportsDevice(device)) {
7636 return nullptr;
7637 }
7638 }
7639 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7640 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007641 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007642 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7643 if (status != NO_ERROR) {
7644 return nullptr;
7645 }
7646
7647 // Here is where the out_set_parameters() for card & device gets called
7648 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7649 const audio_devices_t deviceType = device->type();
7650 const String8 &address = String8(device->address().c_str());
7651 if (!address.isEmpty()) {
7652 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7653 mpClientInterface->setParameters(output, String8(param));
7654 free(param);
7655 }
7656 updateAudioProfiles(device, output, profile->getAudioProfiles());
7657 if (!profile->hasValidAudioProfile()) {
7658 ALOGW("%s() missing param", __func__);
7659 desc->close();
7660 return nullptr;
7661 } else if (profile->hasDynamicAudioProfile()) {
7662 desc->close();
7663 output = AUDIO_IO_HANDLE_NONE;
7664 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7665 profile->pickAudioProfile(
7666 config.sample_rate, config.channel_mask, config.format);
7667 config.offload_info.sample_rate = config.sample_rate;
7668 config.offload_info.channel_mask = config.channel_mask;
7669 config.offload_info.format = config.format;
7670
Eric Laurentb4f42a92022-01-17 17:37:31 +01007671 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007672 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7673 if (status != NO_ERROR) {
7674 return nullptr;
7675 }
7676 }
7677
7678 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007679
jiabinbce0c1d2020-10-05 11:20:18 -07007680 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7681 sp<AudioPolicyMix> policyMix;
7682 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7683 policyMix->setOutput(desc);
7684 desc->mPolicyMix = policyMix;
7685 } else {
7686 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7687 address.string());
7688 }
7689
Eric Laurentb4f42a92022-01-17 17:37:31 +01007690 } else if (hasPrimaryOutput() && profile->getModule()
7691 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7692 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7693 // no duplicated output for:
7694 // - direct outputs
7695 // - outputs used by dynamic policy mixes
7696 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007697 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7698
7699 //TODO: configure audio effect output stage here
7700
7701 // open a duplicating output thread for the new output and the primary output
7702 sp<SwAudioOutputDescriptor> dupOutputDesc =
7703 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7704 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7705 if (status == NO_ERROR) {
7706 // add duplicated output descriptor
7707 addOutput(duplicatedOutput, dupOutputDesc);
7708 } else {
7709 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7710 mPrimaryOutput->mIoHandle, output);
7711 desc->close();
7712 removeOutput(output);
7713 nextAudioPortGeneration();
7714 return nullptr;
7715 }
7716 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007717 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7718 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7719 mPrimaryOutput = desc;
7720 }
jiabinbce0c1d2020-10-05 11:20:18 -07007721 return desc;
7722}
7723
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007724} // namespace android